repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
davisd50/sparc.cache
sparc/cache/splunk/area.py
CacheAreaForSplunkKV.cache
python
def cache(self, CachableItem): _cachedItem = self.get(CachableItem) if not _cachedItem: _cachedItem = self.mapper.get(CachableItem) self._add(_cachedItem) logger.debug("new cachable item added to Splunk KV cache area {id: %s, type: %s}", str(_cachedItem.getId()), str(...
Updates caches area with latest item information returning ICachedItem if cache updates were required. Issues ICacheObjectCreatedEvent, and ICacheObjectModifiedEvent for ICacheArea/ICachableItem combo.
train
https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/splunk/area.py#L117-L138
[ "def _add(self, CachedItem):\n r = self.request('post',\n self.url+\"storage/collections/data/\"+self.collname, \n headers={'Content-Type': 'application/json'}, \n data=json.dumps(self._data(CachedItem)))\n r.raise_for_status()\n", "def _update(sel...
class CacheAreaForSplunkKV(object): """An area where cached information can be stored persistently.""" implements(ITrimmableCacheArea) adapts(sparc.cache.ICachedItemMapper, sparc.db.splunk.ISplunkKVCollectionSchema, sparc.db.splunk.ISplunkConnectionInfo, sparc.db.splunk.ISPl...
davisd50/sparc.cache
sparc/cache/splunk/area.py
CacheAreaForSplunkKV.import_source
python
def import_source(self, CachableSource): _count = 0 self._import_source_items_id_list = set() # used to help speed up trim() for item in CachableSource.items(): self._import_source_items_id_list.add(item.getId()) if self.cache(item): _count += 1 re...
Updates cache area and returns number of items updated with all available entries in ICachableSource
train
https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/splunk/area.py#L140-L150
[ "def cache(self, CachableItem):\n \"\"\"Updates caches area with latest item information returning\n ICachedItem if cache updates were required.\n\n Issues ICacheObjectCreatedEvent, and ICacheObjectModifiedEvent for\n ICacheArea/ICachableItem combo.\n \"\"\"\n _cachedItem = self.get(Cacha...
class CacheAreaForSplunkKV(object): """An area where cached information can be stored persistently.""" implements(ITrimmableCacheArea) adapts(sparc.cache.ICachedItemMapper, sparc.db.splunk.ISplunkKVCollectionSchema, sparc.db.splunk.ISplunkConnectionInfo, sparc.db.splunk.ISPl...
davisd50/sparc.cache
sparc/cache/splunk/area.py
CacheAreaForSplunkKV.reset
python
def reset(self): if self.collname not in self.current_kv_names(): return # nothing to do # we'll simply delete the entire collection and then re-create it. r = self.request('delete', self.url+"storage/collections/data/"+self.collname) r.raise_for_stat...
Deletes all entries in the cache area
train
https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/splunk/area.py#L152-L160
[ "def current_kv_names(self):\n \"\"\"Return set of string names of current available Splunk KV collections\"\"\"\n return current_kv_names(self.sci, self.username, self.appname, request=self._request)\n", "def request(self, *args, **kwargs):\n return self._request.request(*args, **kwargs)\n", "def init...
class CacheAreaForSplunkKV(object): """An area where cached information can be stored persistently.""" implements(ITrimmableCacheArea) adapts(sparc.cache.ICachedItemMapper, sparc.db.splunk.ISplunkKVCollectionSchema, sparc.db.splunk.ISplunkConnectionInfo, sparc.db.splunk.ISPl...
davisd50/sparc.cache
sparc/cache/splunk/area.py
CacheAreaForSplunkKV.initialize
python
def initialize(self): if self.collname not in self.current_kv_names(): r = self.request('post', self.url+"storage/collections/config", headers={'content-type': 'application/json'}, data={'name': self.collname}) ...
Instantiates the cache area to be ready for updates
train
https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/splunk/area.py#L162-L179
[ "def current_kv_names(self):\n \"\"\"Return set of string names of current available Splunk KV collections\"\"\"\n return current_kv_names(self.sci, self.username, self.appname, request=self._request)\n", "def request(self, *args, **kwargs):\n return self._request.request(*args, **kwargs)\n" ]
class CacheAreaForSplunkKV(object): """An area where cached information can be stored persistently.""" implements(ITrimmableCacheArea) adapts(sparc.cache.ICachedItemMapper, sparc.db.splunk.ISplunkKVCollectionSchema, sparc.db.splunk.ISplunkConnectionInfo, sparc.db.splunk.ISPl...
ScienceLogic/amiuploader
amiimporter/amiupload.py
parse_args
python
def parse_args(): parser = argparse.ArgumentParser(description="Uploads specified VMDK file to AWS s3 bucket, and converts to AMI") parser.add_argument('-r', '--aws_regions', type=str, nargs='+', required=True, help='list of AWS regions where uploaded ami should be copied. Available' ...
Argument parser and validator
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/amiupload.py#L17-L41
[ "def validate_args(args):\n \"\"\"\n Perform necessary validation checks\n :param args:\n :return:\n \"\"\"\n # print size of vm to be dl, if dl dir exists, check that file to uplad is a vmdk\n if not os.path.isdir(args.directory):\n print \"Directory {} does not exist\".format(args.dire...
#!/usr/bin/python import argparse import os import sys import tempfile import AWSUtilities # TODO: Add licensing # arg validation # pypi packaging info # requirements # readmes def validate_args(args): """ Perform necessary validation checks :param args: :return: """ # print size of vm to ...
ScienceLogic/amiuploader
amiimporter/amiupload.py
validate_args
python
def validate_args(args): # print size of vm to be dl, if dl dir exists, check that file to uplad is a vmdk if not os.path.isdir(args.directory): print "Directory {} does not exist".format(args.directory) sys.exit(5) try: args.vmdk_upload_file = args.vmdk_upload_file except Attri...
Perform necessary validation checks :param args: :return:
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/amiupload.py#L44-L66
[ "def validate(self):\n \"\"\"\n Call instance validation methods\n :return:\n \"\"\"\n self.validate_regions()\n self.validate_bucket()\n self.validate_ec2_action()\n" ]
#!/usr/bin/python import argparse import os import sys import tempfile import AWSUtilities # TODO: Add licensing # arg validation # pypi packaging info # requirements # readmes def parse_args(): """ Argument parser and validator """ parser = argparse.ArgumentParser(description="Uploads specified VM...
ScienceLogic/amiuploader
amiimporter/amiupload.py
vmdk_to_ami
python
def vmdk_to_ami(args): aws_importer = AWSUtilities.AWSUtils(args.directory, args.aws_profile, args.s3_bucket, args.aws_regions, args.ami_name, args.vmdk_upload_file) aws_importer.import_vmdk()
Calls methods to perform vmdk import :param args: :return:
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/amiupload.py#L69-L77
[ "def import_vmdk(self):\n \"\"\"\n All actions necessary to import vmdk (calls s3 upload, and import to aws ec2)\n :param vmdk_location: location of vmdk to import. Can be provided as a string, or the result output of fabric\n execution\n :return:\n \"\"\"\n # Set the inital upload to be the fi...
#!/usr/bin/python import argparse import os import sys import tempfile import AWSUtilities # TODO: Add licensing # arg validation # pypi packaging info # requirements # readmes def parse_args(): """ Argument parser and validator """ parser = argparse.ArgumentParser(description="Uploads specified VM...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
parse_image_json
python
def parse_image_json(text): image_details = json.loads(text) if image_details.get('Images') is not None: try: image_details = image_details.get('Images')[0] except IndexError: image_details = None return image_details
parses response output of AWS describe commands and returns the first (and only) item in array :param text: describe output :return: image json
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L12-L24
null
import sys import tempfile import os import shlex import subprocess import json import time aws_regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-west-1', 'eu-central-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-2', 'ap-south-1', 'sa-east-1'] clas...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.validate_regions
python
def validate_regions(self): for region in self.aws_regions: if region not in aws_regions: print "Error: Specified region: {} is not a valid aws_region".format(region) print "Valid regions are: {}".format(aws_regions)
Validate the user specified regions are valid :return:
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L54-L62
null
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.validate_ec2_action
python
def validate_ec2_action(self): import_cmd = 'aws ec2 import-image --dry-run --profile {} --region {}'\ .format(self.aws_project, self.aws_regions[0]) print "Attempting ec2 import dry run: {}".format(import_cmd) try: subprocess.check_output(shlex.split(import_cmd), stderr=...
Attempt to validate that the provided user has permissions to import an AMI :return:
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L64-L81
null
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.validate_bucket
python
def validate_bucket(self): s3_check_cmd = "aws s3 ls s3://{} --profile '{}' --region '{}'".format(self.bucket_name, self.aws_project, self.aws_regions[0]) print "Checking for s3 bucket" try: subprocess.che...
Do a quick check to see if the s3 bucket is valid :return:
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L83-L97
null
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.get_image_id_by_name
python
def get_image_id_by_name(self, ami_name, region='us-east-1'): image_details = None detail_query_attempts = 0 while image_details is None: describe_cmd = "aws ec2 describe-images --filters 'Name=name,Values={}' --profile '{}' --region {}"\ .format(ami_name, self.aws_p...
Locate an AMI image id by name in a particular region :param ami_name: ami name you need the id for :param region: the region the image exists in :return: id of the image
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L99-L127
[ "def parse_image_json(text):\n \"\"\"\n parses response output of AWS describe commands and returns the first (and only) item in array\n :param text: describe output\n :return: image json\n \"\"\"\n image_details = json.loads(text)\n if image_details.get('Images') is not None:\n try:\n ...
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.copy_ami_to_new_name
python
def copy_ami_to_new_name(self, ami_id, new_name, source_region='us-east-1'): new_image_ids = [] for region in self.aws_regions: copy_img_cmd = "aws ec2 copy-image --source-image-id {} --profile {} --source-region {} --region {} --name {}"\ .format(ami_id, self.aws_project, ...
Copies an AMI from the default region and name to the desired name and region :param ami_id: ami id to copy :param new_name: name of the new ami to create :param source_region: the source region of the ami to copy
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L129-L155
[ "def wait_for_copy_available(self, image_id, region):\n \"\"\"\n Wait for the newly copied ami to become available\n :param image_id: image id to monitor\n :param region: region to monitor copy\n \"\"\"\n waiting = True\n\n describe_image_cmd = \"aws ec2 --profile {} --region {} --output json d...
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.deregister_image
python
def deregister_image(self, ami_id, region='us-east-1'): deregister_cmd = "aws ec2 --profile {} --region {} deregister-image --image-id {}"\ .format(self.aws_project, region, ami_id) print "De-registering old image, now that the new one exists." print "De-registering cmd: {}".format(d...
Deregister an AMI by id :param ami_id: :param region: region to deregister from :return:
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L157-L170
null
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.wait_for_copy_available
python
def wait_for_copy_available(self, image_id, region): waiting = True describe_image_cmd = "aws ec2 --profile {} --region {} --output json describe-images --image-id {}"\ .format(self.aws_project, region, image_id) while waiting: res = subprocess.check_output(shlex.split(d...
Wait for the newly copied ami to become available :param image_id: image id to monitor :param region: region to monitor copy
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L172-L196
[ "def parse_image_json(text):\n \"\"\"\n parses response output of AWS describe commands and returns the first (and only) item in array\n :param text: describe output\n :return: image json\n \"\"\"\n image_details = json.loads(text)\n if image_details.get('Images') is not None:\n try:\n ...
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.rename_image
python
def rename_image(self, ami_name, new_ami_name, source_region='us-east-1'): print "Re-naming/moving AMI to desired name and region" image_id = self.get_image_id_by_name(ami_name, source_region) self.copy_ami_to_new_name(image_id, new_ami_name, source_region) self.deregister_image(image_id...
Method which renames an ami by copying to a new ami with a new name (only way this is possible in AWS) :param ami_name: :param new_ami_name: :return:
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L198-L208
[ "def get_image_id_by_name(self, ami_name, region='us-east-1'):\n \"\"\"\n Locate an AMI image id by name in a particular region\n :param ami_name: ami name you need the id for\n :param region: the region the image exists in\n :return: id of the image\n \"\"\"\n image_details = None\n detail_...
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.create_config_file
python
def create_config_file(self, vmdk_location, description): description = description format = "vmdk" user_bucket = { "S3Bucket": self.bucket_name, "S3Key": vmdk_location } parent_obj = {'Description': description, 'Format': format, 'UserBucket': user_bucket...
Create the aws import config file :param vmdk_location: location of downloaded VMDK :param description: description to use for config_file creation :return: config file descriptor, config file full path
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L210-L231
null
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.run_ec2_import
python
def run_ec2_import(self, config_file_location, description, region='us-east-1'): import_cmd = "aws ec2 import-image --description '{}' --profile '{}' --region '{}' --output 'json'" \ " --disk-containers file://{}"\ .format(description, self.aws_project, region, config_file_locat...
Runs the command to import an uploaded vmdk to aws ec2 :param config_file_location: config file of import param location :param description: description to attach to the import task :return: the import task id for the given ami
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L233-L253
[ "def check_task_status_and_id(task_json):\n \"\"\"\n Read status of import json and parse\n :param task_json: status json to parse\n :return: (stillRunning, imageId)\n \"\"\"\n if task_json.get('ImportImageTasks') is not None:\n task = task_json['ImportImageTasks'][0]\n else:\n ta...
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.upload_to_s3
python
def upload_to_s3(self, region='us-east-1'): s3_import_cmd = "aws s3 cp {} s3://{} --profile '{}' --region {}".format(self.upload_file, self.bucket_name, self.aws_project, region) print "Uploading to bucket {} in s3 with the...
Uploads the vmdk file to aws s3 :param file_location: location of vmdk :return:
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L255-L275
null
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.wait_for_import_to_complete
python
def wait_for_import_to_complete(self, import_id, region='us-east-1'): task_running = True while task_running: import_status_cmd = "aws ec2 --profile {} --region '{}' --output 'json' describe-import-image-tasks --import-task-ids {}".format(self.aws_project, region, import_id) res...
Monitors the status of aws import, waiting for it to complete, or error out :param import_id: id of import task to monitor
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L277-L288
[ "def check_task_status_and_id(task_json):\n \"\"\"\n Read status of import json and parse\n :param task_json: status json to parse\n :return: (stillRunning, imageId)\n \"\"\"\n if task_json.get('ImportImageTasks') is not None:\n task = task_json['ImportImageTasks'][0]\n else:\n ta...
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.check_task_status_and_id
python
def check_task_status_and_id(task_json): if task_json.get('ImportImageTasks') is not None: task = task_json['ImportImageTasks'][0] else: task = task_json current_status = task['Status'] image_id = task['ImportTaskId'] if current_status == 'completed': ...
Read status of import json and parse :param task_json: status json to parse :return: (stillRunning, imageId)
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L291-L317
null
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.import_vmdk
python
def import_vmdk(self): # Set the inital upload to be the first region in the list first_upload_region = self.aws_regions[0] print "Initial AMI will be created in: {}".format(first_upload_region) self.upload_to_s3(region=first_upload_region) # If the upload was successful, the na...
All actions necessary to import vmdk (calls s3 upload, and import to aws ec2) :param vmdk_location: location of vmdk to import. Can be provided as a string, or the result output of fabric execution :return:
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L319-L337
[ "def rename_image(self, ami_name, new_ami_name, source_region='us-east-1'):\n \"\"\"\n Method which renames an ami by copying to a new ami with a new name (only way this is possible in AWS)\n :param ami_name:\n :param new_ami_name:\n :return:\n \"\"\"\n print \"Re-naming/moving AMI to desired n...
class AWSUtils: """ Methods necessary to perform VM imports """ def __init__(self, config_save_dir, aws_profile, bucket, regions, ami_name, upload_file): """ Instantiate with common properties for all VM imports to AWS :param config_save_dir: where to save aws config files :para...
rgmining/ria
ria/one.py
BipartiteGraph.update
python
def update(self): if self.updated: return 0 res = super(BipartiteGraph, self).update() self.updated = True return res
Update reviewers' anomalous scores and products' summaries. Returns: maximum absolute difference between old summary and new one, and old anomalous score and new one.
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/one.py#L43-L55
[ "def update(self):\n \"\"\"Update reviewers' anomalous scores and products' summaries.\n\n Returns:\n maximum absolute difference between old summary and new one, and\n old anomalous score and new one.\n \"\"\"\n w = self._weight_generator(self.reviewers)\n diff_p = max(p.update_summary(w) ...
class BipartiteGraph(bipartite.BipartiteGraph): """Bipartite graph implementing One algorithm. Attributes: updated: Whether :meth:`update` has been called. If True, that method does nothing. """ def __init__(self, **kwargs): super(BipartiteGraph, self).__init__(**kwargs) ...
rgmining/ria
ria/bipartite.py
Reviewer.anomalous_score
python
def anomalous_score(self): return self._anomalous if self._anomalous else 1. / len(self._graph.reviewers)
Anomalous score of this reviewer. Initial anomalous score is :math:`1 / |R|` where :math:`R` is a set of reviewers.
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L151-L157
null
class Reviewer(_Node): """A node class representing Reviewer. Args: graph: an instance of BipartiteGraph representing the parent graph. credibility: an instance of credibility.Credibility to be used to update scores. name: name of this node. (default: None) anomalous: initial an...
rgmining/ria
ria/bipartite.py
Reviewer.update_anomalous_score
python
def update_anomalous_score(self): products = self._graph.retrieve_products(self) diffs = [ p.summary.difference(self._graph.retrieve_review(self, p)) for p in products ] old = self.anomalous_score try: self.anomalous_score = np.average( ...
Update anomalous score. New anomalous score is a weighted average of differences between current summary and reviews. The weights come from credibilities. Therefore, the new anomalous score of reviewer :math:`p` is as .. math:: {\\rm anomalous}(r) = \\frac{ \\...
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L168-L206
null
class Reviewer(_Node): """A node class representing Reviewer. Args: graph: an instance of BipartiteGraph representing the parent graph. credibility: an instance of credibility.Credibility to be used to update scores. name: name of this node. (default: None) anomalous: initial an...
rgmining/ria
ria/bipartite.py
Product.summary
python
def summary(self): if self._summary: return self._summary reviewers = self._graph.retrieve_reviewers(self) return self._summary_cls( [self._graph.retrieve_review(r, self) for r in reviewers])
Summary of reviews for this product. Initial summary is computed by .. math:: \\frac{1}{|R|} \\sum_{r \\in R} \\mbox{review}(r), where :math:`\\mbox{review}(r)` means review from reviewer :math:`r`.
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L226-L242
null
class Product(_Node): """A node class representing Product. Args: graph: An instance of BipartiteGraph representing the parent graph. name: Name of this node. (default: None) summary_cls: Specify summary type. (default: AverageSummary) """ __slots__ = ("_summary", "_summary_cls") ...
rgmining/ria
ria/bipartite.py
Product.summary
python
def summary(self, v): if hasattr(v, "__iter__"): self._summary = self._summary_cls(v) else: self._summary = self._summary_cls(float(v))
Set summary. Args: v: A new summary. It could be a single number or lists.
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L245-L254
null
class Product(_Node): """A node class representing Product. Args: graph: An instance of BipartiteGraph representing the parent graph. name: Name of this node. (default: None) summary_cls: Specify summary type. (default: AverageSummary) """ __slots__ = ("_summary", "_summary_cls") ...
rgmining/ria
ria/bipartite.py
Product.update_summary
python
def update_summary(self, w): old = self.summary.v # pylint: disable=no-member reviewers = self._graph.retrieve_reviewers(self) reviews = [self._graph.retrieve_review( r, self).score for r in reviewers] weights = [w(r.anomalous_score) for r in reviewers] if sum(weigh...
Update summary. The new summary is a weighted average of reviews i.e. .. math:: \\frac{\\sum_{r \\in R} \\mbox{weight}(r) \\times \\mbox{review}(r)} {\\sum_{r \\in R} \\mbox{weight}(r)}, where :math:`R` is a set of reviewers reviewing this product, :math:`...
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L256-L286
null
class Product(_Node): """A node class representing Product. Args: graph: An instance of BipartiteGraph representing the parent graph. name: Name of this node. (default: None) summary_cls: Specify summary type. (default: AverageSummary) """ __slots__ = ("_summary", "_summary_cls") ...
rgmining/ria
ria/bipartite.py
BipartiteGraph.new_reviewer
python
def new_reviewer(self, name, anomalous=None): n = self._reviewer_cls( self, name=name, credibility=self.credibility, anomalous=anomalous) self.graph.add_node(n) self.reviewers.append(n) return n
Create a new reviewer. Args: name: name of the new reviewer. anomalous: initial anomalous score. (default: None) Returns: A new reviewer instance.
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L333-L347
null
class BipartiteGraph(object): """Bipartite graph model for review data mining. Args: summary_type: specify summary type class, default value is AverageSummary. alpha: used to compute weight of anomalous scores, default value is 1. credibility: credibility class to be used in this graph. ...
rgmining/ria
ria/bipartite.py
BipartiteGraph.new_product
python
def new_product(self, name): n = self._product_cls(self, name, summary_cls=self._summary_cls) self.graph.add_node(n) self.products.append(n) return n
Create a new product. Args: name: name of the new product. Returns: A new product instance.
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L349-L361
null
class BipartiteGraph(object): """Bipartite graph model for review data mining. Args: summary_type: specify summary type class, default value is AverageSummary. alpha: used to compute weight of anomalous scores, default value is 1. credibility: credibility class to be used in this graph. ...
rgmining/ria
ria/bipartite.py
BipartiteGraph.add_review
python
def add_review(self, reviewer, product, review, date=None): if not isinstance(reviewer, self._reviewer_cls): raise TypeError( "Type of given reviewer isn't acceptable:", reviewer, ", expected:", self._reviewer_cls) elif not isinstance(product, self._product_cl...
Add a new review from a given reviewer to a given product. Args: reviewer: an instance of Reviewer. product: an instance of Product. review: a float value. date: date the review issued. Returns: the added new review object. Raises: T...
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L363-L389
null
class BipartiteGraph(object): """Bipartite graph model for review data mining. Args: summary_type: specify summary type class, default value is AverageSummary. alpha: used to compute weight of anomalous scores, default value is 1. credibility: credibility class to be used in this graph. ...
rgmining/ria
ria/bipartite.py
BipartiteGraph.retrieve_products
python
def retrieve_products(self, reviewer): if not isinstance(reviewer, self._reviewer_cls): raise TypeError( "Type of given reviewer isn't acceptable:", reviewer, ", expected:", self._reviewer_cls) return list(self.graph.successors(reviewer))
Retrieve products reviewed by a given reviewer. Args: reviewer: A reviewer. Returns: A list of products which the reviewer reviews. Raises: TypeError: when given reviewer isn't instance of specified reviewer class when this graph is constructed.
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L392-L409
null
class BipartiteGraph(object): """Bipartite graph model for review data mining. Args: summary_type: specify summary type class, default value is AverageSummary. alpha: used to compute weight of anomalous scores, default value is 1. credibility: credibility class to be used in this graph. ...
rgmining/ria
ria/bipartite.py
BipartiteGraph.retrieve_reviewers
python
def retrieve_reviewers(self, product): if not isinstance(product, self._product_cls): raise TypeError( "Type of given product isn't acceptable:", product, ", expected:", self._product_cls) return list(self.graph.predecessors(product))
Retrieve reviewers who reviewed a given product. Args: product: A product specifying reviewers. Returns: A list of reviewers who review the product. Raises: TypeError: when given product isn't instance of specified product class when this graph is con...
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L412-L429
null
class BipartiteGraph(object): """Bipartite graph model for review data mining. Args: summary_type: specify summary type class, default value is AverageSummary. alpha: used to compute weight of anomalous scores, default value is 1. credibility: credibility class to be used in this graph. ...
rgmining/ria
ria/bipartite.py
BipartiteGraph.retrieve_review
python
def retrieve_review(self, reviewer, product): if not isinstance(reviewer, self._reviewer_cls): raise TypeError( "Type of given reviewer isn't acceptable:", reviewer, ", expected:", self._reviewer_cls) elif not isinstance(product, self._product_cls): ...
Retrieve review that the given reviewer put the given product. Args: reviewer: An instance of Reviewer. product: An instance of Product. Returns: A review object. Raises: TypeError: when given reviewer and product aren't instance of specifie...
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L432-L460
null
class BipartiteGraph(object): """Bipartite graph model for review data mining. Args: summary_type: specify summary type class, default value is AverageSummary. alpha: used to compute weight of anomalous scores, default value is 1. credibility: credibility class to be used in this graph. ...
rgmining/ria
ria/bipartite.py
BipartiteGraph.update
python
def update(self): w = self._weight_generator(self.reviewers) diff_p = max(p.update_summary(w) for p in self.products) diff_a = max(r.update_anomalous_score() for r in self.reviewers) return max(diff_p, diff_a)
Update reviewers' anomalous scores and products' summaries. Returns: maximum absolute difference between old summary and new one, and old anomalous score and new one.
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L462-L472
[ "def _weight_generator(self, reviewers):\n \"\"\"Compute a weight function for the given reviewers.\n\n Args:\n reviewers: a set of reviewers to compute weight function.\n\n Returns:\n a function computing a weight for a reviewer.\n \"\"\"\n scores = [r.anomalous_score for r in reviewers]\n...
class BipartiteGraph(object): """Bipartite graph model for review data mining. Args: summary_type: specify summary type class, default value is AverageSummary. alpha: used to compute weight of anomalous scores, default value is 1. credibility: credibility class to be used in this graph. ...
rgmining/ria
ria/bipartite.py
BipartiteGraph._weight_generator
python
def _weight_generator(self, reviewers): scores = [r.anomalous_score for r in reviewers] mu = np.average(scores) sigma = np.std(scores) if sigma: def w(v): """Compute a weight for the given reviewer. Args: v: anomalous score ...
Compute a weight function for the given reviewers. Args: reviewers: a set of reviewers to compute weight function. Returns: a function computing a weight for a reviewer.
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L474-L507
null
class BipartiteGraph(object): """Bipartite graph model for review data mining. Args: summary_type: specify summary type class, default value is AverageSummary. alpha: used to compute weight of anomalous scores, default value is 1. credibility: credibility class to be used in this graph. ...
rgmining/ria
ria/bipartite.py
BipartiteGraph.dump_credibilities
python
def dump_credibilities(self, output): for p in self.products: json.dump({ "product_id": p.name, "credibility": self.credibility(p) }, output) output.write("\n")
Dump credibilities of all products. Args: output: a writable object.
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L509-L520
null
class BipartiteGraph(object): """Bipartite graph model for review data mining. Args: summary_type: specify summary type class, default value is AverageSummary. alpha: used to compute weight of anomalous scores, default value is 1. credibility: credibility class to be used in this graph. ...
rgmining/ria
ria/credibility.py
GraphBasedCredibility.review_score
python
def review_score(self, reviewer, product): return self._g.retrieve_review(reviewer, product).score
Find a review score from a given reviewer to a product. Args: reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`. product: Product i.e. an instance of :class:`ria.bipartite.Product`. Returns: A review object representing the review from the reviewer to...
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/credibility.py#L109-L119
null
class GraphBasedCredibility(object): """Abstract class of credibility using a Bipartite graph. Args: g: A bipartite graph instance. This class provides two helper methods; :meth:`reviewers` and :meth:`review_score`. """ __slots__ = ("_g") def __init__(self, g): """Construct ...
rgmining/ria
ria/bipartite_sum.py
Reviewer.update_anomalous_score
python
def update_anomalous_score(self): old = self.anomalous_score products = self._graph.retrieve_products(self) self.anomalous_score = sum( p.summary.difference( self._graph.retrieve_review(self, p)) * self._credibility(p) - 0.5 for p in products ) ...
Update anomalous score. New anomalous score is the summation of weighted differences between current summary and reviews. The weights come from credibilities. Therefore, the new anomalous score is defined as .. math:: {\\rm anomalous}(r) = \\sum_{p \\in P} \\m...
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite_sum.py#L38-L67
null
class Reviewer(bipartite.Reviewer): """Reviewer which uses normalized summations for updated anomalous scores. This reviewer will update its anomalous score by computing summation of partial anomalous scores instead of using a weighted average. """ __slots__ = ()
rgmining/ria
ria/bipartite_sum.py
BipartiteGraph.update
python
def update(self): res = super(BipartiteGraph, self).update() max_v = None min_v = float("inf") for r in self.reviewers: max_v = max(max_v, r.anomalous_score) min_v = min(min_v, r.anomalous_score) width = max_v - min_v if width: for r ...
Update reviewers' anomalous scores and products' summaries. The update consists of 2 steps; Step1 (updating summaries): Update summaries of products with anomalous scores of reviewers and weight function. The weight is calculated by the manner in :class:`ria.biparti...
train
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite_sum.py#L85-L120
[ "def update(self):\n \"\"\"Update reviewers' anomalous scores and products' summaries.\n\n Returns:\n maximum absolute difference between old summary and new one, and\n old anomalous score and new one.\n \"\"\"\n w = self._weight_generator(self.reviewers)\n diff_p = max(p.update_summary(w) ...
class BipartiteGraph(bipartite.BipartiteGraph): """Bipartite Graph implementing OneSum algorithm. This graph employs a normalized summation of deviation times credibility as the undated anomalous scores for each reviewer. Constructor receives as same arguments as :class:`ria.bipartite.BipartiteGra...
mattbierner/blotre-py
blotre.py
create_disposable
python
def create_disposable(clientInfo, config = {}): response = requests.put( _format_url( _extend(DEFAULT_CONFIG, config), OAUTH2_ROOT + 'disposable'), json = clientInfo) if response.status_code != 200: return None else: body = response.json() ...
Create a new disposable client.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L328-L346
[ "def _extend(dict1, dict2):\n extended = dict1.copy()\n extended.update(dict2)\n return extended\n", "def _format_url(config, relPath, query={}):\n return urlunparse((\n config.get('protocol'),\n config.get('host'),\n relPath,\n '',\n urlencode(query),\n ''))\...
import json import os import re import requests try: from urllib import urlencode from urlparse import urlunparse except ImportError: from urllib.parse import urlencode from urllib.parse import urlunparse _JSON_HEADERS = { 'accepts': 'application/json', 'content-type': 'application/json' } ROO...
mattbierner/blotre-py
blotre.py
_get_existing_disposable_app
python
def _get_existing_disposable_app(file, clientInfo, conf): if not os.path.isfile(file): return None else: data = None with open(file, 'r') as f: data = json.load(f) if not 'client' in data or not 'creds' in data: return None return _BlotreDisposable...
Attempt to load an existing
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L373-L388
null
import json import os import re import requests try: from urllib import urlencode from urlparse import urlunparse except ImportError: from urllib.parse import urlencode from urllib.parse import urlunparse _JSON_HEADERS = { 'accepts': 'application/json', 'content-type': 'application/json' } ROO...
mattbierner/blotre-py
blotre.py
_try_redeem_disposable_app
python
def _try_redeem_disposable_app(file, client): redeemedClient = client.redeem_onetime_code(None) if redeemedClient is None: return None else: return _BlotreDisposableApp(file, redeemedClient.client, creds = redeemedClient.creds, config = redeemedClient.conf...
Attempt to redeem a one time code registred on the client.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L390-L401
[ "def redeem_onetime_code(self, code):\n \"\"\"\n Attempt to exchange a onetime token for a new access token.\n If successful, update client to use these credentials.\n \"\"\"\n return self._access_token_endpoint(\n 'https://oauth2grant.blot.re/onetime_code', {\n 'code': code if code...
import json import os import re import requests try: from urllib import urlencode from urlparse import urlunparse except ImportError: from urllib.parse import urlencode from urllib.parse import urlunparse _JSON_HEADERS = { 'accepts': 'application/json', 'content-type': 'application/json' } ROO...
mattbierner/blotre-py
blotre.py
_check_app_is_valid
python
def _check_app_is_valid(client): try: if 'refresh_token' in client.creds: client.exchange_refresh_token() else: existing.get_token_info() return True except TokenEndpointError as e: return False
Check to see if the app has valid creds.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L411-L422
[ "def exchange_refresh_token(self):\n \"\"\"\n Attempt to exchange a refresh token for a new access token.\n If successful, update client to use these credentials.\n \"\"\"\n return self._access_token_endpoint('refresh_token', {\n 'refresh_token': self.creds['refresh_token']\n })\n" ]
import json import os import re import requests try: from urllib import urlencode from urlparse import urlunparse except ImportError: from urllib.parse import urlencode from urllib.parse import urlunparse _JSON_HEADERS = { 'accepts': 'application/json', 'content-type': 'application/json' } ROO...
mattbierner/blotre-py
blotre.py
create_disposable_app
python
def create_disposable_app(clientInfo, config={}): file = _get_disposable_app_filename(clientInfo) existing = _get_existing_disposable_app(file, clientInfo, config) if existing: if _check_app_is_valid(existing): return existing else: print("Existing client has expired,...
Use an existing disposable app if data exists or create a new one and persist the data.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L424-L437
[ "def _get_disposable_app_filename(clientInfo):\n \"\"\"\n Get name of file used to store creds.\n \"\"\"\n return clientInfo.get('file', clientInfo['name'] + '.client_data.json')\n", "def _get_existing_disposable_app(file, clientInfo, conf):\n \"\"\"\n Attempt to load an existing \n \"\"\"\n ...
import json import os import re import requests try: from urllib import urlencode from urlparse import urlunparse except ImportError: from urllib.parse import urlencode from urllib.parse import urlunparse _JSON_HEADERS = { 'accepts': 'application/json', 'content-type': 'application/json' } ROO...
mattbierner/blotre-py
blotre.py
Blotre.set_creds
python
def set_creds(self, newCreds): self.creds = newCreds self.on_creds_changed(newCreds) return self
Manually update the current creds.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L86-L90
[ "def on_creds_changed(self, newCreds):\n \"\"\"\n Overridable function called when the creds change\n \"\"\"\n pass\n" ]
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def on_creds_changed(self, newCreds): """ Overridable function called when ...
mattbierner/blotre-py
blotre.py
Blotre.normalize_uri
python
def normalize_uri(self, uri): return urllib.quote( re.sub(r"\s", '+', uri.strip().lower()), safe = '~@#$&()*!+=:),.?/\'')
Convert a stream path into it's normalized form.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L98-L102
null
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
Blotre.get_authorization_url
python
def get_authorization_url(self): return self._format_url( OAUTH2_ROOT + 'authorize', query = { 'response_type': 'code', 'client_id': self.client.get('client_id', ''), 'redirect_uri': self.client.get('redirect_uri', '') })
Get the authorization Url for the current client.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L121-L129
[ "def _format_url(self, relPath, query={}):\n return _format_url(self.config, relPath, query)\n" ]
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
Blotre._access_token_endpoint
python
def _access_token_endpoint(self, grantType, extraParams={}): response = requests.post( self._format_url(OAUTH2_ROOT + 'access_token'), data = _extend({ 'grant_type': grantType, 'client_id': self.client.get('client_id', ''), 'client_secret':...
Base exchange of data for an access_token.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L138-L155
[ "def _extend(dict1, dict2):\n extended = dict1.copy()\n extended.update(dict2)\n return extended\n", "def _token_error_from_data(data):\n return TokenEndpointError(\n data.get('error', ''),\n data.get('error_description', ''))\n", "def set_creds(self, newCreds):\n \"\"\"Manually upd...
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
Blotre.get_token_info
python
def get_token_info(self): response = requests.get( self._format_url(OAUTH2_ROOT + 'token_info', { 'token': self.creds['access_token'] })) data = response.json() if response.status_code != 200: raise _token_error_from_data(data) else: ...
Get information about the current access token.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L185-L197
[ "def _token_error_from_data(data):\n return TokenEndpointError(\n data.get('error', ''),\n data.get('error_description', ''))\n", "def _format_url(self, relPath, query={}):\n return _format_url(self.config, relPath, query)\n" ]
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
Blotre._add_auth_headers
python
def _add_auth_headers(self, base): if 'access_token' in self.creds: return _extend(base, { 'authorization': 'Bearer ' + self.creds['access_token'] }) return base
Attach the acces_token to a request.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L200-L206
null
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
Blotre._is_expired_response
python
def _is_expired_response(self, response): if response.status_code != 401: return False challenge = response.headers.get('www-authenticate', '') return 'error="invalid_token"' in challenge
Check if the response failed because of an expired access token.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L208-L215
null
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
Blotre._make_request
python
def _make_request(self, type, path, args, noRetry=False): response = getattr(requests, type)(path, headers = self._add_auth_headers(_JSON_HEADERS), **args) if response.status_code == 200 or response.status_code == 201: return response.json() elif not noRetry and self._is_expired_resp...
Make a request to Blot're. Attempts to reply the request if it fails due to an expired access token.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L217-L234
[ "def _rest_error_from_response(response):\n body = response.json()\n return RestError(\n response.status_code,\n body['error'],\n body.get('details', None))\n", "def _add_auth_headers(self, base):\n \"\"\"Attach the acces_token to a request.\"\"\"\n if 'access_token' in self.creds...
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
Blotre.get
python
def get(self, path, query={}): return self._make_request('get', self._format_url(API_ROOT + path, query=query), {})
GET request.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L236-L239
[ "def _format_url(self, relPath, query={}):\n return _format_url(self.config, relPath, query)\n", "def _make_request(self, type, path, args, noRetry=False):\n \"\"\"\n Make a request to Blot're.\n\n Attempts to reply the request if it fails due to an expired\n access token.\n \"\"\"\n response...
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
Blotre.post
python
def post(self, path, body): return self._make_request('post', self._format_url(API_ROOT + path), { 'json': body })
POST request.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L241-L246
[ "def _format_url(self, relPath, query={}):\n return _format_url(self.config, relPath, query)\n", "def _make_request(self, type, path, args, noRetry=False):\n \"\"\"\n Make a request to Blot're.\n\n Attempts to reply the request if it fails due to an expired\n access token.\n \"\"\"\n response...
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
Blotre.put
python
def put(self, path, body): return self._make_request('put', self._format_url(API_ROOT + path), { 'json': body })
PUT request.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L248-L253
[ "def _format_url(self, relPath, query={}):\n return _format_url(self.config, relPath, query)\n", "def _make_request(self, type, path, args, noRetry=False):\n \"\"\"\n Make a request to Blot're.\n\n Attempts to reply the request if it fails due to an expired\n access token.\n \"\"\"\n response...
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
Blotre.get_child
python
def get_child(self, streamId, childId, options={}): return self.get('stream/' + streamId + '/children/' + childId, options)
Get the child of a stream.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L294-L296
[ "def get(self, path, query={}):\n \"\"\"GET request.\"\"\"\n return self._make_request('get',\n self._format_url(API_ROOT + path, query=query), {})\n" ]
class Blotre: """ Main Blot're flow object. """ def __init__(self, client, creds={}, config={}): self.client = client self.config = _extend(DEFAULT_CONFIG, config) self.creds = creds def set_creds(self, newCreds): """Manually update the current creds.""" self...
mattbierner/blotre-py
blotre.py
_BlotreDisposableApp._persist
python
def _persist(self): with open(self.file, 'w') as f: json.dump({ 'client': self.client, 'creds': self.creds, 'config': self.config }, f)
Persist client data.
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L358-L365
null
class _BlotreDisposableApp(Blotre): def __init__(self, file, client, **kwargs): Blotre.__init__(self, client, **kwargs) self.file = file self._persist() def on_creds_changed(self, newCreds): self._persist()
arraylabs/pymyq
pymyq/api.py
login
python
async def login( username: str, password: str, brand: str, websession: ClientSession = None) -> API: api = API(brand, websession) await api.authenticate(username, password) return api
Log in to the API.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L286-L292
[ "async def authenticate(self, username: str, password: str) -> None:\n \"\"\"Authenticate against the API.\"\"\"\n self._credentials = {\n 'username': username,\n 'password': password,\n }\n\n await self._get_security_token()\n" ]
"""Define the MyQ API.""" import asyncio import logging from datetime import datetime, timedelta from typing import Optional from aiohttp import ClientSession from aiohttp.client_exceptions import ClientError from .errors import MyQError, RequestError, UnsupportedBrandError _LOGGER = logging.getLogger(__name__) API...
arraylabs/pymyq
pymyq/api.py
API._create_websession
python
def _create_websession(self): from socket import AF_INET from aiohttp import ClientTimeout, TCPConnector _LOGGER.debug('Creating web session') conn = TCPConnector( family=AF_INET, limit_per_host=5, enable_cleanup_closed=True, ) # Crea...
Create a web session.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L73-L89
null
class API: """Define a class for interacting with the MyQ iOS App API.""" def __init__(self, brand: str, websession: ClientSession = None) -> None: """Initialize the API object.""" if brand not in BRAND_MAPPINGS: raise UnsupportedBrandError('Unknown brand: {0}'.format(brand)) ...
arraylabs/pymyq
pymyq/api.py
API.close_websession
python
async def close_websession(self): # We do not close the web session if it was provided. if self._supplied_websession or self._websession is None: return _LOGGER.debug('Closing connections') # Need to set _websession to none first to prevent any other task # from clos...
Close web session if not already closed and created by us.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L91-L104
null
class API: """Define a class for interacting with the MyQ iOS App API.""" def __init__(self, brand: str, websession: ClientSession = None) -> None: """Initialize the API object.""" if brand not in BRAND_MAPPINGS: raise UnsupportedBrandError('Unknown brand: {0}'.format(brand)) ...
arraylabs/pymyq
pymyq/api.py
API.authenticate
python
async def authenticate(self, username: str, password: str) -> None: self._credentials = { 'username': username, 'password': password, } await self._get_security_token()
Authenticate against the API.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L219-L226
[ "async def _get_security_token(self) -> None:\n \"\"\"Request a security token.\"\"\"\n _LOGGER.debug('Requesting security token.')\n if self._credentials is None:\n return\n\n # Make sure only 1 request can be sent at a time.\n async with self._security_token_lock:\n # Confirm there is...
class API: """Define a class for interacting with the MyQ iOS App API.""" def __init__(self, brand: str, websession: ClientSession = None) -> None: """Initialize the API object.""" if brand not in BRAND_MAPPINGS: raise UnsupportedBrandError('Unknown brand: {0}'.format(brand)) ...
arraylabs/pymyq
pymyq/api.py
API._get_security_token
python
async def _get_security_token(self) -> None: _LOGGER.debug('Requesting security token.') if self._credentials is None: return # Make sure only 1 request can be sent at a time. async with self._security_token_lock: # Confirm there is still no security token. ...
Request a security token.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L228-L253
[ "async def _request(\n self,\n method: str,\n endpoint: str,\n *,\n headers: dict = None,\n params: dict = None,\n data: dict = None,\n json: dict = None,\n login_request: bool = False,\n **kwargs) -> Optional[dict]:\n\n # Get a security token...
class API: """Define a class for interacting with the MyQ iOS App API.""" def __init__(self, brand: str, websession: ClientSession = None) -> None: """Initialize the API object.""" if brand not in BRAND_MAPPINGS: raise UnsupportedBrandError('Unknown brand: {0}'.format(brand)) ...
arraylabs/pymyq
pymyq/api.py
API.get_devices
python
async def get_devices(self, covers_only: bool = True) -> list: from .device import MyQDevice _LOGGER.debug('Retrieving list of devices') devices_resp = await self._request('get', DEVICE_LIST_ENDPOINT) # print(json.dumps(devices_resp, indent=4)) device_list = [] if devic...
Get a list of all devices associated with the account.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L255-L283
[ "async def _request(\n self,\n method: str,\n endpoint: str,\n *,\n headers: dict = None,\n params: dict = None,\n data: dict = None,\n json: dict = None,\n login_request: bool = False,\n **kwargs) -> Optional[dict]:\n\n # Get a security token...
class API: """Define a class for interacting with the MyQ iOS App API.""" def __init__(self, brand: str, websession: ClientSession = None) -> None: """Initialize the API object.""" if brand not in BRAND_MAPPINGS: raise UnsupportedBrandError('Unknown brand: {0}'.format(brand)) ...
arraylabs/pymyq
example.py
main
python
async def main() -> None: loglevels = dict((logging.getLevelName(level), level) for level in [10, 20, 30, 40, 50]) logging.basicConfig( level=loglevels[LOGLEVEL], format='%(asctime)s:%(levelname)s:\t%(name)s\t%(message)s') async with ClientSession() as websession: ...
Create the aiohttp session and run the example.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/example.py#L31-L97
[ "async def login(\n username: str, password: str, brand: str,\n websession: ClientSession = None) -> API:\n \"\"\"Log in to the API.\"\"\"\n api = API(brand, websession)\n await api.authenticate(username, password)\n return api\n" ]
"""Run an example script to quickly test any MyQ account.""" import asyncio import logging import json from aiohttp import ClientSession import pymyq from pymyq.device import STATE_CLOSED, STATE_OPEN from pymyq.errors import MyQError # Provide your email and password account details for MyQ. MYQ_ACCOUNT_EMAIL = '<EM...
arraylabs/pymyq
pymyq/device.py
MyQDevice.name
python
def name(self) -> str: return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'desc')
Return the device name.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L64-L68
null
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
arraylabs/pymyq
pymyq/device.py
MyQDevice.available
python
def available(self) -> bool: # Both ability to retrieve state from MyQ cloud AND device itself has # to be online. is_available = self.api.online and \ next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get(...
Return if device is online or not.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L71-L81
null
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
arraylabs/pymyq
pymyq/device.py
MyQDevice.open_allowed
python
def open_allowed(self) -> bool: return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'isunattendedopenallowed')\ == "1"
Door can be opened unattended.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L89-L94
null
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
arraylabs/pymyq
pymyq/device.py
MyQDevice.close_allowed
python
def close_allowed(self) -> bool: return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'isunattendedcloseallowed')\ == "1"
Door can be closed unattended.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L97-L102
null
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
arraylabs/pymyq
pymyq/device.py
MyQDevice.state
python
def state(self) -> str: return self._coerce_state_from_string( next( attr['Value'] for attr in self._device_json.get( 'Attributes', []) if attr.get('AttributeDisplayName') == 'doorstate'))
Return the current state of the device (if it exists).
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L105-L111
[ "def _coerce_state_from_string(value: Union[int, str]) -> str:\n \"\"\"Return a proper state from a string input.\"\"\"\n try:\n return STATE_MAP[int(value)]\n except KeyError:\n _LOGGER.error('Unknown state: %s', value)\n return STATE_UNKNOWN\n" ]
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
arraylabs/pymyq
pymyq/device.py
MyQDevice._update_state
python
def _update_state(self, value: str) -> None: attribute = next(attr for attr in self._device['device_info'].get( 'Attributes', []) if attr.get( 'AttributeDisplayName') == 'doorstate') if attribute is not None: attribute['Value'] = value
Update state temporary during open or close.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L113-L119
null
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
arraylabs/pymyq
pymyq/device.py
MyQDevice._coerce_state_from_string
python
def _coerce_state_from_string(value: Union[int, str]) -> str: try: return STATE_MAP[int(value)] except KeyError: _LOGGER.error('Unknown state: %s', value) return STATE_UNKNOWN
Return a proper state from a string input.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L127-L133
null
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
arraylabs/pymyq
pymyq/device.py
MyQDevice._set_state
python
async def _set_state(self, state: int) -> bool: try: set_state_resp = await self.api._request( 'put', DEVICE_SET_ENDPOINT, json={ 'attributeName': 'desireddoorstate', 'myQDeviceId': self.device_id, ...
Set the state of the device.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L136-L161
null
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
arraylabs/pymyq
pymyq/device.py
MyQDevice.close
python
async def close(self) -> bool: _LOGGER.debug('%s: Sending close command', self.name) if not await self._set_state(0): return False # Do not allow update of this device's state for 10 seconds. self.next_allowed_update = datetime.utcnow() + timedelta(seconds=10) # Ens...
Close the device.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L163-L179
[ "async def _set_state(self, state: int) -> bool:\n \"\"\"Set the state of the device.\"\"\"\n try:\n set_state_resp = await self.api._request(\n 'put',\n DEVICE_SET_ENDPOINT,\n json={\n 'attributeName': 'desireddoorstate',\n 'myQDeviceId': ...
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
arraylabs/pymyq
pymyq/device.py
MyQDevice.open
python
async def open(self) -> bool: _LOGGER.debug('%s: Sending open command', self.name) if not await self._set_state(1): return False # Do not allow update of this device's state for 5 seconds. self.next_allowed_update = datetime.utcnow() + timedelta(seconds=5) # Ensure ...
Open the device.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L181-L197
[ "async def _set_state(self, state: int) -> bool:\n \"\"\"Set the state of the device.\"\"\"\n try:\n set_state_resp = await self.api._request(\n 'put',\n DEVICE_SET_ENDPOINT,\n json={\n 'attributeName': 'desireddoorstate',\n 'myQDeviceId': ...
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
arraylabs/pymyq
pymyq/device.py
MyQDevice.update
python
async def update(self) -> None: if self.next_allowed_update is not None and \ datetime.utcnow() < self.next_allowed_update: return self.next_allowed_update = None await self.api._update_device_state() self._device_json = self._device['device_info']
Retrieve updated device state.
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L200-L208
null
class MyQDevice: """Define a generic MyQ device.""" def __init__(self, device: dict, brand: str, api: API) -> None: """Initialize.""" self._brand = brand self._device = device self._device_json = device['device_info'] self._device_id = self._device_json['MyQDeviceId'] ...
xmunoz/sodapy
sodapy/__init__.py
_raise_for_status
python
def _raise_for_status(response): ''' Custom raise_for_status with more appropriate error message. ''' http_error_msg = "" if 400 <= response.status_code < 500: http_error_msg = "{0} Client Error: {1}".format(response.status_code, respo...
Custom raise_for_status with more appropriate error message.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L510-L531
null
from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import object from io import StringIO, IOBase import requests import csv import json import logging import re import os from .constants import DEFAULT_API_PATH, OLD_API_PATH, DATASETS_PATH cl...
xmunoz/sodapy
sodapy/__init__.py
_clear_empty_values
python
def _clear_empty_values(args): ''' Scrap junk data from a dict. ''' result = {} for param in args: if args[param] is not None: result[param] = args[param] return result
Scrap junk data from a dict.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L534-L542
null
from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import object from io import StringIO, IOBase import requests import csv import json import logging import re import os from .constants import DEFAULT_API_PATH, OLD_API_PATH, DATASETS_PATH cl...
xmunoz/sodapy
sodapy/__init__.py
authentication_validation
python
def authentication_validation(username, password, access_token): ''' Only accept one form of authentication. ''' if bool(username) is not bool(password): raise Exception("Basic authentication requires a username AND" " password.") if (username and access_token) or (pa...
Only accept one form of authentication.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L570-L580
null
from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import object from io import StringIO, IOBase import requests import csv import json import logging import re import os from .constants import DEFAULT_API_PATH, OLD_API_PATH, DATASETS_PATH cl...
xmunoz/sodapy
sodapy/__init__.py
_download_file
python
def _download_file(url, local_filename): ''' Utility function that downloads a chunked response from the specified url to a local path. This method is suitable for larger downloads. ''' response = requests.get(url, stream=True) with open(local_filename, 'wb') as outfile: for chunk in res...
Utility function that downloads a chunked response from the specified url to a local path. This method is suitable for larger downloads.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L583-L592
null
from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import object from io import StringIO, IOBase import requests import csv import json import logging import re import os from .constants import DEFAULT_API_PATH, OLD_API_PATH, DATASETS_PATH cl...
xmunoz/sodapy
sodapy/__init__.py
Socrata.datasets
python
def datasets(self, limit=0, offset=0, order=None, **kwargs): ''' Returns the list of datasets associated with a particular domain. WARNING: Large limits (>1000) will return megabytes of data, which can be slow on low-bandwidth networks, and is also a lot of data to hold in memory...
Returns the list of datasets associated with a particular domain. WARNING: Large limits (>1000) will return megabytes of data, which can be slow on low-bandwidth networks, and is also a lot of data to hold in memory. This method performs a get request on these type of URLs: http...
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L97-L205
[ "def _perform_request(self, request_type, resource, **kwargs):\n '''\n Utility method that performs all requests.\n '''\n request_type_methods = set([\"get\", \"post\", \"put\", \"delete\"])\n if request_type not in request_type_methods:\n raise Exception(\"Unknown request type. Supported requ...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.create
python
def create(self, name, **kwargs): ''' Create a dataset, including the field types. Optionally, specify args such as: description : description of the dataset columns : list of columns (see docs/tests for list structure) category : must exist in /admin/metadata ...
Create a dataset, including the field types. Optionally, specify args such as: description : description of the dataset columns : list of columns (see docs/tests for list structure) category : must exist in /admin/metadata tags : list of tag strings row_identi...
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L207-L234
[ "def _format_old_api_request(dataid=None, content_type=None):\n\n if dataid is not None:\n if content_type is not None:\n return \"{0}/{1}.{2}\".format(OLD_API_PATH, dataid, content_type)\n else:\n return \"{0}/{1}\".format(OLD_API_PATH, dataid)\n else:\n if content_...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.set_permission
python
def set_permission(self, dataset_identifier, permission="private", content_type="json"): ''' Set a dataset's permissions to private or public Options are private, public ''' resource = _format_old_api_request(dataid=dataset_identifier, content_type=content_type) params ...
Set a dataset's permissions to private or public Options are private, public
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L236-L249
[ "def _format_old_api_request(dataid=None, content_type=None):\n\n if dataid is not None:\n if content_type is not None:\n return \"{0}/{1}.{2}\".format(OLD_API_PATH, dataid, content_type)\n else:\n return \"{0}/{1}\".format(OLD_API_PATH, dataid)\n else:\n if content_...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.get_metadata
python
def get_metadata(self, dataset_identifier, content_type="json"): ''' Retrieve the metadata for a particular dataset. ''' resource = _format_old_api_request(dataid=dataset_identifier, content_type=content_type) return self._perform_request("get", resource)
Retrieve the metadata for a particular dataset.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L251-L256
[ "def _format_old_api_request(dataid=None, content_type=None):\n\n if dataid is not None:\n if content_type is not None:\n return \"{0}/{1}.{2}\".format(OLD_API_PATH, dataid, content_type)\n else:\n return \"{0}/{1}\".format(OLD_API_PATH, dataid)\n else:\n if content_...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.update_metadata
python
def update_metadata(self, dataset_identifier, update_fields, content_type="json"): ''' Update the metadata for a particular dataset. update_fields is a dictionary containing [metadata key:new value] pairs. This method performs a full replace for the key:value pairs listed in `update...
Update the metadata for a particular dataset. update_fields is a dictionary containing [metadata key:new value] pairs. This method performs a full replace for the key:value pairs listed in `update_fields`, and returns all of the metadata with the updates applied.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L258-L267
[ "def _format_old_api_request(dataid=None, content_type=None):\n\n if dataid is not None:\n if content_type is not None:\n return \"{0}/{1}.{2}\".format(OLD_API_PATH, dataid, content_type)\n else:\n return \"{0}/{1}\".format(OLD_API_PATH, dataid)\n else:\n if content_...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.download_attachments
python
def download_attachments(self, dataset_identifier, content_type="json", download_dir="~/sodapy_downloads"): ''' Download all of the attachments associated with a dataset. Return the paths of downloaded files. ''' metadata = self.get_metadata(dataset_i...
Download all of the attachments associated with a dataset. Return the paths of downloaded files.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L269-L304
[ "def _format_old_api_request(dataid=None, content_type=None):\n\n if dataid is not None:\n if content_type is not None:\n return \"{0}/{1}.{2}\".format(OLD_API_PATH, dataid, content_type)\n else:\n return \"{0}/{1}\".format(OLD_API_PATH, dataid)\n else:\n if content_...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.publish
python
def publish(self, dataset_identifier, content_type="json"): ''' The create() method creates a dataset in a "working copy" state. This method publishes it. ''' base = _format_old_api_request(dataid=dataset_identifier) resource = "{0}/publication.{1}".format(base, content_t...
The create() method creates a dataset in a "working copy" state. This method publishes it.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L306-L314
[ "def _format_old_api_request(dataid=None, content_type=None):\n\n if dataid is not None:\n if content_type is not None:\n return \"{0}/{1}.{2}\".format(OLD_API_PATH, dataid, content_type)\n else:\n return \"{0}/{1}\".format(OLD_API_PATH, dataid)\n else:\n if content_...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.get
python
def get(self, dataset_identifier, content_type="json", **kwargs): ''' Read data from the requested resource. Options for content_type are json, csv, and xml. Optionally, specify a keyword arg to filter results: select : the set of columns to be returned, defaults to * wh...
Read data from the requested resource. Options for content_type are json, csv, and xml. Optionally, specify a keyword arg to filter results: select : the set of columns to be returned, defaults to * where : filters the rows to be returned, defaults to limit order : specifies...
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L316-L363
[ "def _clear_empty_values(args):\n '''\n Scrap junk data from a dict.\n '''\n result = {}\n for param in args:\n if args[param] is not None:\n result[param] = args[param]\n return result\n", "def _format_new_api_request(dataid=None, row_id=None, content_type=None):\n if datai...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.upsert
python
def upsert(self, dataset_identifier, payload, content_type="json"): ''' Insert, update or delete data to/from an existing dataset. Currently supports json and csv file objects. See here for the upsert documentation: http://dev.socrata.com/publishers/upsert.html ''' ...
Insert, update or delete data to/from an existing dataset. Currently supports json and csv file objects. See here for the upsert documentation: http://dev.socrata.com/publishers/upsert.html
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L365-L374
[ "def _format_new_api_request(dataid=None, row_id=None, content_type=None):\n if dataid is not None:\n if content_type is not None:\n if row_id is not None:\n return \"{0}{1}/{2}.{3}\".format(DEFAULT_API_PATH, dataid, row_id, content_type)\n else:\n retur...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.create_non_data_file
python
def create_non_data_file(self, params, file_data): ''' Creates a new file-based dataset with the name provided in the files tuple. A valid file input would be: files = ( {'file': ("gtfs2", open('myfile.zip', 'rb'))} ) ''' api_prefix = '/api/imports2/'...
Creates a new file-based dataset with the name provided in the files tuple. A valid file input would be: files = ( {'file': ("gtfs2", open('myfile.zip', 'rb'))} )
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L385-L398
[ "def _perform_request(self, request_type, resource, **kwargs):\n '''\n Utility method that performs all requests.\n '''\n request_type_methods = set([\"get\", \"post\", \"put\", \"delete\"])\n if request_type not in request_type_methods:\n raise Exception(\"Unknown request type. Supported requ...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.replace_non_data_file
python
def replace_non_data_file(self, dataset_identifier, params, file_data): ''' Same as create_non_data_file, but replaces a file that already exists in a file-based dataset. WARNING: a table-based dataset cannot be replaced by a file-based dataset. Use create_non_data_file...
Same as create_non_data_file, but replaces a file that already exists in a file-based dataset. WARNING: a table-based dataset cannot be replaced by a file-based dataset. Use create_non_data_file in order to replace.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L400-L415
[ "def _format_old_api_request(dataid=None, content_type=None):\n\n if dataid is not None:\n if content_type is not None:\n return \"{0}/{1}.{2}\".format(OLD_API_PATH, dataid, content_type)\n else:\n return \"{0}/{1}\".format(OLD_API_PATH, dataid)\n else:\n if content_...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata._perform_update
python
def _perform_update(self, method, resource, payload): ''' Execute the update task. ''' # python2/3 compatibility wizardry try: file_type = file except NameError: file_type = IOBase if isinstance(payload, (dict, list)): respons...
Execute the update task.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L417-L441
[ "def _perform_request(self, request_type, resource, **kwargs):\n '''\n Utility method that performs all requests.\n '''\n request_type_methods = set([\"get\", \"post\", \"put\", \"delete\"])\n if request_type not in request_type_methods:\n raise Exception(\"Unknown request type. Supported requ...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata.delete
python
def delete(self, dataset_identifier, row_id=None, content_type="json"): ''' Delete the entire dataset, e.g. client.delete("nimj-3ivp") or a single row, e.g. client.delete("nimj-3ivp", row_id=4) ''' if row_id: resource = _format_new_api_request(...
Delete the entire dataset, e.g. client.delete("nimj-3ivp") or a single row, e.g. client.delete("nimj-3ivp", row_id=4)
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L443-L457
[ "def _format_old_api_request(dataid=None, content_type=None):\n\n if dataid is not None:\n if content_type is not None:\n return \"{0}/{1}.{2}\".format(OLD_API_PATH, dataid, content_type)\n else:\n return \"{0}/{1}\".format(OLD_API_PATH, dataid)\n else:\n if content_...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
xmunoz/sodapy
sodapy/__init__.py
Socrata._perform_request
python
def _perform_request(self, request_type, resource, **kwargs): ''' Utility method that performs all requests. ''' request_type_methods = set(["get", "post", "put", "delete"]) if request_type not in request_type_methods: raise Exception("Unknown request type. Supported ...
Utility method that performs all requests.
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L459-L500
[ "def _raise_for_status(response):\n '''\n Custom raise_for_status with more appropriate error message.\n '''\n http_error_msg = \"\"\n\n if 400 <= response.status_code < 500:\n http_error_msg = \"{0} Client Error: {1}\".format(response.status_code,\n ...
class Socrata(object): ''' The main class that interacts with the SODA API. Sample usage: from sodapy import Socrata client = Socrata("opendata.socrata.com", None) ''' def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=...
tableau/document-api-python
tableaudocumentapi/xfile.py
xml_open
python
def xml_open(filename, expected_root=None): # Is the file a zip (.twbx or .tdsx) if zipfile.is_zipfile(filename): tree = get_xml_from_archive(filename) else: tree = ET.parse(filename) # Is the file a supported version tree_root = tree.getroot() file_version = Version(tree_root....
Opens the provided 'filename'. Handles detecting if the file is an archive, detecting the document version, and validating the root tag.
train
https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/xfile.py#L24-L46
[ "def get_xml_from_archive(filename):\n with zipfile.ZipFile(filename) as zf:\n with zf.open(find_file_in_zip(zf)) as xml_file:\n xml_tree = ET.parse(xml_file)\n\n return xml_tree\n" ]
import contextlib import os import shutil import tempfile import zipfile import xml.etree.ElementTree as ET try: from distutils2.version import NormalizedVersion as Version except ImportError: from distutils.version import LooseVersion as Version MIN_SUPPORTED_VERSION = Version("9.0") class TableauVersionNo...
tableau/document-api-python
tableaudocumentapi/xfile.py
find_file_in_zip
python
def find_file_in_zip(zip_file): '''Returns the twb/tds file from a Tableau packaged file format. Packaged files can contain cache entries which are also valid XML, so only look for files with a .tds or .twb extension. ''' candidate_files = filter(lambda x: x.split('.')[-1] in ('twb', 'tds'), ...
Returns the twb/tds file from a Tableau packaged file format. Packaged files can contain cache entries which are also valid XML, so only look for files with a .tds or .twb extension.
train
https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/xfile.py#L58-L74
null
import contextlib import os import shutil import tempfile import zipfile import xml.etree.ElementTree as ET try: from distutils2.version import NormalizedVersion as Version except ImportError: from distutils.version import LooseVersion as Version MIN_SUPPORTED_VERSION = Version("9.0") class TableauVersionNo...
tableau/document-api-python
tableaudocumentapi/xfile.py
build_archive_file
python
def build_archive_file(archive_contents, zip_file): # This is tested against Desktop and Server, and reverse engineered by lots # of trial and error. Do not change this logic. for root_dir, _, files in os.walk(archive_contents): relative_dir = os.path.relpath(root_dir, archive_contents) for...
Build a Tableau-compatible archive file.
train
https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/xfile.py#L85-L96
null
import contextlib import os import shutil import tempfile import zipfile import xml.etree.ElementTree as ET try: from distutils2.version import NormalizedVersion as Version except ImportError: from distutils.version import LooseVersion as Version MIN_SUPPORTED_VERSION = Version("9.0") class TableauVersionNo...
tableau/document-api-python
tableaudocumentapi/connection.py
Connection.from_attributes
python
def from_attributes(cls, server, dbname, username, dbclass, port=None, query_band=None, initial_sql=None, authentication=''): root = ET.Element('connection', authentication=authentication) xml = cls(root) xml.server = server xml.dbname = dbname xml.userna...
Creates a new connection that can be added into a Data Source. defaults to `''` which will be treated as 'prompt' by Tableau.
train
https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/connection.py#L28-L43
null
class Connection(object): """A class representing connections inside Data Sources.""" def __init__(self, connxml): """Connection is usually instantiated by passing in connection elements in a Data Source. If creating a connection from scratch you can call `from_attributes` passing in th...
tableau/document-api-python
tableaudocumentapi/connection.py
Connection.dbname
python
def dbname(self, value): self._dbname = value self._connectionXML.set('dbname', value)
Set the connection's database name property. Args: value: New name of the database. String. Returns: Nothing.
train
https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/connection.py#L51-L63
null
class Connection(object): """A class representing connections inside Data Sources.""" def __init__(self, connxml): """Connection is usually instantiated by passing in connection elements in a Data Source. If creating a connection from scratch you can call `from_attributes` passing in th...
tableau/document-api-python
tableaudocumentapi/connection.py
Connection.server
python
def server(self, value): self._server = value self._connectionXML.set('server', value)
Set the connection's server property. Args: value: New server. String. Returns: Nothing.
train
https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/connection.py#L71-L83
null
class Connection(object): """A class representing connections inside Data Sources.""" def __init__(self, connxml): """Connection is usually instantiated by passing in connection elements in a Data Source. If creating a connection from scratch you can call `from_attributes` passing in th...