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 |
|---|---|---|---|---|---|---|---|---|---|
aleontiev/dj | dj/commands/init.py | init | python | def init(name, runtime):
runtime = click.unstyle(runtime)
stdout.write(
style.format_command(
'Initializing',
'%s %s %s' % (name, style.gray('@'), style.green(runtime))
)
)
config = Config(os.getcwd())
config.set('runtime', runtime)
config.save()
ge... | Create a new Django app. | train | https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/commands/init.py#L18-L34 | [
"def format_command(a, b='', prefix=''):\n return (\n white(prefix) +\n blue('%s: ' % a) +\n white(b)\n )\n",
"def green(message):\n return click.style(message, fg='green', bold=True)\n",
"def gray(message):\n return click.style(message, fg='white', bold=False)\n",
"def write(... | from __future__ import absolute_import
import os
import click
from dj.config import Config
from dj.utils import style
from .generate import generate
from .base import stdout
from .run import run
@click.command()
@click.argument('name')
@click.option(
'--runtime',
prompt=style.prompt('Python version'),
def... |
aleontiev/dj | dj/commands/add.py | add | python | def add(addon, dev, interactive):
application = get_current_application()
application.add(
addon,
dev=dev,
interactive=interactive
) | Add a dependency.
Examples:
$ django add dynamic-rest==1.5.0
+ dynamic-rest == 1.5.0 | train | https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/commands/add.py#L14-L28 | [
"def get_current_application():\n global current_application\n if not current_application:\n current_application = Application()\n return current_application\n",
"def add(self, addon, dev=False, interactive=True):\n \"\"\"Add a new dependency and install it.\"\"\"\n dependencies = self.get_d... | from __future__ import absolute_import
import click
from dj.application import get_current_application
@click.argument('addon')
@click.option('--dev', is_flag=True)
@click.option(
'--interactive/--not-interactive',
is_flag=True,
default=True
)
@click.command()
|
aleontiev/dj | dj/blueprints/command/context.py | get_context | python | def get_context(name, doc):
name = inflection.underscore(name)
return {
'name': name,
'doc': doc or name
} | Generate a command with given name.
The command can be run immediately after generation.
For example:
dj generate command bar
dj run manage.py bar | train | https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/blueprints/command/context.py#L8-L22 | null | import click
import inflection
@click.command()
@click.argument('name')
@click.option('--doc')
|
aleontiev/dj | dj/utils/system.py | execute | python | def execute(
command,
abort=True,
capture=False,
verbose=False,
echo=False,
stream=None,
):
stream = stream or sys.stdout
if echo:
out = stream
out.write(u'$ %s' % command)
# Capture stdout and stderr in the same stream
command = u'%s 2>&1' % command
if ver... | Run a command locally.
Arguments:
command: a command to execute.
abort: If True, a non-zero return code will trigger an exception.
capture: If True, returns the output of the command.
If False, returns a subprocess result.
echo: if True, prints the command before executi... | train | https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/utils/system.py#L76-L148 | [
"def make_terminate_handler(process, signal=signal.SIGTERM):\n def inner(*args):\n try:\n os.killpg(os.getpgid(process.pid), signal)\n except OSError:\n pass\n return inner\n"
] | import os
import click
import sys
import subprocess
import signal
def get_platform_os():
if not exists('uname'):
return 'Windows'
return execute(
'uname -s',
capture=True
)
def get(
directory,
filter=None,
depth=0,
include_files=False,
include_dirs=False
):
... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord.attrs | python | def attrs(self):
ret = dict(self.__dict__) # obtain copy of internal __dict__
del ret["_matches"] # match history is specifically distinguished from player information (and stored separately)
if self.type != c.COMPUTER: # difficulty only matters for computer playres
del ret["difficul... | provide a copy of this player's attributes as a dictionary | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L97-L103 | null | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord.simpleAttrs | python | def simpleAttrs(self):
simpleAttrs = {}
for k,v in iteritems(self.attrs):
if k in ["_matches"]: continue # attributes to specifically ignore
try: simpleAttrs[k] = v.type
except: simpleAttrs[k] = v
return simpleAttrs | provide a copy of this player's attributes as a dictionary, but with objects flattened into a string representation of the object | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L106-L113 | null | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord._validateAttrs | python | def _validateAttrs(self, keys):
badAttrs = []
for k in keys:
if k not in self.__dict__:
badAttrs.append("Attribute key '%s' is not a valid attribute"%(k))
badAttrsMsg = os.linesep.join(badAttrs)
if not keys: return # is iterable, but didn't contain any keys
... | prove that all attributes are defined appropriately | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L124-L134 | null | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord.control | python | def control(self):
if self.isComputer: value = c.COMPUTER
else: value = c.PARTICIPANT
return c.PlayerControls(value) | the type of control this player exhibits | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L137-L141 | null | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord.load | python | def load(self, playerName=None):
if playerName: # switch the PlayerRecord this object describes
self.name = playerName # preset value to load self.filename
try:
with open(self.filename, "rb") as f:
data = f.read()
except Exception:
raise ValueE... | retrieve the PlayerRecord settings from saved disk file | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L143-L153 | [
"def update(self, attrs):\n \"\"\"update attributes initialized with the proper type\"\"\"\n ########################################################################\n def convertStrToDict(strVal):\n if isinstance(strVal, dict): return strVal\n strVal = re.sub(\"[\\{\\}]+\", \"\", str(strVal)... | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord.save | python | def save(self):
data = str.encode( json.dumps(self.simpleAttrs, indent=4, sort_keys=True) )
with open(self.filename, "wb") as f:
f.write(data) | save PlayerRecord settings to disk | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L155-L159 | null | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord.update | python | def update(self, attrs):
########################################################################
def convertStrToDict(strVal):
if isinstance(strVal, dict): return strVal
strVal = re.sub("[\{\}]+", "", str(strVal))
regexCol = re.compile(":")
terms = re.spl... | update attributes initialized with the proper type | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L161-L204 | [
"def _validateAttrs(self, keys):\n \"\"\"prove that all attributes are defined appropriately\"\"\"\n badAttrs = []\n for k in keys:\n if k not in self.__dict__:\n badAttrs.append(\"Attribute key '%s' is not a valid attribute\"%(k))\n badAttrsMsg = os.linesep.join(badAttrs)\n if not ... | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord.matchSubset | python | def matchSubset(**kwargs):
ret = []
for m in self.matches:
allMatched = True
for k,v in iteritems(kwargs):
mVal = getattr(m, k)
try:
if v == mVal or v in mVal: continue # this check passed
except Exception: pass ... | extract matches from player's entire match history given matching criteria kwargs | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L206-L219 | null | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord.apmRecent | python | def apmRecent(self, maxMatches=c.RECENT_MATCHES, **criteria):
if not self.matches: return 0 # no apm information without match history
#try: maxMatches = criteria["maxMatches"]
#except: maxMatches = c.RECENT_MATCHES
apms = [m.apm(self) for m in self.recentMatches(maxMatches=ma... | collect recent match history's apm data to report player's calculated MMR | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L221-L227 | [
"def recentMatches(self, **criteria):\n \"\"\"identify all recent matches for player given optional, additional criteria\"\"\"\n if not self.matches: return [] # no match history\n try: # maxMatches is a specially handled parameter (not true criteria)\n maxMatches = criteria[\"maxMatches\"]\n ... | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord.apmAggregate | python | def apmAggregate(self, **criteria):
apms = [m.apm(self) for m in self.matchSubset(**criteria)]
if not apms: return 0 # no apm information without match history
return sum(apms) / len(apms) | collect all match history's apm data to report player's calculated MMR | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L229-L233 | [
"def matchSubset(**kwargs):\n \"\"\"extract matches from player's entire match history given matching criteria kwargs\"\"\"\n ret = []\n for m in self.matches:\n allMatched = True\n for k,v in iteritems(kwargs):\n mVal = getattr(m, k)\n try:\n if v == mVal... | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerRecord.py | PlayerRecord.recentMatches | python | def recentMatches(self, **criteria):
if not self.matches: return [] # no match history
try: # maxMatches is a specially handled parameter (not true criteria)
maxMatches = criteria["maxMatches"]
del criteria["maxMatches"]
except AttributeError:
maxMatches = c.R... | identify all recent matches for player given optional, additional criteria | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerRecord.py#L235-L247 | [
"def matchSubset(**kwargs):\n \"\"\"extract matches from player's entire match history given matching criteria kwargs\"\"\"\n ret = []\n for m in self.matches:\n allMatched = True\n for k,v in iteritems(kwargs):\n mVal = getattr(m, k)\n try:\n if v == mVal... | class PlayerRecord(object):
"""manage the out-of-game meta data of a given player"""
AVAILABLE_KEYS = [
"name",
"type",
"difficulty",
"initCmd",
"initOptions",
"raceDefault",
"rating",
]
#############################################################... |
ttinies/sc2players | sc2players/playerManagement.py | addPlayer | python | def addPlayer(settings):
_validate(settings)
player = PlayerRecord(settings)
player.save()
getKnownPlayers()[player.name] = player
return player | define a new PlayerRecord setting and save to disk file | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerManagement.py#L26-L32 | [
"def getKnownPlayers(reset=False):\n \"\"\"identify all of the currently defined players\"\"\"\n global playerCache\n if not playerCache or reset:\n jsonFiles = os.path.join(c.PLAYERS_FOLDER, \"*.json\")\n for playerFilepath in glob.glob(jsonFiles):\n filename = os.path.basename(pl... | """
PURPOSE: manage records of all known players, both local and remote
"""
from __future__ import absolute_import
from __future__ import division # python 2/3 compatibility
from __future__ import print_function # python 2/3 compatibility
from six import iteritems, itervalues # python 2/3 compatibility
import ... |
ttinies/sc2players | sc2players/playerManagement.py | updatePlayer | python | def updatePlayer(name, settings):
player = delPlayer(name) # remove the existing record
_validate(settings)
player.update(settings)
player.save()
getKnownPlayers()[player.name] = player
return player | update an existing PlayerRecord setting and save to disk file | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerManagement.py#L36-L43 | [
"def delPlayer(name):\n \"\"\"forget about a previously defined PlayerRecord setting by deleting its disk file\"\"\"\n player = getPlayer(name)\n try: os.remove(player.filename) # delete from disk\n except IOError: pass # shouldn't happen, but don't crash if the disk data doesn't exist\n try: d... | """
PURPOSE: manage records of all known players, both local and remote
"""
from __future__ import absolute_import
from __future__ import division # python 2/3 compatibility
from __future__ import print_function # python 2/3 compatibility
from six import iteritems, itervalues # python 2/3 compatibility
import ... |
ttinies/sc2players | sc2players/playerManagement.py | getPlayer | python | def getPlayer(name):
if isinstance(name, PlayerRecord): return name
try: return getKnownPlayers()[name.lower()]
except KeyError:
raise ValueError("given player name '%s' is not a known player definition"%(name)) | obtain a specific PlayerRecord settings file | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerManagement.py#L47-L52 | [
"def getKnownPlayers(reset=False):\n \"\"\"identify all of the currently defined players\"\"\"\n global playerCache\n if not playerCache or reset:\n jsonFiles = os.path.join(c.PLAYERS_FOLDER, \"*.json\")\n for playerFilepath in glob.glob(jsonFiles):\n filename = os.path.basename(pl... | """
PURPOSE: manage records of all known players, both local and remote
"""
from __future__ import absolute_import
from __future__ import division # python 2/3 compatibility
from __future__ import print_function # python 2/3 compatibility
from six import iteritems, itervalues # python 2/3 compatibility
import ... |
ttinies/sc2players | sc2players/playerManagement.py | delPlayer | python | def delPlayer(name):
player = getPlayer(name)
try: os.remove(player.filename) # delete from disk
except IOError: pass # shouldn't happen, but don't crash if the disk data doesn't exist
try: del getKnownPlayers()[player.name] # forget object from cache
except: pass
return player | forget about a previously defined PlayerRecord setting by deleting its disk file | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerManagement.py#L56-L63 | [
"def getPlayer(name):\n \"\"\"obtain a specific PlayerRecord settings file\"\"\"\n if isinstance(name, PlayerRecord): return name\n try: return getKnownPlayers()[name.lower()]\n except KeyError:\n raise ValueError(\"given player name '%s' is not a known player definition\"%(name))\n",
"def g... | """
PURPOSE: manage records of all known players, both local and remote
"""
from __future__ import absolute_import
from __future__ import division # python 2/3 compatibility
from __future__ import print_function # python 2/3 compatibility
from six import iteritems, itervalues # python 2/3 compatibility
import ... |
ttinies/sc2players | sc2players/playerManagement.py | getKnownPlayers | python | def getKnownPlayers(reset=False):
global playerCache
if not playerCache or reset:
jsonFiles = os.path.join(c.PLAYERS_FOLDER, "*.json")
for playerFilepath in glob.glob(jsonFiles):
filename = os.path.basename(playerFilepath)
name = re.sub("^player_", "", filename)
... | identify all of the currently defined players | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerManagement.py#L81-L92 | null | """
PURPOSE: manage records of all known players, both local and remote
"""
from __future__ import absolute_import
from __future__ import division # python 2/3 compatibility
from __future__ import print_function # python 2/3 compatibility
from six import iteritems, itervalues # python 2/3 compatibility
import ... |
ttinies/sc2players | sc2players/playerManagement.py | getBlizzBotPlayers | python | def getBlizzBotPlayers():
ret = {}
for pName,p in iteritems(getKnownPlayers()):
if p.isComputer:
ret[pName] = p
return ret | identify all of Blizzard's built-in bots | train | https://github.com/ttinies/sc2players/blob/fd9b37c268bf1005d9ef73a25e65ed97c8b7895f/sc2players/playerManagement.py#L96-L102 | [
"def getKnownPlayers(reset=False):\n \"\"\"identify all of the currently defined players\"\"\"\n global playerCache\n if not playerCache or reset:\n jsonFiles = os.path.join(c.PLAYERS_FOLDER, \"*.json\")\n for playerFilepath in glob.glob(jsonFiles):\n filename = os.path.basename(pl... | """
PURPOSE: manage records of all known players, both local and remote
"""
from __future__ import absolute_import
from __future__ import division # python 2/3 compatibility
from __future__ import print_function # python 2/3 compatibility
from six import iteritems, itervalues # python 2/3 compatibility
import ... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | fetch_gbwithparts | python | def fetch_gbwithparts(list_of_NC_accessions, email, folder):
'''Download genbank files from NCBI using Biopython Entrez efetch.
Args:
list_of_NC_accessions (list): a list of strings, e.g ['NC_015758', 'NC_002695']
email (string): NCBI wants your email
folder (string): Where the gb fil... | Download genbank files from NCBI using Biopython Entrez efetch.
Args:
list_of_NC_accessions (list): a list of strings, e.g ['NC_015758', 'NC_002695']
email (string): NCBI wants your email
folder (string): Where the gb files download to, generally './genomes/' | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L40-L71 | null | '''
The MIT License (MIT)
Copyright (c) 2015 Matthew Solomonson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, ... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | OrganismDB.generate_combined_fasta | python | def generate_combined_fasta(self, genome_list, genome_dir):
'''Generate a combined fasta using the genbank files.
Args
genome_list (list)
genome_dir (string)
'''
fasta = []
for genome in genome_list:
... | Generate a combined fasta using the genbank files.
Args
genome_list (list)
genome_dir (string) | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L113-L171 | null | class OrganismDB(object):
"""The database object of hmmerclust.
On initialization, takes a list of genbank accessions and the directory
in which they are stored, generates a list of Organisms, and creates a
combined_fasta text file which is later queried by HMMER.
Args
database_name (str... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | OrganismDB.make_organisms | python | def make_organisms(self, genome_list, genome_dir):
'''Organism factory method.
Appends organisms to the organisms list.
Args
genome_list (list)
genome_dir (string)
'''
for genome in genome_list:
genome_path = genome_dir + genome
... | Organism factory method.
Appends organisms to the organisms list.
Args
genome_list (list)
genome_dir (string) | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L173-L207 | null | class OrganismDB(object):
"""The database object of hmmerclust.
On initialization, takes a list of genbank accessions and the directory
in which they are stored, generates a list of Organisms, and creates a
combined_fasta text file which is later queried by HMMER.
Args
database_name (str... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | OrganismDB.add_protein_to_organisms | python | def add_protein_to_organisms(self, orgprot_list):
'''
Protein factory method.
Iterates through a list of SearchIO hit objects, matches
the accession against SeqRecord features for each organism.
If there is a match, the new Protein object is created and
stored in the pr... | Protein factory method.
Iterates through a list of SearchIO hit objects, matches
the accession against SeqRecord features for each organism.
If there is a match, the new Protein object is created and
stored in the protein list of that Organism.
Args
orgprot_list: a ... | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L209-L259 | null | class OrganismDB(object):
"""The database object of hmmerclust.
On initialization, takes a list of genbank accessions and the directory
in which they are stored, generates a list of Organisms, and creates a
combined_fasta text file which is later queried by HMMER.
Args
database_name (str... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | OrganismDB.add_hits_to_proteins | python | def add_hits_to_proteins(self, hmm_hit_list):
'''Add HMMER results to Protein objects'''
for org in self.organisms:
print "adding SearchIO hit objects for", org.accession
for hit in hmm_hit_list:
hit_org_id = hit.id.split(',')[0]
hit_prot_id = h... | Add HMMER results to Protein objects | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L261-L275 | null | class OrganismDB(object):
"""The database object of hmmerclust.
On initialization, takes a list of genbank accessions and the directory
in which they are stored, generates a list of Organisms, and creates a
combined_fasta text file which is later queried by HMMER.
Args
database_name (str... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | OrganismDB.cluster_number | python | def cluster_number(self, data, maxgap):
'''General function that clusters numbers.
Args
data (list): list of integers.
maxgap (int): max gap between numbers in the cluster.
'''
data.sort()
groups = [[data[0]]]
for x in data[1:]:
if ... | General function that clusters numbers.
Args
data (list): list of integers.
maxgap (int): max gap between numbers in the cluster. | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L278-L294 | null | class OrganismDB(object):
"""The database object of hmmerclust.
On initialization, takes a list of genbank accessions and the directory
in which they are stored, generates a list of Organisms, and creates a
combined_fasta text file which is later queried by HMMER.
Args
database_name (str... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | OrganismDB.find_loci | python | def find_loci(self, cluster_size, maxgap, locusview=False, colordict=None):
'''
Finds the loci of a given cluster size & maximum gap between cluster members.
Args
cluster_size (int): minimum number of genes in the cluster.
maxgap (int): max basepair gap between ... | Finds the loci of a given cluster size & maximum gap between cluster members.
Args
cluster_size (int): minimum number of genes in the cluster.
maxgap (int): max basepair gap between genes in the cluster.
Kwargs
locusview (bool): whether or not a map is generated for... | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L296-L355 | [
"def cluster_number(self, data, maxgap): \n '''General function that clusters numbers.\n\n Args\n data (list): list of integers.\n maxgap (int): max gap between numbers in the cluster.\n\n '''\n\n data.sort()\n groups = [[data[0]]]\n for x in data[1:]:\n if abs(x - groups[-1][... | class OrganismDB(object):
"""The database object of hmmerclust.
On initialization, takes a list of genbank accessions and the directory
in which they are stored, generates a list of Organisms, and creates a
combined_fasta text file which is later queried by HMMER.
Args
database_name (str... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | Protein.parse_hmm_hit_list | python | def parse_hmm_hit_list(self, hmm_hit_list):
'''
take a list of hmm hit results, take needed info,
'''
tuplist = []
for hit in hmm_hit_list:
for hsp in hit.hsps:
tup = tuplist.append((hit._query_id.split('_')[0],
... | take a list of hmm hit results, take needed info, | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L462-L484 | null | class Protein(object):
"""Encapsulates data related to a single protein/gene.
Args
feature(SeqIO feature object)
Attributes
accession info
genome location info
hmm_hit_list (list): Complete list of SearchIO hit objects.
data related to the best-scoring hit
... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | rRNA16SDB.write_16S_rRNA_fasta | python | def write_16S_rRNA_fasta(self, org_list):
'''
Writes a fasta file containing 16S rRNA sequences
for a list of Organism objects,
The first 16S sequence found in the seq record object is used,
since it looks like there are duplicates
'''
fasta = []
for or... | Writes a fasta file containing 16S rRNA sequences
for a list of Organism objects,
The first 16S sequence found in the seq record object is used,
since it looks like there are duplicates | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L494-L536 | null | class rRNA16SDB:
def __init__(self, OrganismDB):
#self.write_16S_rRNA_fasta(OrganismDB.organisms)
self.import_tree_order_from_file(OrganismDB, '16S_aligned.csv')
def write_16S_rRNA_fasta(self, org_list):
'''
Writes a fasta file containing 16S rRNA sequences
for a lis... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | rRNA16SDB.import_tree_order_from_file | python | def import_tree_order_from_file(self, MyOrganismDB, filename):
'''
Import the accession list that has been ordered by position
in a phylogenetic tree. Get the index in the list, and
add this to the Organism object. Later we can use this position
to make a heatmap that matches up... | Import the accession list that has been ordered by position
in a phylogenetic tree. Get the index in the list, and
add this to the Organism object. Later we can use this position
to make a heatmap that matches up to a phylogenetic tree. | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L539-L555 | null | class rRNA16SDB:
def __init__(self, OrganismDB):
#self.write_16S_rRNA_fasta(OrganismDB.organisms)
self.import_tree_order_from_file(OrganismDB, '16S_aligned.csv')
def write_16S_rRNA_fasta(self, org_list):
'''
Writes a fasta file containing 16S rRNA sequences
for a lis... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | HmmSearch.run_hmmbuild | python | def run_hmmbuild(self):
'''
Generate hmm with hhbuild,
output to file. Also stores query names.
'''
for alignment in self.alignment_list:
print 'building Hmm for', alignment
alignment_full_path = self.alignment_dir + alignment
query_name = ... | Generate hmm with hhbuild,
output to file. Also stores query names. | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L607-L627 | null | class HmmSearch:
"""
Give alignment files, name them according to what the names
should be in the analysis.
First the hmm is built with Hmmbuild, and the hmm files output.
Then run Hmmsearch, parse the files, put each result in a list
"""
def __init__(self, OrganismDB, combined_fasta, f... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | HmmSearch.extract_hit_list_from_hmmsearch_results | python | def extract_hit_list_from_hmmsearch_results(self):
'''
Make a giant list of all the hit objects from
our search
'''
combined_list_of_hits = []
for result in self.hmm_result_list:
fullpath = self.hhsearch_result_folder + result
se =... | Make a giant list of all the hit objects from
our search | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L655-L676 | null | class HmmSearch:
"""
Give alignment files, name them according to what the names
should be in the analysis.
First the hmm is built with Hmmbuild, and the hmm files output.
Then run Hmmsearch, parse the files, put each result in a list
"""
def __init__(self, OrganismDB, combined_fasta, f... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | HmmSearch.make_protein_arrow_color_dict | python | def make_protein_arrow_color_dict(self, query_names):
'''
Generates a random color for all proteins in query_names,
stores these in a dict.
'''
protein_arrow_color_dict = dict()
for protein in self.query_names:
protein_arrow_color_dict[protein] = (random(),... | Generates a random color for all proteins in query_names,
stores these in a dict. | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L679-L691 | null | class HmmSearch:
"""
Give alignment files, name them according to what the names
should be in the analysis.
First the hmm is built with Hmmbuild, and the hmm files output.
Then run Hmmsearch, parse the files, put each result in a list
"""
def __init__(self, OrganismDB, combined_fasta, f... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | HmmSearch.parse_proteins | python | def parse_proteins(self,OrganismDB):
'''
Iterate through all the proteins in the DB,
creates a hit_dataframe for each protein.
'''
for org in OrganismDB.organisms:
for prot in org.proteins:
if len(prot.hmm_hit_list) > 0:
try:
... | Iterate through all the proteins in the DB,
creates a hit_dataframe for each protein. | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L701-L714 | null | class HmmSearch:
"""
Give alignment files, name them according to what the names
should be in the analysis.
First the hmm is built with Hmmbuild, and the hmm files output.
Then run Hmmsearch, parse the files, put each result in a list
"""
def __init__(self, OrganismDB, combined_fasta, f... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | HmmSearch.set_best_hit_values_for_proteins | python | def set_best_hit_values_for_proteins(self, OrganismDB):
'''
Iterate through all proteins in the DB,
drop duplicates in the hit_dataframe, then store the maximum
hit information as protein attributes.
'''
for org in OrganismDB.organisms:
print 'setting best h... | Iterate through all proteins in the DB,
drop duplicates in the hit_dataframe, then store the maximum
hit information as protein attributes. | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L716-L741 | null | class HmmSearch:
"""
Give alignment files, name them according to what the names
should be in the analysis.
First the hmm is built with Hmmbuild, and the hmm files output.
Then run Hmmsearch, parse the files, put each result in a list
"""
def __init__(self, OrganismDB, combined_fasta, f... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | HeatMap.make_heatmap | python | def make_heatmap(self, unstacked_df, singleletters):
fig, ax = plt.subplots(num=None, figsize=(10,len(unstacked_df)/3), dpi=80, facecolor='w', edgecolor='k')
#heatmap = ax.pcolor(unstacked_df, cmap=plt.cm.Reds, alpha=2, vmax = 5)
#heatmap = ax.pcolor(unstacked_df, cmap=plt.cm.gist_ncar_r, alp... | exerimental: displaying text on the heatmap | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L1094-L1136 | null | class HeatMap:
def __init__(self, DataFrame, by_locus=False, cols=None, subset=None, singleletters=None):
self.unstacked_df = self.unstack_df(DataFrame, by_locus, cols, subset)
self.heatmap = self.make_heatmap(self.unstacked_df, singleletters)
def unstack_df(self, DataFrame, by_locus, cols, ... |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | RelatedProteinGroup.make_related_protein_fasta_from_dataframe | python | def make_related_protein_fasta_from_dataframe(self, input_df):
'''
DataFrame should have
'''
dirname = './group_fastas'
if not os.path.exists(dirname):
os.makedirs(dirname)
unique_hit_queries = set(input_df.hit_query)
for hq in unique_hit_queries... | DataFrame should have | train | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L1200-L1231 | null | class RelatedProteinGroup:
'''
An object representing a group of related proteins
to be used for generating alignments, phylogeny, etc.
Input is a list of Protein objects, e.g. of the same type that were
identified in the Hmm search & where found in a cluster.
Can output a fasta file for each... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | clean_dict_keys | python | def clean_dict_keys(d):
new_d = {}
for (k, v) in d.iteritems():
new_d[str(k)] = v
return new_d | Convert all keys of the dict 'd' to (ascii-)strings.
:Raises: UnicodeEncodeError | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L16-L24 | null | """
JSON-RPC (especially v2) prescribes that the message format adheres
to a specific format/schema. This module contains code that helps
in serializing data (including errors) into JSON-RPC message format.
This file is part of `jsonrpcparts` project. See project's source for license and copyright.
"""
import json
im... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | BaseJSONRPCSerializer.json_dumps | python | def json_dumps(cls, obj, **kwargs):
if 'cls' not in kwargs:
kwargs['cls'] = cls.json_encoder
return json.dumps(obj, **kwargs) | A rewrap of json.dumps done for one reason - to inject a custom `cls` kwarg
:param obj:
:param kwargs:
:return:
:rtype: str | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L43-L54 | null | class BaseJSONRPCSerializer(object):
"""
Common base class for various json rpc serializers
Mostly done just for keeping track of common methods and attributes
(and thus define some sort of internal API/signature for these)
"""
# these are used in stringify/destringify calls like so:
# json... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | BaseJSONRPCSerializer.json_loads | python | def json_loads(cls, s, **kwargs):
if 'cls' not in kwargs:
kwargs['cls'] = cls.json_decoder
return json.loads(s, **kwargs) | A rewrap of json.loads done for one reason - to inject a custom `cls` kwarg
:param s:
:param kwargs:
:return:
:rtype: dict | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L57-L68 | null | class BaseJSONRPCSerializer(object):
"""
Common base class for various json rpc serializers
Mostly done just for keeping track of common methods and attributes
(and thus define some sort of internal API/signature for these)
"""
# these are used in stringify/destringify calls like so:
# json... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | JSONRPC10Serializer.assemble_request | python | def assemble_request(method, params=tuple(), id=0):
if not isinstance(method, (str, unicode)):
raise TypeError('"method" must be a string (or unicode string).')
if not isinstance(params, (tuple, list)):
raise TypeError("params must be a tuple/list.")
return {
... | serialize JSON-RPC-Request
:Parameters:
- method: the method-name (str/unicode)
- params: the parameters (list/tuple)
- id: if id=None, this results in a Notification
:Returns: | {"method": "...", "params": ..., "id": ...}
| "method", "param... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L112-L133 | null | class JSONRPC10Serializer(BaseJSONRPCSerializer):
"""JSON-RPC V1.0 data-structure / serializer
This implementation is quite liberal in what it accepts: It treats
missing "params" and "id" in Requests and missing "result"/"error" in
Responses as empty/null.
:SeeAlso: JSON-RPC 1.0 specification
... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | JSONRPC10Serializer.assemble_notification_request | python | def assemble_notification_request(method, params=tuple()):
if not isinstance(method, (str, unicode)):
raise TypeError('"method" must be a string (or unicode string).')
if not isinstance(params, (tuple, list)):
raise TypeError("params must be a tuple/list.")
return {
... | serialize a JSON-RPC-Notification
:Parameters: see dumps_request
:Returns: | {"method": "...", "params": ..., "id": null}
| "method", "params" and "id" are always in this order.
:Raises: see dumps_request | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L136-L153 | null | class JSONRPC10Serializer(BaseJSONRPCSerializer):
"""JSON-RPC V1.0 data-structure / serializer
This implementation is quite liberal in what it accepts: It treats
missing "params" and "id" in Requests and missing "result"/"error" in
Responses as empty/null.
:SeeAlso: JSON-RPC 1.0 specification
... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | JSONRPC10Serializer.parse_request | python | def parse_request(cls, jsonrpc_message):
try:
data = cls.json_loads(jsonrpc_message)
except ValueError, err:
raise errors.RPCParseError("No valid JSON. (%s)" % str(err))
if not isinstance(data, dict):
raise errors.RPCInvalidRPC("No valid RPC-package.")
... | We take apart JSON-RPC-formatted message as a string and decompose it
into a dictionary object, emitting errors if parsing detects issues with
the format of the message.
:Returns: | [method_name, params, id] or [method_name, params]
| params is a tuple/list
... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L206-L240 | null | class JSONRPC10Serializer(BaseJSONRPCSerializer):
"""JSON-RPC V1.0 data-structure / serializer
This implementation is quite liberal in what it accepts: It treats
missing "params" and "id" in Requests and missing "result"/"error" in
Responses as empty/null.
:SeeAlso: JSON-RPC 1.0 specification
... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | JSONRPC10Serializer.parse_response | python | def parse_response(cls, jsonrpc_message):
try:
data = cls.json_loads(jsonrpc_message)
except ValueError, err:
raise errors.RPCParseError("No valid JSON. (%s)" % str(err))
if not isinstance(data, dict):
raise errors.RPCInvalidRPC("No valid RPC-package.")
... | de-serialize a JSON-RPC Response/error
:Returns: | [result, id] for Responses
:Raises: | RPCFault+derivates for error-packages/faults, RPCParseError, RPCInvalidRPC
| Note that for error-packages which do not match the
V2.0-definition, RPCFault(-1, "Error", RECEIVE... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L243-L311 | null | class JSONRPC10Serializer(BaseJSONRPCSerializer):
"""JSON-RPC V1.0 data-structure / serializer
This implementation is quite liberal in what it accepts: It treats
missing "params" and "id" in Requests and missing "result"/"error" in
Responses as empty/null.
:SeeAlso: JSON-RPC 1.0 specification
... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | JSONRPC20Serializer.assemble_request | python | def assemble_request(method, params=None, notification=False):
if not isinstance(method, (str, unicode)):
raise TypeError('"method" must be a string (or unicode string).')
if params and not isinstance(params, (tuple, list, dict)):
raise TypeError("params must be a tuple/list/dic... | serialize JSON-RPC-Request
:Parameters:
- method: the method-name (str/unicode)
- params: the parameters (None/list/tuple/dict)
- notification: bool
:Returns: | {"jsonrpc": "2.0", "method": "...", "params": ..., "id": ...}
| "jsonrpc", "method",... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L319-L349 | null | class JSONRPC20Serializer(BaseJSONRPCSerializer):
@staticmethod
@staticmethod
def assemble_response(result, request_id):
return {
"jsonrpc": "2.0",
"result": result,
"id": request_id
}
@staticmethod
def assemble_error_response(error):
... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | JSONRPC20Serializer._parse_single_request_trap_errors | python | def _parse_single_request_trap_errors(cls, request_data):
try:
method, params, request_id = cls._parse_single_request(request_data)
return method, params, request_id, None
except errors.RPCFault as ex:
return None, None, ex.request_id, ex | Traps exceptions generated by __parse_single_request and
converts them into values of request_id and error in the
returned tuple.
:Returns: (method_name, params_object, request_id, error)
Where:
- method_name is a str (or None when error is set)
-... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L421-L437 | null | class JSONRPC20Serializer(BaseJSONRPCSerializer):
@staticmethod
def assemble_request(method, params=None, notification=False):
"""serialize JSON-RPC-Request
:Parameters:
- method: the method-name (str/unicode)
- params: the parameters (None/list/tuple/dict)
... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | JSONRPC20Serializer.parse_request | python | def parse_request(cls, request_string):
try:
batch = cls.json_loads(request_string)
except ValueError as err:
raise errors.RPCParseError("No valid JSON. (%s)" % str(err))
if isinstance(batch, (list, tuple)) and batch:
# batch is true batch.
# list... | JSONRPC allows for **batch** requests to be communicated
as array of dicts. This method parses out each individual
element in the batch and returns a list of tuples, each
tuple a result of parsing of each item in the batch.
:Returns: | tuple of (results, is_batch_mode_flag)
... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L440-L467 | [
"def json_loads(cls, s, **kwargs):\n \"\"\"\n A rewrap of json.loads done for one reason - to inject a custom `cls` kwarg\n\n :param s:\n :param kwargs:\n :return:\n :rtype: dict\n \"\"\"\n if 'cls' not in kwargs:\n kwargs['cls'] = cls.json_decoder\n return json.loads(s, **kwargs)\... | class JSONRPC20Serializer(BaseJSONRPCSerializer):
@staticmethod
def assemble_request(method, params=None, notification=False):
"""serialize JSON-RPC-Request
:Parameters:
- method: the method-name (str/unicode)
- params: the parameters (None/list/tuple/dict)
... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | JSONRPC20Serializer._parse_single_response | python | def _parse_single_response(cls, response_data):
if not isinstance(response_data, dict):
raise errors.RPCInvalidRequest("No valid RPC-package.")
if "id" not in response_data:
raise errors.RPCInvalidRequest("""Invalid Response, "id" missing.""")
request_id = response_dat... | de-serialize a JSON-RPC Response/error
:Returns: | [result, id] for Responses
:Raises: | RPCFault+derivates for error-packages/faults, RPCParseError, RPCInvalidRPC | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L470-L515 | null | class JSONRPC20Serializer(BaseJSONRPCSerializer):
@staticmethod
def assemble_request(method, params=None, notification=False):
"""serialize JSON-RPC-Request
:Parameters:
- method: the method-name (str/unicode)
- params: the parameters (None/list/tuple/dict)
... |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | JSONRPC20Serializer.parse_response | python | def parse_response(cls, response_string):
try:
batch = cls.json_loads(response_string)
except ValueError as err:
raise errors.RPCParseError("No valid JSON. (%s)" % str(err))
if isinstance(batch, (list, tuple)) and batch:
# batch is true batch.
# l... | JSONRPC allows for **batch** responses to be communicated
as arrays of dicts. This method parses out each individual
element in the batch and returns a list of tuples, each
tuple a result of parsing of each item in the batch.
:Returns: | tuple of (results, is_batch_mode_flag)
... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L526-L553 | [
"def json_loads(cls, s, **kwargs):\n \"\"\"\n A rewrap of json.loads done for one reason - to inject a custom `cls` kwarg\n\n :param s:\n :param kwargs:\n :return:\n :rtype: dict\n \"\"\"\n if 'cls' not in kwargs:\n kwargs['cls'] = cls.json_decoder\n return json.loads(s, **kwargs)\... | class JSONRPC20Serializer(BaseJSONRPCSerializer):
@staticmethod
def assemble_request(method, params=None, notification=False):
"""serialize JSON-RPC-Request
:Parameters:
- method: the method-name (str/unicode)
- params: the parameters (None/list/tuple/dict)
... |
dvdotsenko/jsonrpc.py | jsonrpcparts/application.py | JSONPRCCollection.register_class | python | def register_class(self, instance, name=None):
prefix_name = name or instance.__class__.__name__
for e in dir(instance):
if e[0][0] != "_":
self.register_function(
getattr(instance, e),
name="%s.%s" % (prefix_name, e)
) | Add all functions of a class-instance to the RPC-services.
All entries of the instance which do not begin with '_' are added.
:Parameters:
- myinst: class-instance containing the functions
- name: | hierarchical prefix.
| If omitted, the functions are ad... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/application.py#L22-L43 | [
"def register_function(self, function, name=None):\n \"\"\"Add a function to the RPC-services.\n\n :Parameters:\n - function: function to add\n - name: RPC-name for the function. If omitted/None, the original\n name of the function is used.\n \"\"\"\n if name:\n ... | class JSONPRCCollection(dict):
"""
A dictionary-like collection that helps with registration
and use (calling of) JSON-RPC methods.
"""
def register_function(self, function, name=None):
"""Add a function to the RPC-services.
:Parameters:
- function: function to add
... |
dvdotsenko/jsonrpc.py | jsonrpcparts/application.py | JSONPRCApplication.process_method | python | def process_method(self, method, args, kwargs, request_id=None, **context):
return method(*([] if args is None else args), **({} if kwargs is None else kwargs)) | Executes the actual method with args, kwargs provided.
This step is broken out of the process_requests flow to
allow for ease of overriding the call in your subclass of this class.
In some cases it's preferable to make callee aware of the request_id
and easily overridable caller method... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/application.py#L69-L97 | null | class JSONPRCApplication(JSONPRCCollection):
def __init__(self, data_serializer=JSONRPC20Serializer, *args, **kw):
"""
:Parameters:
- data_serializer: a data_structure+serializer-instance
"""
super(JSONPRCApplication, self).__init__(*args, **kw)
self._data_serial... |
dvdotsenko/jsonrpc.py | jsonrpcparts/application.py | JSONPRCApplication.process_requests | python | def process_requests(self, requests, **context):
ds = self._data_serializer
responses = []
for method, params, request_id, error in requests:
if error: # these are request message validation errors
if error.request_id: # no ID = Notification. We don't reply
... | Turns a list of request objects into a list of
response objects.
:param requests: A list of tuples describing the RPC call
:type requests: list[list[callable,object,object,list]]
:param context:
A dict with additional parameters passed to handle_request_string and process_re... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/application.py#L99-L167 | [
"def process_method(self, method, args, kwargs, request_id=None, **context):\n \"\"\"\n Executes the actual method with args, kwargs provided.\n\n This step is broken out of the process_requests flow to\n allow for ease of overriding the call in your subclass of this class.\n\n In some cases it's pre... | class JSONPRCApplication(JSONPRCCollection):
def __init__(self, data_serializer=JSONRPC20Serializer, *args, **kw):
"""
:Parameters:
- data_serializer: a data_structure+serializer-instance
"""
super(JSONPRCApplication, self).__init__(*args, **kw)
self._data_serial... |
dvdotsenko/jsonrpc.py | jsonrpcparts/application.py | JSONPRCApplication.handle_request_string | python | def handle_request_string(self, request_string, **context):
ds = self._data_serializer
try:
requests, is_batch_mode = ds.parse_request(request_string)
except errors.RPCFault as ex:
return ds.json_dumps(ds.assemble_error_response(ex))
except Exception as ex:
... | Handle a RPC-Request.
:param request_string: the received rpc-string
:param context:
A dict with additional parameters passed to process_requests and process_method
Allows wrapping code to pass additional parameters deep into parsing stack, override process_method
me... | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/application.py#L169-L217 | [
"def process_requests(self, requests, **context):\n \"\"\"\n Turns a list of request objects into a list of\n response objects.\n\n :param requests: A list of tuples describing the RPC call\n :type requests: list[list[callable,object,object,list]]\n :param context:\n A dict with additional ... | class JSONPRCApplication(JSONPRCCollection):
def __init__(self, data_serializer=JSONRPC20Serializer, *args, **kw):
"""
:Parameters:
- data_serializer: a data_structure+serializer-instance
"""
super(JSONPRCApplication, self).__init__(*args, **kw)
self._data_serial... |
dvdotsenko/jsonrpc.py | jsonrpcparts/client.py | Client.call | python | def call(self, method, *args, **kw):
if args and kw:
raise ValueError("JSON-RPC method calls allow only either named or positional arguments.")
if not method:
raise ValueError("JSON-RPC method call requires a method name.")
request = self._data_serializer.assemble_reques... | In context of a batch we return the request's ID
else we return the actual json | train | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/client.py#L49-L67 | null | class Client(object):
def __init__(self, data_serializer=JSONRPC20Serializer):
"""
:Parameters:
- data_serializer: a data_structure+serializer-instance
"""
self._in_batch_mode = False
self._requests = []
self._data_serializer = data_serializer
# Cont... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.sendCommand | python | def sendCommand(self, command):
data = { 'rapi' : command }
full_url = self.url + urllib.parse.urlencode(data)
data = urllib.request.urlopen(full_url)
response = re.search('\<p>>\$(.+)\<script', data.read().decode('utf-8'))
if response == None:#If we are using version 1 - https://github.com/OpenE... | Sends a command through the web interface of the charger and parses the response | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L31-L39 | null | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def getStatus(self):
"""Returns the charger's charge status, as a string"""
command = '$GS'
status = self.sendCommand(command)
return ... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getStatus | python | def getStatus(self):
command = '$GS'
status = self.sendCommand(command)
return states[int(status[1])] | Returns the charger's charge status, as a string | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L41-L45 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getChargeTimeElapsed | python | def getChargeTimeElapsed(self):
command = '$GS'
status = self.sendCommand(command)
if int(status[1]) == 3:
return int(status[2])
else:
return 0 | Returns the charge time elapsed (in seconds), or 0 if is not currently charging | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L47-L54 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getServiceLevel | python | def getServiceLevel(self):
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return (flags & 0x0001) + 1 | Returns the service level | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L92-L97 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getDiodeCheckEnabled | python | def getDiodeCheckEnabled(self):
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0002) | Returns True if enabled, False if disabled | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L99-L104 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getVentRequiredEnabled | python | def getVentRequiredEnabled(self):
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0004) | Returns True if enabled, False if disabled | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L106-L111 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getGroundCheckEnabled | python | def getGroundCheckEnabled(self):
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0008) | Returns True if enabled, False if disabled | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L113-L118 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getStuckRelayCheckEnabled | python | def getStuckRelayCheckEnabled(self):
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0010) | Returns True if enabled, False if disabled | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L120-L125 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getAutoServiceLevelEnabled | python | def getAutoServiceLevelEnabled(self):
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0020) | Returns True if enabled, False if disabled | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L127-L132 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getAutoStartEnabled | python | def getAutoStartEnabled(self):
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0040) | Returns True if enabled, False if disabled | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L134-L139 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getSerialDebugEnabled | python | def getSerialDebugEnabled(self):
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0080) | Returns True if enabled, False if disabled | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L141-L146 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getLCDType | python | def getLCDType(self):
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
if flags & 0x0100:
lcdtype = 'monochrome'
else:
lcdtype = 'rgb'
return lcdtype | Returns LCD type as a string, either monochrome or rgb | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L148-L157 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getChargingCurrent | python | def getChargingCurrent(self):
command = '$GG'
currentAndVoltage = self.sendCommand(command)
amps = float(currentAndVoltage[1])/1000
return amps | Returns the charging current, in amps, or 0.0 of not charging | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L184-L189 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getChargingVoltage | python | def getChargingVoltage(self):
command = '$GG'
currentAndVoltage = self.sendCommand(command)
volts = float(currentAndVoltage[2])/1000
return volts | Returns the charging voltage, in volts, or 0.0 of not charging | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L191-L196 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getAmbientThreshold | python | def getAmbientThreshold(self):
command = '$GO'
threshold = self.sendCommand(command)
if threshold[0] == 'NK':
return 0
else:
return float(threshold[1])/10 | Returns the ambient temperature threshold in degrees Celcius, or 0 if no Threshold is set | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L222-L229 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getIRThreshold | python | def getIRThreshold(self):
command = '$GO'
threshold = self.sendCommand(command)
if threshold[0] == 'NK':
return 0
else:
return float(threshold[2])/10 | Returns the IR temperature threshold in degrees Celcius, or 0 if no Threshold is set | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L231-L238 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
miniconfig/python-openevse-wifi | openevsewifi/__init__.py | Charger.getTime | python | def getTime(self):
command = '$GT'
time = self.sendCommand(command)
if time == ['OK','165', '165', '165', '165', '165', '85']:
return NULL
else:
return datetime.datetime(year = int(time[1])+2000,
month = int(time[2]),
day = int(ti... | Get the RTC time. Returns a datetime object, or NULL if the clock is not set | train | https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L258-L270 | [
"def sendCommand(self, command):\n \"\"\"Sends a command through the web interface of the charger and parses the response\"\"\"\n data = { 'rapi' : command }\n full_url = self.url + urllib.parse.urlencode(data)\n data = urllib.request.urlopen(full_url)\n response = re.search('\\<p>>\\$(.+)\\<script', data.r... | class Charger:
def __init__(self, host):
"""A connection to an OpenEVSE charging station equipped with the wifi kit."""
self.url = 'http://' + host + '/r?'
def sendCommand(self, command):
"""Sends a command through the web interface of the charger and parses the response"""
data = { 'rapi' : comman... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/client_hooks/__init__.py | install_all_patches | python | def install_all_patches():
from . import mysqldb
from . import psycopg2
from . import strict_redis
from . import sqlalchemy
from . import tornado_http
from . import urllib
from . import urllib2
from . import requests
mysqldb.install_patches()
psycopg2.install_patches()
stric... | A convenience method that installs all available hooks.
If a specific module is not available on the path, it is ignored. | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/client_hooks/__init__.py#L33-L55 | null | # Copyright (c) 2015-2017 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/client_hooks/__init__.py | install_patches | python | def install_patches(patchers='all'):
if patchers is None or patchers == 'all':
install_all_patches()
return
if not _valid_args(patchers):
raise ValueError('patchers argument must be None, "all", or a list')
for patch_func_name in patchers:
logging.info('Loading client hook %... | Usually called from middleware to install client hooks
specified in the client_hooks section of the configuration.
:param patchers: a list of patchers to run. Acceptable values include:
* None - installs all client patches
* 'all' - installs all client patches
* empty list - does not install ... | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/client_hooks/__init__.py#L58-L79 | [
"def install_all_patches():\n \"\"\"\n A convenience method that installs all available hooks.\n\n If a specific module is not available on the path, it is ignored.\n \"\"\"\n from . import mysqldb\n from . import psycopg2\n from . import strict_redis\n from . import sqlalchemy\n from . i... | # Copyright (c) 2015-2017 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/client_hooks/__init__.py | install_client_interceptors | python | def install_client_interceptors(client_interceptors=()):
if not _valid_args(client_interceptors):
raise ValueError('client_interceptors argument must be a list')
from ..http_client import ClientInterceptors
for client_interceptor in client_interceptors:
logging.info('Loading client interce... | Install client interceptors for the patchers.
:param client_interceptors: a list of client interceptors to install.
Should be a list of classes | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/client_hooks/__init__.py#L82-L98 | [
"def _valid_args(value):\n return isinstance(value, Sequence) and \\\n not isinstance(value, six.string_types)\n",
"def _load_symbol(name):\n \"\"\"Load a symbol by name.\n\n :param str name: The name to load, specified by `module.attr`.\n :returns: The attribute value. If the specified module ... | # Copyright (c) 2015-2017 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/client_hooks/__init__.py | _load_symbol | python | def _load_symbol(name):
module_name, key = name.rsplit('.', 1)
try:
module = importlib.import_module(module_name)
except ImportError as err:
# it's possible the symbol is a class method
module_name, class_name = module_name.rsplit('.', 1)
module = importlib.import_module(modu... | Load a symbol by name.
:param str name: The name to load, specified by `module.attr`.
:returns: The attribute value. If the specified module does not contain
the requested attribute then `None` is returned. | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/client_hooks/__init__.py#L106-L129 | null | # Copyright (c) 2015-2017 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/request_context.py | get_current_span | python | def get_current_span():
# Check against the old, ScopeManager-less implementation,
# for backwards compatibility.
context = RequestContextManager.current_context()
if context is not None:
return context.span
active = opentracing.tracer.scope_manager.active
return active.span if active e... | Access current request context and extract current Span from it.
:return:
Return current span associated with the current request context.
If no request context is present in thread local, or the context
has no span, return None. | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/request_context.py#L117-L132 | [
"def current_context(cls):\n \"\"\"Get the current request context.\n\n :rtype: opentracing_instrumentation.RequestContext\n :returns: The current request context, or None.\n \"\"\"\n return getattr(cls._state, 'context', None)\n"
] | # Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/request_context.py | span_in_context | python | def span_in_context(span):
# Return a no-op Scope if None was specified.
if span is None:
return opentracing.Scope(None, None)
return opentracing.tracer.scope_manager.activate(span, False) | Create a context manager that stores the given span in the thread-local
request context. This function should only be used in single-threaded
applications like Flask / uWSGI.
## Usage example in WSGI middleware:
.. code-block:: python
from opentracing_instrumentation.http_server import WSGIReq... | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/request_context.py#L135-L178 | null | # Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/request_context.py | span_in_stack_context | python | def span_in_stack_context(span):
if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
raise RuntimeError('scope_manager is not TornadoScopeManager')
# Enter the newly created stack context so we have
# storage available for Span activation.
context = tracer_stack_context()... | Create Tornado's StackContext that stores the given span in the
thread-local request context. This function is intended for use
in Tornado applications based on IOLoop, although will work fine
in single-threaded apps like Flask, albeit with more overhead.
## Usage example in Tornado application
Su... | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/request_context.py#L181-L226 | null | # Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/local_span.py | func_span | python | def func_span(func, tags=None, require_active_trace=False):
current_span = get_current_span()
if current_span is None and require_active_trace:
@contextlib2.contextmanager
def empty_ctx_mgr():
yield None
return empty_ctx_mgr()
# TODO convert func to a proper name: modu... | Creates a new local span for execution of the given `func`.
The returned span is best used as a context manager, e.g.
.. code-block:: python
with func_span('my_function'):
return my_function(...)
At this time the func should be a string name. In the future this code
can be enhance... | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/local_span.py#L28-L61 | [
"def get_current_span():\n \"\"\"\n Access current request context and extract current Span from it.\n :return:\n Return current span associated with the current request context.\n If no request context is present in thread local, or the context\n has no span, return None.\n \"\"\"\... | # Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/local_span.py | traced_function | python | def traced_function(func=None, name=None, on_start=None,
require_active_trace=False):
if func is None:
return functools.partial(traced_function, name=name,
on_start=on_start,
require_active_trace=require_active_trace)
... | A decorator that enables tracing of the wrapped function or
Tornado co-routine provided there is a parent span already established.
.. code-block:: python
@traced_function
def my_function1(arg1, arg2=None)
...
:param func: decorated function or Tornado co-routine
:param na... | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/local_span.py#L64-L153 | null | # Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/utils.py | start_child_span | python | def start_child_span(operation_name, tracer=None, parent=None, tags=None):
tracer = tracer or opentracing.tracer
return tracer.start_span(
operation_name=operation_name,
child_of=parent.context if parent else None,
tags=tags
) | Start a new span as a child of parent_span. If parent_span is None,
start a new root span.
:param operation_name: operation name
:param tracer: Tracer or None (defaults to opentracing.tracer)
:param parent: parent Span or None
:param tags: optional tags
:return: new span | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/utils.py#L25-L41 | null | # Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/http_server.py | before_request | python | def before_request(request, tracer=None):
if tracer is None: # pragma: no cover
tracer = opentracing.tracer
# we need to prepare tags upfront, mainly because RPC_SERVER tag must be
# set when starting the span, to support Zipkin's one-span-per-RPC model
tags_dict = {
tags.SPAN_KIND: ta... | Attempts to extract a tracing span from incoming request.
If no tracing context is passed in the headers, or the data
cannot be parsed, a new root span is started.
:param request: HTTP request with `.headers` property exposed
that satisfies a regular dictionary interface
:param tracer: optional... | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/http_server.py#L35-L86 | null | # Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/http_server.py | WSGIRequestWrapper._parse_wsgi_headers | python | def _parse_wsgi_headers(wsgi_environ):
prefix = 'HTTP_'
p_len = len(prefix)
# use .items() despite suspected memory pressure bc GC occasionally
# collects wsgi_environ.iteritems() during iteration.
headers = {
key[p_len:].replace('_', '-').lower():
val... | HTTP headers are presented in WSGI environment with 'HTTP_' prefix.
This method finds those headers, removes the prefix, converts
underscores to dashes, and converts to lower case.
:param wsgi_environ:
:return: returns a dictionary of headers | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/http_server.py#L174-L191 | null | class WSGIRequestWrapper(AbstractRequestWrapper):
"""
Wraps WSGI environment and exposes several properties
used by the tracing methods.
"""
def __init__(self, wsgi_environ, headers):
self.wsgi_environ = wsgi_environ
self._headers = headers
@classmethod
def from_wsgi_enviro... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/http_server.py | WSGIRequestWrapper.full_url | python | def full_url(self):
environ = self.wsgi_environ
url = environ['wsgi.url_scheme'] + '://'
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url += environ['SERVER_NAME']
if environ['wsgi.url_scheme'] == 'https':
if environ... | Taken from
http://legacy.python.org/dev/peps/pep-3333/#url-reconstruction
:return: Reconstructed URL from WSGI environment. | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/http_server.py#L194-L220 | null | class WSGIRequestWrapper(AbstractRequestWrapper):
"""
Wraps WSGI environment and exposes several properties
used by the tracing methods.
"""
def __init__(self, wsgi_environ, headers):
self.wsgi_environ = wsgi_environ
self._headers = headers
@classmethod
def from_wsgi_enviro... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/interceptors.py | ClientInterceptors.append | python | def append(cls, interceptor):
cls._check(interceptor)
cls._interceptors.append(interceptor) | Add interceptor to the end of the internal list.
Note: Raises ``ValueError`` if interceptor
does not extend ``OpenTracingInterceptor`` | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/interceptors.py#L80-L88 | null | class ClientInterceptors(object):
"""
Client interceptors executed between span creation and injection.
Subclassed implementations of ``OpenTracingInterceptor`` can be added
and are executed in order in which they are added, after child
span for current request is created, but before the span bagga... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/interceptors.py | ClientInterceptors.insert | python | def insert(cls, index, interceptor):
cls._check(interceptor)
cls._interceptors.insert(index, interceptor) | Add interceptor to the given index in the internal list.
Note: Raises ``ValueError`` if interceptor
does not extend ``OpenTracingInterceptor`` | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/interceptors.py#L91-L99 | null | class ClientInterceptors(object):
"""
Client interceptors executed between span creation and injection.
Subclassed implementations of ``OpenTracingInterceptor`` can be added
and are executed in order in which they are added, after child
span for current request is created, but before the span bagga... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/client_hooks/_singleton.py | singleton | python | def singleton(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if wrapper.__call_state__ == CALLED:
return
ret = func(*args, **kwargs)
wrapper.__call_state__ = CALLED
return ret
def reset():
wrapper.__call_state__ = NOT_CALLED
wrapper.res... | This decorator allows you to make sure that a function is called once and
only once. Note that recursive functions will still work.
WARNING: Not thread-safe!!! | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/client_hooks/_singleton.py#L30-L55 | [
"def reset():\n wrapper.__call_state__ = NOT_CALLED\n"
] | # Copyright (c) 2015,2018 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/http_client.py | before_http_request | python | def before_http_request(request, current_span_extractor):
span = utils.start_child_span(
operation_name=request.operation,
parent=current_span_extractor()
)
span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
span.set_tag(tags.HTTP_URL, request.full_url)
service_name = request... | A hook to be executed before HTTP request is executed.
It returns a Span object that can be used as a context manager around
the actual HTTP call implementation, or in case of async callback,
it needs its `finish()` method to be called explicitly.
:param request: request must match API defined by Abstr... | train | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/http_client.py#L35-L79 | [
"def get_current_span():\n \"\"\"\n Access current request context and extract current Span from it.\n :return:\n Return current span associated with the current request context.\n If no request context is present in thread local, or the context\n has no span, return None.\n \"\"\"\... | # Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
jreese/aiosqlite | aiosqlite/core.py | connect | python | def connect(
database: Union[str, Path], *, loop: asyncio.AbstractEventLoop = None, **kwargs: Any
) -> Connection:
if loop is None:
loop = asyncio.get_event_loop()
def connector() -> sqlite3.Connection:
if isinstance(database, str):
loc = database
elif isinstance(databas... | Create and return a connection proxy to the sqlite database. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L287-L304 | null | # Copyright 2018 John Reese
# Licensed under the MIT license
"""
Core implementation of aiosqlite proxies
"""
import asyncio
import logging
import sqlite3
from functools import partial
from pathlib import Path
from queue import Queue, Empty
from threading import Thread
from typing import Any, Callable, Generator, It... |
jreese/aiosqlite | aiosqlite/core.py | Cursor._execute | python | async def _execute(self, fn, *args, **kwargs):
return await self._conn._execute(fn, *args, **kwargs) | Execute the given function on the shared connection's thread. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L42-L44 | null | class Cursor:
def __init__(self, conn: "Connection", cursor: sqlite3.Cursor) -> None:
self._conn = conn
self._cursor = cursor
def __aiter__(self) -> "Cursor":
"""The cursor proxy is also an async iterator."""
return self
async def __anext__(self) -> sqlite3.Row:
"""... |
jreese/aiosqlite | aiosqlite/core.py | Cursor.execute | python | async def execute(self, sql: str, parameters: Iterable[Any] = None) -> None:
if parameters is None:
parameters = []
await self._execute(self._cursor.execute, sql, parameters) | Execute the given query. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L46-L50 | [
"async def _execute(self, fn, *args, **kwargs):\n \"\"\"Execute the given function on the shared connection's thread.\"\"\"\n return await self._conn._execute(fn, *args, **kwargs)\n"
] | class Cursor:
def __init__(self, conn: "Connection", cursor: sqlite3.Cursor) -> None:
self._conn = conn
self._cursor = cursor
def __aiter__(self) -> "Cursor":
"""The cursor proxy is also an async iterator."""
return self
async def __anext__(self) -> sqlite3.Row:
"""... |
jreese/aiosqlite | aiosqlite/core.py | Cursor.executemany | python | async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
await self._execute(self._cursor.executemany, sql, parameters) | Execute the given multiquery. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L52-L54 | [
"async def _execute(self, fn, *args, **kwargs):\n \"\"\"Execute the given function on the shared connection's thread.\"\"\"\n return await self._conn._execute(fn, *args, **kwargs)\n"
] | class Cursor:
def __init__(self, conn: "Connection", cursor: sqlite3.Cursor) -> None:
self._conn = conn
self._cursor = cursor
def __aiter__(self) -> "Cursor":
"""The cursor proxy is also an async iterator."""
return self
async def __anext__(self) -> sqlite3.Row:
"""... |
jreese/aiosqlite | aiosqlite/core.py | Cursor.executescript | python | async def executescript(self, sql_script: str) -> None:
await self._execute(self._cursor.executescript, sql_script) | Execute a user script. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L56-L58 | [
"async def _execute(self, fn, *args, **kwargs):\n \"\"\"Execute the given function on the shared connection's thread.\"\"\"\n return await self._conn._execute(fn, *args, **kwargs)\n"
] | class Cursor:
def __init__(self, conn: "Connection", cursor: sqlite3.Cursor) -> None:
self._conn = conn
self._cursor = cursor
def __aiter__(self) -> "Cursor":
"""The cursor proxy is also an async iterator."""
return self
async def __anext__(self) -> sqlite3.Row:
"""... |
jreese/aiosqlite | aiosqlite/core.py | Cursor.fetchone | python | async def fetchone(self) -> Optional[sqlite3.Row]:
return await self._execute(self._cursor.fetchone) | Fetch a single row. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L60-L62 | [
"async def _execute(self, fn, *args, **kwargs):\n \"\"\"Execute the given function on the shared connection's thread.\"\"\"\n return await self._conn._execute(fn, *args, **kwargs)\n"
] | class Cursor:
def __init__(self, conn: "Connection", cursor: sqlite3.Cursor) -> None:
self._conn = conn
self._cursor = cursor
def __aiter__(self) -> "Cursor":
"""The cursor proxy is also an async iterator."""
return self
async def __anext__(self) -> sqlite3.Row:
"""... |
jreese/aiosqlite | aiosqlite/core.py | Cursor.fetchmany | python | async def fetchmany(self, size: int = None) -> Iterable[sqlite3.Row]:
args = () # type: Tuple[int, ...]
if size is not None:
args = (size,)
return await self._execute(self._cursor.fetchmany, *args) | Fetch up to `cursor.arraysize` number of rows. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L64-L69 | [
"async def _execute(self, fn, *args, **kwargs):\n \"\"\"Execute the given function on the shared connection's thread.\"\"\"\n return await self._conn._execute(fn, *args, **kwargs)\n"
] | class Cursor:
def __init__(self, conn: "Connection", cursor: sqlite3.Cursor) -> None:
self._conn = conn
self._cursor = cursor
def __aiter__(self) -> "Cursor":
"""The cursor proxy is also an async iterator."""
return self
async def __anext__(self) -> sqlite3.Row:
"""... |
jreese/aiosqlite | aiosqlite/core.py | Cursor.fetchall | python | async def fetchall(self) -> Iterable[sqlite3.Row]:
return await self._execute(self._cursor.fetchall) | Fetch all remaining rows. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L71-L73 | [
"async def _execute(self, fn, *args, **kwargs):\n \"\"\"Execute the given function on the shared connection's thread.\"\"\"\n return await self._conn._execute(fn, *args, **kwargs)\n"
] | class Cursor:
def __init__(self, conn: "Connection", cursor: sqlite3.Cursor) -> None:
self._conn = conn
self._cursor = cursor
def __aiter__(self) -> "Cursor":
"""The cursor proxy is also an async iterator."""
return self
async def __anext__(self) -> sqlite3.Row:
"""... |
jreese/aiosqlite | aiosqlite/core.py | Connection.run | python | def run(self) -> None:
while self._running:
try:
future, function = self._tx.get(timeout=0.1)
except Empty:
continue
try:
LOG.debug("executing %s", function)
result = function()
LOG.debug("return... | Execute function calls on a separate thread. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L143-L158 | null | class Connection(Thread):
def __init__(
self,
connector: Callable[[], sqlite3.Connection],
loop: asyncio.AbstractEventLoop,
) -> None:
super().__init__()
self._running = True
self._connection = None # type: Optional[sqlite3.Connection]
self._connector = c... |
jreese/aiosqlite | aiosqlite/core.py | Connection._execute | python | async def _execute(self, fn, *args, **kwargs):
function = partial(fn, *args, **kwargs)
future = self._loop.create_future()
self._tx.put_nowait((future, function))
return await future | Queue a function with the given arguments for execution. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L160-L167 | null | class Connection(Thread):
def __init__(
self,
connector: Callable[[], sqlite3.Connection],
loop: asyncio.AbstractEventLoop,
) -> None:
super().__init__()
self._running = True
self._connection = None # type: Optional[sqlite3.Connection]
self._connector = c... |
jreese/aiosqlite | aiosqlite/core.py | Connection._connect | python | async def _connect(self) -> "Connection":
if self._connection is None:
self._connection = await self._execute(self._connector)
return self | Connect to the actual sqlite database. | train | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L169-L173 | [
"async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n"
] | class Connection(Thread):
def __init__(
self,
connector: Callable[[], sqlite3.Connection],
loop: asyncio.AbstractEventLoop,
) -> None:
super().__init__()
self._running = True
self._connection = None # type: Optional[sqlite3.Connection]
self._connector = c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.