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 |
|---|---|---|---|---|---|---|---|---|---|
thespacedoctor/transientNamer | transientNamer/search.py | search.files | python | def files(
self):
relatedFilesResultsList = []
relatedFilesResultsList[:] = [dict(l)
for l in self.relatedFilesResultsList]
return relatedFilesResultsList | *The associated source files*
**Usage:**
.. code-block:: python
sourceFiles = tns.files | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L182-L195 | null | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search.photometry | python | def photometry(
self):
photResultsList = []
photResultsList[:] = [dict(l) for l in self.photResultsList]
return photResultsList | *The associated source photometry*
**Usage:**
.. code-block:: python
sourcePhotometry = tns.photometry | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L198-L210 | null | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search.csv | python | def csv(
self,
dirPath=None):
if dirPath:
p = self._file_prefix()
csvSources = self.sourceResults.csv(
filepath=dirPath + "/" + p + "sources.csv")
csvPhot = self.photResults.csv(
filepath=dirPath + "/" + p + "phot.csv")... | *Render the results in csv format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `csvSources` -- the top-level transient data
- `csvPhot` -- all photometry associated with the transients
... | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L226-L280 | [
"def _file_prefix(\n self):\n \"\"\"*Generate a file prefix based on the type of search for saving files to disk*\n\n **Return:**\n - ``prefix`` -- the file prefix\n \"\"\"\n self.log.info('starting the ``_file_prefix`` method')\n\n if self.ra:\n now = datetime.now()\n pre... | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search.json | python | def json(
self,
dirPath=None):
if dirPath:
p = self._file_prefix()
jsonSources = self.sourceResults.json(
filepath=dirPath + "/" + p + "sources.json")
jsonPhot = self.photResults.json(
filepath=dirPath + "/" + p + "phot... | *Render the results in json format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `jsonSources` -- the top-level transient data
- `jsonPhot` -- all photometry associated with the transient... | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L282-L357 | [
"def _file_prefix(\n self):\n \"\"\"*Generate a file prefix based on the type of search for saving files to disk*\n\n **Return:**\n - ``prefix`` -- the file prefix\n \"\"\"\n self.log.info('starting the ``_file_prefix`` method')\n\n if self.ra:\n now = datetime.now()\n pre... | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search.yaml | python | def yaml(
self,
dirPath=None):
if dirPath:
p = self._file_prefix()
yamlSources = self.sourceResults.yaml(
filepath=dirPath + "/" + p + "sources.yaml")
yamlPhot = self.photResults.yaml(
filepath=dirPath + "/" + p + "phot... | *Render the results in yaml format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `yamlSources` -- the top-level transient data
- `yamlPhot` -- all photometry associated with the transient... | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L359-L430 | [
"def _file_prefix(\n self):\n \"\"\"*Generate a file prefix based on the type of search for saving files to disk*\n\n **Return:**\n - ``prefix`` -- the file prefix\n \"\"\"\n self.log.info('starting the ``_file_prefix`` method')\n\n if self.ra:\n now = datetime.now()\n pre... | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search.markdown | python | def markdown(
self,
dirPath=None):
if dirPath:
p = self._file_prefix()
markdownSources = self.sourceResults.markdown(
filepath=dirPath + "/" + p + "sources.md")
markdownPhot = self.photResults.markdown(
filepath=dirPath... | *Render the results in markdown format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `markdownSources` -- the top-level transient data
- `markdownPhot` -- all photometry associated with t... | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L432-L487 | [
"def _file_prefix(\n self):\n \"\"\"*Generate a file prefix based on the type of search for saving files to disk*\n\n **Return:**\n - ``prefix`` -- the file prefix\n \"\"\"\n self.log.info('starting the ``_file_prefix`` method')\n\n if self.ra:\n now = datetime.now()\n pre... | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search.table | python | def table(
self,
dirPath=None):
if dirPath:
p = self._file_prefix()
tableSources = self.sourceResults.table(
filepath=dirPath + "/" + p + "sources.ascii")
tablePhot = self.photResults.table(
filepath=dirPath + "/" + p +... | *Render the results as an ascii table*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `tableSources` -- the top-level transient data
- `tablePhot` -- all photometry associated with the tran... | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L489-L546 | [
"def _file_prefix(\n self):\n \"\"\"*Generate a file prefix based on the type of search for saving files to disk*\n\n **Return:**\n - ``prefix`` -- the file prefix\n \"\"\"\n self.log.info('starting the ``_file_prefix`` method')\n\n if self.ra:\n now = datetime.now()\n pre... | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search.mysql | python | def mysql(
self,
tableNamePrefix="TNS",
dirPath=None):
if dirPath:
p = self._file_prefix()
createStatement = """
CREATE TABLE `%(tableNamePrefix)s_sources` (
`primaryId` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'An internal counter',
`TNSId` var... | *Render the results as MySQL Insert statements*
**Key Arguments:**
- ``tableNamePrefix`` -- the prefix for the database table names to assign the insert statements to. Default *TNS*.
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Re... | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L548-L704 | [
"def _file_prefix(\n self):\n \"\"\"*Generate a file prefix based on the type of search for saving files to disk*\n\n **Return:**\n - ``prefix`` -- the file prefix\n \"\"\"\n self.log.info('starting the ``_file_prefix`` method')\n\n if self.ra:\n now = datetime.now()\n pre... | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search._query_tns | python | def _query_tns(self):
self.log.info('starting the ``get`` method')
sourceTable = []
photoTable = []
specTable = []
relatedFilesTable = []
# THIS stop IS TO KEEP TRACK OF THE TNS PAGINATION IF MANY RESULT PAGES
# ARE RETURNED
stop = False
sourceC... | *determine how to query the TNS, send query and parse the results*
**Return:**
- ``results`` -- a list of dictionaries (one dictionary for each result set returned from the TNS) | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L706-L777 | [
"def _get_tns_search_results(\n self):\n \"\"\"\n *query the tns and result the response*\n \"\"\"\n self.log.info('starting the ``_get_tns_search_results`` method')\n\n try:\n response = requests.get(\n url=\"http://wis-tns.weizmann.ac.il/search\",\n params={\n ... | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search._get_tns_search_results | python | def _get_tns_search_results(
self):
self.log.info('starting the ``_get_tns_search_results`` method')
try:
response = requests.get(
url="http://wis-tns.weizmann.ac.il/search",
params={
"page": self.page,
"ra"... | *query the tns and result the response* | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L779-L818 | null | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search._file_prefix | python | def _file_prefix(
self):
self.log.info('starting the ``_file_prefix`` method')
if self.ra:
now = datetime.now()
prefix = now.strftime("%Y%m%dt%H%M%S%f_tns_conesearch_")
elif self.name:
prefix = self.name + "_tns_conesearch_"
elif self.inte... | *Generate a file prefix based on the type of search for saving files to disk*
**Return:**
- ``prefix`` -- the file prefix | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L820-L843 | null | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search._parse_transient_rows | python | def _parse_transient_rows(
self,
content,
count=False):
self.log.info('starting the ``_parse_transient_rows`` method')
regexForRow = r"""\n([^\n]*?<a href="/object/.*?)(?=\n[^\n]*?<a href="/object/|<\!\-\- /\.section, /#content \-\->)"""
if count:
... | * parse transient rows from the TNS result page content*
**Key Arguments:**
- ``content`` -- the content from the TNS results page.
- ``count`` -- return only the number of rows
**Return:**
- ``transientRows`` | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L845-L879 | null | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search._parse_discovery_information | python | def _parse_discovery_information(
self,
content):
self.log.info('starting the ``_parse_discovery_information`` method')
# ASTROCALC UNIT CONVERTER OBJECT
converter = unit_conversion(
log=self.log
)
matches = re.finditer(
r"""<tr c... | * parse discovery information from one row on the TNS results page*
**Key Arguments:**
- ``content`` -- a table row from the TNS results page.
**Return:**
- ``discoveryData`` -- dictionary of results
- ``TNSId`` -- the unique TNS id for the transient | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L881-L971 | null | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search._parse_photometry_data | python | def _parse_photometry_data(
self,
content,
TNSId):
self.log.info('starting the ``_parse_photometry_data`` method')
photData = []
relatedFilesTable = []
# AT REPORT BLOCK
ATBlock = re.search(
r"""<tr class=[^\n]*?AT reportings.*?(?... | *parse photometry data from a row in the tns results content*
**Key Arguments:**
- ``content`` -- a table row from the TNS results page
- ``TNSId`` -- the tns id of the transient
**Return:**
- ``photData`` -- a list of dictionaries of the photometry data
... | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L973-L1106 | null | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search._parse_related_files | python | def _parse_related_files(
self,
content):
self.log.info('starting the ``_parse_related_files`` method')
relatedFilesList = re.finditer(
r"""<td class="cell-filename">.*?href="(?P<filepath>[^"]*).*?remarks">(?P<fileComment>[^<]*)""",
content,
f... | *parse the contents for related files URLs and comments*
**Key Arguments:**
- ``content`` -- the content to parse.
**Return:**
- ``relatedFiles`` -- a list of dictionaries of transient related files | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L1108-L1133 | null | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/search.py | search._parse_spectral_data | python | def _parse_spectral_data(
self,
content,
TNSId):
self.log.info('starting the ``_parse_spectral_data`` method')
specData = []
relatedFilesTable = []
# CLASSIFICATION BLOCK
classBlock = re.search(
r"""<tr class=[^\n]*?Classification... | *parse spectra data from a row in the tns results content*
**Key Arguments:**
- ``content`` -- a table row from the TNS results page
- ``TNSId`` -- the tns id of the transient
**Return:**
- ``specData`` -- a list of dictionaries of the spectral data
- ... | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L1135-L1273 | null | class search():
"""
*The worker class for the transient namer search module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra`` -- RA of the location being checked
- ``dec`` -- DEC of the location being searched
- ``radiusArcsec... |
thespacedoctor/transientNamer | transientNamer/cl_utils.py | main | python | def main(arguments=None):
# setup the command-line util settings
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="WARNING",
options_first=False,
projectName="transientNamer"
)
arguments, settings, log, dbConn = su.setup()
# tab completion for raw... | *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* | train | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/cl_utils.py#L49-L162 | [
"def csv(\n self,\n dirPath=None):\n \"\"\"*Render the results in csv format*\n\n **Key Arguments:**\n - ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*\n\n **Return:**\n - `csvSources` -- the top-level transient data\n - `csvPhot`... | #!/usr/local/bin/python
# encoding: utf-8
"""
Documentation for transientNamer can be found here: http://transientNamer.readthedocs.org/en/stable
Usage:
transientNamer [-c] cone <ra> <dec> <arcsecRadius> [<render> | mysql <tableNamePrefix>] [-o directory]
transientNamer [-c] search <name> [<render> | mysql <ta... |
watchforstock/evohome-client | evohomeclient2/location.py | Location.status | python | def status(self):
response = requests.get(
"https://tccna.honeywell.com/WebAPI/emea/api/v1/"
"location/%s/status?includeTemperatureControlSystems=True" %
self.locationId,
headers=self.client._headers() # pylint: disable=protec... | Retrieves the location status. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/location.py#L26-L55 | null | class Location(object): # pylint: disable=too-few-public-methods,useless-object-inheritance
"""Provides handling of a location."""
def __init__(self, client, data=None):
self.client = client
self._gateways = []
self.gateways = {}
... |
watchforstock/evohome-client | evohomeclient2/hotwater.py | HotWater.set_dhw_on | python | def set_dhw_on(self, until=None):
if until is None:
data = {"Mode": "PermanentOverride",
"State": "On",
"UntilTime": None}
else:
data = {"Mode": "TemporaryOverride",
"State": "On",
"UntilTime": until.... | Sets the DHW on until a given time, or permanently. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/hotwater.py#L34-L45 | [
"def _set_dhw(self, data):\n headers = dict(self.client._headers()) # pylint: disable=protected-access\n headers['Content-Type'] = 'application/json'\n url = (\n \"https://tccna.honeywell.com/WebAPI/emea/api/v1\"\n \"/domesticHotWater/%s/state\" % self.dhwId\... | class HotWater(ZoneBase):
"""Provides handling of the hot water zone."""
def __init__(self, client, data):
super(HotWater, self).__init__(client)
self.dhwId = None # pylint: disable=invalid-name
self.__dict__.update(data)
... |
watchforstock/evohome-client | evohomeclient2/hotwater.py | HotWater.set_dhw_off | python | def set_dhw_off(self, until=None):
if until is None:
data = {"Mode": "PermanentOverride",
"State": "Off",
"UntilTime": None}
else:
data = {"Mode": "TemporaryOverride",
"State": "Off",
"UntilTime": unt... | Sets the DHW off until a given time, or permanently. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/hotwater.py#L47-L58 | [
"def _set_dhw(self, data):\n headers = dict(self.client._headers()) # pylint: disable=protected-access\n headers['Content-Type'] = 'application/json'\n url = (\n \"https://tccna.honeywell.com/WebAPI/emea/api/v1\"\n \"/domesticHotWater/%s/state\" % self.dhwId\... | class HotWater(ZoneBase):
"""Provides handling of the hot water zone."""
def __init__(self, client, data):
super(HotWater, self).__init__(client)
self.dhwId = None # pylint: disable=invalid-name
self.__dict__.update(data)
... |
watchforstock/evohome-client | evohomeclient2/zone.py | ZoneBase.schedule | python | def schedule(self):
response = requests.get(
"https://tccna.honeywell.com/WebAPI/emea/api/v1"
"/%s/%s/schedule" % (self.zone_type, self.zoneId),
headers=self.client._headers() # pylint: disable=no-member,protected-access
)
... | Gets the schedule for the given zone | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/zone.py#L16-L42 | null | class ZoneBase(object): # pylint: disable=useless-object-inheritance
"""Provides the base for Zones"""
def __init__(self, client):
self.client = client
self.name = None
self.zoneId = None ... |
watchforstock/evohome-client | evohomeclient2/zone.py | ZoneBase.set_schedule | python | def set_schedule(self, zone_info):
# must only POST json, otherwise server API handler raises exceptions
try:
json.loads(zone_info)
except ValueError as error:
raise ValueError("zone_info must be valid JSON: ", error)
headers = dict(self.client._headers()) ... | Sets the schedule for this zone | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/zone.py#L44-L63 | null | class ZoneBase(object): # pylint: disable=useless-object-inheritance
"""Provides the base for Zones"""
def __init__(self, client):
self.client = client
self.name = None
self.zoneId = None ... |
watchforstock/evohome-client | evohomeclient/__init__.py | EvohomeClient.temperatures | python | def temperatures(self, force_refresh=False):
self._populate_full_data(force_refresh)
for device in self.full_data['devices']:
set_point = 0
status = ""
if 'heatSetpoint' in device['thermostat']['changeableValues']:
set_point = float(
... | Retrieve the current details for each zone. Returns a generator. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L115-L133 | [
"def _populate_full_data(self, force_refresh=False):\n if self.full_data is None or force_refresh:\n self._populate_user_info()\n\n user_id = self.user_data['userInfo']['userID']\n session_id = self.user_data['sessionId']\n\n url = (self.hostname + \"/WebAPI/api/locations\"\n ... | class EvohomeClient(object): # pylint: disable=useless-object-inheritance
"""Provides a client to access the Honeywell Evohome system"""
# pylint: disable=too-many-instance-attributes,too-many-arguments
def __init__(self, username, password, debug=False, user_data=None,
hostname="https://... |
watchforstock/evohome-client | evohomeclient/__init__.py | EvohomeClient.get_modes | python | def get_modes(self, zone):
self._populate_full_data()
device = self._get_device(zone)
return device['thermostat']['allowedModes'] | Returns the set of modes the device can be assigned. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L135-L139 | [
"def _populate_full_data(self, force_refresh=False):\n if self.full_data is None or force_refresh:\n self._populate_user_info()\n\n user_id = self.user_data['userInfo']['userID']\n session_id = self.user_data['sessionId']\n\n url = (self.hostname + \"/WebAPI/api/locations\"\n ... | class EvohomeClient(object): # pylint: disable=useless-object-inheritance
"""Provides a client to access the Honeywell Evohome system"""
# pylint: disable=too-many-instance-attributes,too-many-arguments
def __init__(self, username, password, debug=False, user_data=None,
hostname="https://... |
watchforstock/evohome-client | evohomeclient/__init__.py | EvohomeClient.set_temperature | python | def set_temperature(self, zone, temperature, until=None):
if until is None:
data = {"Value": temperature, "Status": "Hold", "NextTime": None}
else:
data = {"Value": temperature,
"Status": "Temporary",
"NextTime": until.strftime('%Y-%m-%dT%H... | Sets the temperature of the given zone. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L266-L275 | [
"def _set_heat_setpoint(self, zone, data):\n self._populate_full_data()\n\n device_id = self._get_device_id(zone)\n\n url = (self.hostname + \"/WebAPI/api/devices\"\n \"/%s/thermostat/changeableValues/heatSetpoint\" % device_id)\n\n response = self._do_request('put', url, json.dumps(data))\n\n... | class EvohomeClient(object): # pylint: disable=useless-object-inheritance
"""Provides a client to access the Honeywell Evohome system"""
# pylint: disable=too-many-instance-attributes,too-many-arguments
def __init__(self, username, password, debug=False, user_data=None,
hostname="https://... |
watchforstock/evohome-client | evohomeclient/__init__.py | EvohomeClient._set_dhw | python | def _set_dhw(self, status="Scheduled", mode=None, next_time=None):
data = {"Status": status,
"Mode": mode,
"NextTime": next_time,
"SpecialModes": None,
"HeatSetpoint": None,
"CoolSetpoint": None}
self._populate_full_data()
... | Set DHW to On, Off or Auto, either indefinitely, or until a
specified time. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L288-L311 | [
"def _populate_full_data(self, force_refresh=False):\n if self.full_data is None or force_refresh:\n self._populate_user_info()\n\n user_id = self.user_data['userInfo']['userID']\n session_id = self.user_data['sessionId']\n\n url = (self.hostname + \"/WebAPI/api/locations\"\n ... | class EvohomeClient(object): # pylint: disable=useless-object-inheritance
"""Provides a client to access the Honeywell Evohome system"""
# pylint: disable=too-many-instance-attributes,too-many-arguments
def __init__(self, username, password, debug=False, user_data=None,
hostname="https://... |
watchforstock/evohome-client | evohomeclient/__init__.py | EvohomeClient.set_dhw_on | python | def set_dhw_on(self, until=None):
time_until = None if until is None else until.strftime(
'%Y-%m-%dT%H:%M:%SZ')
self._set_dhw(status="Hold", mode="DHWOn", next_time=time_until) | Set DHW to on, either indefinitely, or until a specified time.
When On, the DHW controller will work to keep its target temperature
at/above its target temperature. After the specified time, it will
revert to its scheduled behaviour. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L313-L324 | [
"def _set_dhw(self, status=\"Scheduled\", mode=None, next_time=None):\n \"\"\"Set DHW to On, Off or Auto, either indefinitely, or until a\n specified time.\n \"\"\"\n data = {\"Status\": status,\n \"Mode\": mode,\n \"NextTime\": next_time,\n \"SpecialModes\": None,\n ... | class EvohomeClient(object): # pylint: disable=useless-object-inheritance
"""Provides a client to access the Honeywell Evohome system"""
# pylint: disable=too-many-instance-attributes,too-many-arguments
def __init__(self, username, password, debug=False, user_data=None,
hostname="https://... |
watchforstock/evohome-client | evohomeclient2/__init__.py | EvohomeClient._headers | python | def _headers(self):
if not self.access_token or not self.access_token_expires:
self._basic_login()
elif datetime.now() > self.access_token_expires - timedelta(seconds=30):
self._basic_login()
return {'Accept': HEADER_ACCEPT,
'Authorization': 'bearer ' + ... | Ensure the Authorization Header has a valid Access Token. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L84-L93 | [
"def _basic_login(self):\n \"\"\"Obtain a new access token from the vendor.\n\n First, try using the refresh_token, if one is available, otherwise\n authenticate using the user credentials.\n \"\"\"\n _LOGGER.debug(\"No/Expired/Invalid access_token, re-authenticating...\")\n self.access_token = se... | class EvohomeClient(object): # pylint: disable=too-many-instance-attributes,useless-object-inheritance
"""Provides access to the v2 Evohome API."""
def __init__(self, username, password, debug=False, refresh_token=None, # pylint: disable=too-many-argumen... |
watchforstock/evohome-client | evohomeclient2/__init__.py | EvohomeClient._basic_login | python | def _basic_login(self):
_LOGGER.debug("No/Expired/Invalid access_token, re-authenticating...")
self.access_token = self.access_token_expires = None
if self.refresh_token:
_LOGGER.debug("Trying refresh_token...")
credentials = {'grant_type': "refresh_token",
... | Obtain a new access token from the vendor.
First, try using the refresh_token, if one is available, otherwise
authenticate using the user credentials. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L95-L130 | null | class EvohomeClient(object): # pylint: disable=too-many-instance-attributes,useless-object-inheritance
"""Provides access to the v2 Evohome API."""
def __init__(self, username, password, debug=False, refresh_token=None, # pylint: disable=too-many-argumen... |
watchforstock/evohome-client | evohomeclient2/__init__.py | EvohomeClient.user_account | python | def user_account(self):
self.account_info = None
url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount'
response = requests.get(url, headers=self._headers())
response.raise_for_status()
self.account_info = response.json()
return self.account_info | Return the user account information. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L192-L202 | [
"def _headers(self):\n \"\"\"Ensure the Authorization Header has a valid Access Token.\"\"\"\n if not self.access_token or not self.access_token_expires:\n self._basic_login()\n\n elif datetime.now() > self.access_token_expires - timedelta(seconds=30):\n self._basic_login()\n\n return {'Ac... | class EvohomeClient(object): # pylint: disable=too-many-instance-attributes,useless-object-inheritance
"""Provides access to the v2 Evohome API."""
def __init__(self, username, password, debug=False, refresh_token=None, # pylint: disable=too-many-argumen... |
watchforstock/evohome-client | evohomeclient2/__init__.py | EvohomeClient.installation | python | def installation(self):
self.locations = []
url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location"
"/installationInfo?userId=%s"
"&includeTemperatureControlSystems=True"
% self.account_info['userId'])
response = requests.get(url, headers=s... | Return the details of the installation. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L204-L223 | [
"def _headers(self):\n \"\"\"Ensure the Authorization Header has a valid Access Token.\"\"\"\n if not self.access_token or not self.access_token_expires:\n self._basic_login()\n\n elif datetime.now() > self.access_token_expires - timedelta(seconds=30):\n self._basic_login()\n\n return {'Ac... | class EvohomeClient(object): # pylint: disable=too-many-instance-attributes,useless-object-inheritance
"""Provides access to the v2 Evohome API."""
def __init__(self, username, password, debug=False, refresh_token=None, # pylint: disable=too-many-argumen... |
watchforstock/evohome-client | evohomeclient2/__init__.py | EvohomeClient.full_installation | python | def full_installation(self, location=None):
url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location"
"/%s/installationInfo?includeTemperatureControlSystems=True"
% self._get_location(location))
response = requests.get(url, headers=self._headers())
response.... | Return the full details of the installation. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L225-L234 | [
"def _headers(self):\n \"\"\"Ensure the Authorization Header has a valid Access Token.\"\"\"\n if not self.access_token or not self.access_token_expires:\n self._basic_login()\n\n elif datetime.now() > self.access_token_expires - timedelta(seconds=30):\n self._basic_login()\n\n return {'Ac... | class EvohomeClient(object): # pylint: disable=too-many-instance-attributes,useless-object-inheritance
"""Provides access to the v2 Evohome API."""
def __init__(self, username, password, debug=False, refresh_token=None, # pylint: disable=too-many-argumen... |
watchforstock/evohome-client | evohomeclient2/__init__.py | EvohomeClient.gateway | python | def gateway(self):
url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway'
response = requests.get(url, headers=self._headers())
response.raise_for_status()
return response.json() | Return the detail of the gateway. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L236-L243 | [
"def _headers(self):\n \"\"\"Ensure the Authorization Header has a valid Access Token.\"\"\"\n if not self.access_token or not self.access_token_expires:\n self._basic_login()\n\n elif datetime.now() > self.access_token_expires - timedelta(seconds=30):\n self._basic_login()\n\n return {'Ac... | class EvohomeClient(object): # pylint: disable=too-many-instance-attributes,useless-object-inheritance
"""Provides access to the v2 Evohome API."""
def __init__(self, username, password, debug=False, refresh_token=None, # pylint: disable=too-many-argumen... |
watchforstock/evohome-client | evohomeclient2/controlsystem.py | ControlSystem.temperatures | python | def temperatures(self):
self.location.status()
if self.hotwater:
yield {
'thermostat': 'DOMESTIC_HOT_WATER',
'id': self.hotwater.dhwId,
'name': '',
'temp': self.hotwater.temperatureStatus['temperature'], # pylint: disa... | Return a generator with the details of each zone. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L92-L116 | null | class ControlSystem(object): # pylint: disable=useless-object-inheritance, too-many-instance-attributes
"""Provides handling of a control system."""
def __init__(self, client, location, gateway, data=None):
self.client = client
self.location =... |
watchforstock/evohome-client | evohomeclient2/controlsystem.py | ControlSystem.zone_schedules_backup | python | def zone_schedules_backup(self, filename):
_LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...",
self.systemId, self.location.name)
schedules = {}
if self.hotwater:
_LOGGER.info("Retrieving DHW schedule: %s...",
self.hotwa... | Backup all zones on control system to the given file. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L118-L149 | null | class ControlSystem(object): # pylint: disable=useless-object-inheritance, too-many-instance-attributes
"""Provides handling of a control system."""
def __init__(self, client, location, gateway, data=None):
self.client = client
self.location =... |
watchforstock/evohome-client | evohomeclient2/controlsystem.py | ControlSystem.zone_schedules_restore | python | def zone_schedules_restore(self, filename):
_LOGGER.info("Restoring schedules to ControlSystem %s (%s)...",
self.systemId, self.location)
_LOGGER.info("Reading from backup file: %s...", filename)
with open(filename, 'r') as file_input:
schedule_db = file_input.r... | Restore all zones on control system from the given file. | train | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L151-L174 | null | class ControlSystem(object): # pylint: disable=useless-object-inheritance, too-many-instance-attributes
"""Provides handling of a control system."""
def __init__(self, client, location, gateway, data=None):
self.client = client
self.location =... |
gtalarico/airtable-python-wrapper | airtable/params.py | _BaseObjectArrayParam.to_param_dict | python | def to_param_dict(self):
""" Sorts to ensure Order is consistent for Testing """
param_dict = {}
for index, dictionary in enumerate(self.value):
for key, value in dictionary.items():
param_name = '{param_name}[{index}][{key}]'.format(
... | Sorts to ensure Order is consistent for Testing | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/params.py#L68-L78 | null | class _BaseObjectArrayParam(_BaseParam):
"""
Api Expects Array of Objects:
>>> [{field: "UUID", direction: "desc"}, {...}]
Requests Params Input:
>>> params={'sort': ['FieldOne', '-FieldTwo']}
or
>>> params={'sort': [('FieldOne', 'asc'), ('-FieldTwo', 'desc')]}
Requests Url Params Enco... |
gtalarico/airtable-python-wrapper | airtable/params.py | AirtableParams._discover_params | python | def _discover_params(cls):
"""
Returns a dict where filter keyword is key, and class is value.
To handle param alias (maxRecords or max_records), both versions are
added.
"""
try:
return cls.filters
except AttributeError:
filters... | Returns a dict where filter keyword is key, and class is value.
To handle param alias (maxRecords or max_records), both versions are
added. | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/params.py#L342-L359 | null | class AirtableParams():
class MaxRecordsParam(_BaseParam):
"""
Max Records Param
Kwargs:
``max_records=`` or ``maxRecords=``
The maximum total number of records that will be returned.
Usage:
>>> airtable.get_all(max_records=10)
Args:
... |
gtalarico/airtable-python-wrapper | airtable/params.py | AirtableParams._get | python | def _get(cls, kwarg_name):
""" Returns a Param Class Instance, by its kwarg or param name """
param_classes = cls._discover_params()
try:
param_class = param_classes[kwarg_name]
except KeyError:
raise ValueError('invalid param keyword {}'.format(kwarg_name))... | Returns a Param Class Instance, by its kwarg or param name | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/params.py#L362-L370 | null | class AirtableParams():
class MaxRecordsParam(_BaseParam):
"""
Max Records Param
Kwargs:
``max_records=`` or ``maxRecords=``
The maximum total number of records that will be returned.
Usage:
>>> airtable.get_all(max_records=10)
Args:
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable._process_params | python | def _process_params(self, params):
"""
Process params names or values as needed using filters
"""
new_params = OrderedDict()
for param_name, param_value in sorted(params.items()):
param_value = params[param_name]
ParamClass = AirtableParams._get(par... | Process params names or values as needed using filters | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L141-L150 | null | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.get | python | def get(self, record_id):
"""
Retrieves a record by its id
>>> record = airtable.get('recwPQIfs4wKPyc9D')
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Record
"""
record_url = self.record_url(record... | Retrieves a record by its id
>>> record = airtable.get('recwPQIfs4wKPyc9D')
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Record | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L202-L215 | [
"def record_url(self, record_id):\n \"\"\" Builds URL with record id \"\"\"\n return posixpath.join(self.url_table, record_id)\n",
"def _get(self, url, **params):\n processed_params = self._process_params(params)\n return self._request('get', url, params=processed_params)\n"
] | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.get_iter | python | def get_iter(self, **options):
"""
Record Retriever Iterator
Returns iterator with lists in batches according to pageSize.
To get all records at once use :any:`get_all`
>>> for page in airtable.get_iter():
... for record in page:
... print(r... | Record Retriever Iterator
Returns iterator with lists in batches according to pageSize.
To get all records at once use :any:`get_all`
>>> for page in airtable.get_iter():
... for record in page:
... print(record)
[{'fields': ... }, ...]
Ke... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L217-L256 | [
"def _get(self, url, **params):\n processed_params = self._process_params(params)\n return self._request('get', url, params=processed_params)\n"
] | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.get_all | python | def get_all(self, **options):
"""
Retrieves all records repetitively and returns a single list.
>>> airtable.get_all()
>>> airtable.get_all(view='MyView', fields=['ColA', '-ColB'])
>>> airtable.get_all(maxRecords=50)
[{'fields': ... }, ...]
Keyword Args... | Retrieves all records repetitively and returns a single list.
>>> airtable.get_all()
>>> airtable.get_all(view='MyView', fields=['ColA', '-ColB'])
>>> airtable.get_all(maxRecords=50)
[{'fields': ... }, ...]
Keyword Args:
max_records (``int``, optional): The ... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L258-L288 | [
"def get_iter(self, **options):\n \"\"\"\n Record Retriever Iterator\n\n Returns iterator with lists in batches according to pageSize.\n To get all records at once use :any:`get_all`\n\n >>> for page in airtable.get_iter():\n ... for record in page:\n ... print(record)\n [{'field... | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.match | python | def match(self, field_name, field_value, **options):
"""
Returns first match found in :any:`get_all`
>>> airtable.match('Name', 'John')
{'fields': {'Name': 'John'} }
Args:
field_name (``str``): Name of field to match (column name).
field_value (... | Returns first match found in :any:`get_all`
>>> airtable.match('Name', 'John')
{'fields': {'Name': 'John'} }
Args:
field_name (``str``): Name of field to match (column name).
field_value (``str``): Value of field to match.
Keyword Args:
ma... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L290-L320 | [
"def get_all(self, **options):\n \"\"\"\n Retrieves all records repetitively and returns a single list.\n\n >>> airtable.get_all()\n >>> airtable.get_all(view='MyView', fields=['ColA', '-ColB'])\n >>> airtable.get_all(maxRecords=50)\n [{'fields': ... }, ...]\n\n Keyword Args:\n max_recor... | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.search | python | def search(self, field_name, field_value, record=None, **options):
"""
Returns all matching records found in :any:`get_all`
>>> airtable.search('Gender', 'Male')
[{'fields': {'Name': 'John', 'Gender': 'Male'}, ... ]
Args:
field_name (``str``): Name of field ... | Returns all matching records found in :any:`get_all`
>>> airtable.search('Gender', 'Male')
[{'fields': {'Name': 'John', 'Gender': 'Male'}, ... ]
Args:
field_name (``str``): Name of field to match (column name).
field_value (``str``): Value of field to match.
... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L322-L352 | [
"def get_all(self, **options):\n \"\"\"\n Retrieves all records repetitively and returns a single list.\n\n >>> airtable.get_all()\n >>> airtable.get_all(view='MyView', fields=['ColA', '-ColB'])\n >>> airtable.get_all(maxRecords=50)\n [{'fields': ... }, ...]\n\n Keyword Args:\n max_recor... | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.insert | python | def insert(self, fields, typecast=False):
"""
Inserts a record
>>> record = {'Name': 'John'}
>>> airtable.insert(record)
Args:
fields(``dict``): Fields to insert.
Must be dictionary with Column names as Key.
typecast(``boolean``... | Inserts a record
>>> record = {'Name': 'John'}
>>> airtable.insert(record)
Args:
fields(``dict``): Fields to insert.
Must be dictionary with Column names as Key.
typecast(``boolean``): Automatic data conversion from string values.
Retu... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L354-L370 | [
"def _post(self, url, json_data):\n return self._request('post', url, json_data=json_data)\n"
] | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable._batch_request | python | def _batch_request(self, func, iterable):
""" Internal Function to limit batch calls to API limit """
responses = []
for item in iterable:
responses.append(func(item))
time.sleep(self.API_LIMIT)
return responses | Internal Function to limit batch calls to API limit | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L372-L378 | [
"def insert(self, fields, typecast=False):\n \"\"\"\n Inserts a record\n\n >>> record = {'Name': 'John'}\n >>> airtable.insert(record)\n\n Args:\n fields(``dict``): Fields to insert.\n Must be dictionary with Column names as Key.\n typecast(``boolean``): Automatic data conver... | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.batch_insert | python | def batch_insert(self, records, typecast=False):
"""
Calls :any:`insert` repetitively, following set API Rate Limit (5/sec)
To change the rate limit use ``airtable.API_LIMIT = 0.2``
(5 per second)
>>> records = [{'Name': 'John'}, {'Name': 'Marc'}]
>>> airtable.bat... | Calls :any:`insert` repetitively, following set API Rate Limit (5/sec)
To change the rate limit use ``airtable.API_LIMIT = 0.2``
(5 per second)
>>> records = [{'Name': 'John'}, {'Name': 'Marc'}]
>>> airtable.batch_insert(records)
Args:
records(``list``): Rec... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L380-L397 | [
"def _batch_request(self, func, iterable):\n \"\"\" Internal Function to limit batch calls to API limit \"\"\"\n responses = []\n for item in iterable:\n responses.append(func(item))\n time.sleep(self.API_LIMIT)\n return responses\n"
] | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.update | python | def update(self, record_id, fields, typecast=False):
"""
Updates a record by its record id.
Only Fields passed are updated, the rest are left as is.
>>> record = airtable.match('Employee Id', 'DD13332454')
>>> fields = {'Status': 'Fired'}
>>> airtable.update(recor... | Updates a record by its record id.
Only Fields passed are updated, the rest are left as is.
>>> record = airtable.match('Employee Id', 'DD13332454')
>>> fields = {'Status': 'Fired'}
>>> airtable.update(record['id'], fields)
Args:
record_id(``str``): Id of Re... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L399-L418 | [
"def record_url(self, record_id):\n \"\"\" Builds URL with record id \"\"\"\n return posixpath.join(self.url_table, record_id)\n",
"def _patch(self, url, json_data):\n return self._request('patch', url, json_data=json_data)\n"
] | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.update_by_field | python | def update_by_field(self, field_name, field_value, fields, typecast=False, **options):
"""
Updates the first record to match field name and value.
Only Fields passed are updated, the rest are left as is.
>>> record = {'Name': 'John', 'Tel': '540-255-5522'}
>>> airtable.upd... | Updates the first record to match field name and value.
Only Fields passed are updated, the rest are left as is.
>>> record = {'Name': 'John', 'Tel': '540-255-5522'}
>>> airtable.update_by_field('Name', 'John', record)
Args:
field_name (``str``): Name of field to mat... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L420-L445 | [
"def match(self, field_name, field_value, **options):\n \"\"\"\n Returns first match found in :any:`get_all`\n\n >>> airtable.match('Name', 'John')\n {'fields': {'Name': 'John'} }\n\n Args:\n field_name (``str``): Name of field to match (column name).\n field_value (``str``): Value of f... | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.replace | python | def replace(self, record_id, fields, typecast=False):
"""
Replaces a record by its record id.
All Fields are updated to match the new ``fields`` provided.
If a field is not included in ``fields``, value will bet set to null.
To update only selected fields, use :any:`update`.... | Replaces a record by its record id.
All Fields are updated to match the new ``fields`` provided.
If a field is not included in ``fields``, value will bet set to null.
To update only selected fields, use :any:`update`.
>>> record = airtable.match('Seat Number', '22A')
>>> f... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L447-L468 | [
"def record_url(self, record_id):\n \"\"\" Builds URL with record id \"\"\"\n return posixpath.join(self.url_table, record_id)\n",
"def _put(self, url, json_data):\n return self._request('put', url, json_data=json_data)\n"
] | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.replace_by_field | python | def replace_by_field(self, field_name, field_value, fields, typecast=False, **options):
"""
Replaces the first record to match field name and value.
All Fields are updated to match the new ``fields`` provided.
If a field is not included in ``fields``, value will bet set to null.
... | Replaces the first record to match field name and value.
All Fields are updated to match the new ``fields`` provided.
If a field is not included in ``fields``, value will bet set to null.
To update only selected fields, use :any:`update`.
Args:
field_name (``str``): Na... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L470-L494 | [
"def match(self, field_name, field_value, **options):\n \"\"\"\n Returns first match found in :any:`get_all`\n\n >>> airtable.match('Name', 'John')\n {'fields': {'Name': 'John'} }\n\n Args:\n field_name (``str``): Name of field to match (column name).\n field_value (``str``): Value of f... | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.delete | python | def delete(self, record_id):
"""
Deletes a record by its id
>>> record = airtable.match('Employee Id', 'DD13332454')
>>> airtable.delete(record['id'])
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Deleted Re... | Deletes a record by its id
>>> record = airtable.match('Employee Id', 'DD13332454')
>>> airtable.delete(record['id'])
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Deleted Record | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L496-L510 | [
"def record_url(self, record_id):\n \"\"\" Builds URL with record id \"\"\"\n return posixpath.join(self.url_table, record_id)\n",
"def _delete(self, url):\n return self._request('delete', url)\n"
] | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.delete_by_field | python | def delete_by_field(self, field_name, field_value, **options):
"""
Deletes first record to match provided ``field_name`` and
``field_value``.
>>> record = airtable.delete_by_field('Employee Id', 'DD13332454')
Args:
field_name (``str``): Name of field to mat... | Deletes first record to match provided ``field_name`` and
``field_value``.
>>> record = airtable.delete_by_field('Employee Id', 'DD13332454')
Args:
field_name (``str``): Name of field to match (column name).
field_value (``str``): Value of field to match.
... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L512-L534 | [
"def record_url(self, record_id):\n \"\"\" Builds URL with record id \"\"\"\n return posixpath.join(self.url_table, record_id)\n",
"def _delete(self, url):\n return self._request('delete', url)\n",
"def match(self, field_name, field_value, **options):\n \"\"\"\n Returns first match found in :any:... | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable.mirror | python | def mirror(self, records, **options):
"""
Deletes all records on table or view and replaces with records.
>>> records = [{'Name': 'John'}, {'Name': 'Marc'}]
>>> record = airtable.,mirror(records)
If view options are provided, only records visible on that view will
... | Deletes all records on table or view and replaces with records.
>>> records = [{'Name': 'John'}, {'Name': 'Marc'}]
>>> record = airtable.,mirror(records)
If view options are provided, only records visible on that view will
be deleted.
>>> record = airtable.mirror(rec... | train | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L554-L584 | [
"def get_all(self, **options):\n \"\"\"\n Retrieves all records repetitively and returns a single list.\n\n >>> airtable.get_all()\n >>> airtable.get_all(view='MyView', fields=['ColA', '-ColB'])\n >>> airtable.get_all(maxRecords=50)\n [{'fields': ... }, ...]\n\n Keyword Args:\n max_recor... | class Airtable():
VERSION = 'v0'
API_BASE_URL = 'https://api.airtable.com/'
API_LIMIT = 1.0 / 5 # 5 per second
API_URL = posixpath.join(API_BASE_URL, VERSION)
def __init__(self, base_key, table_name, api_key=None):
"""
If api_key is not provided, :any:`AirtableAuth` will attempt
... |
adamrehn/slidingwindow | slidingwindow/SlidingWindow.py | generate | python | def generate(data, dimOrder, maxWindowSize, overlapPercent, transforms = []):
# Determine the dimensions of the input data
width = data.shape[dimOrder.index('w')]
height = data.shape[dimOrder.index('h')]
# Generate the windows
return generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, trans... | Generates a set of sliding windows for the specified dataset. | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L87-L97 | [
"def generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, transforms = []):\n\t\"\"\"\n\tGenerates a set of sliding windows for a dataset with the specified dimensions and order.\n\t\"\"\"\n\n\t# If the input data is smaller than the specified window size,\n\t# clip the window size to the input s... | import math
class DimOrder(object):
"""
Represents the order of the dimensions in a dataset's shape.
"""
ChannelHeightWidth = ['c', 'h', 'w']
HeightWidthChannel = ['h', 'w', 'c']
class SlidingWindow(object):
"""
Represents a single window into a larger dataset.
"""
def __init__(self, x, y, w, h, dimOrder, ... |
adamrehn/slidingwindow | slidingwindow/SlidingWindow.py | generateForSize | python | def generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, transforms = []):
# If the input data is smaller than the specified window size,
# clip the window size to the input size on both dimensions
windowSizeX = min(maxWindowSize, width)
windowSizeY = min(maxWindowSize, height)
# Compute the... | Generates a set of sliding windows for a dataset with the specified dimensions and order. | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L100-L143 | null | import math
class DimOrder(object):
"""
Represents the order of the dimensions in a dataset's shape.
"""
ChannelHeightWidth = ['c', 'h', 'w']
HeightWidthChannel = ['h', 'w', 'c']
class SlidingWindow(object):
"""
Represents a single window into a larger dataset.
"""
def __init__(self, x, y, w, h, dimOrder, ... |
adamrehn/slidingwindow | slidingwindow/SlidingWindow.py | SlidingWindow.apply | python | def apply(self, matrix):
view = matrix[ self.indices() ]
return self.transform(view) if self.transform != None else view | Slices the supplied matrix and applies any transform bound to this window | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L27-L32 | [
"def indices(self, includeChannel=True):\n\t\"\"\"\n\tRetrieves the indices for this window as a tuple of slices\n\t\"\"\"\n\tif self.dimOrder == DimOrder.HeightWidthChannel:\n\n\t\t# Equivalent to [self.y:self.y+self.h+1, self.x:self.x+self.w+1]\n\t\treturn (\n\t\t\tslice(self.y, self.y+self.h),\n\t\t\tslice(self.... | class SlidingWindow(object):
"""
Represents a single window into a larger dataset.
"""
def __init__(self, x, y, w, h, dimOrder, transform = None):
"""
Creates a new window with the specified dimensions and transform
"""
self.x = x
self.y = y
self.w = w
self.h = h
self.dimOrder = dimOrder
self.tra... |
adamrehn/slidingwindow | slidingwindow/SlidingWindow.py | SlidingWindow.getRect | python | def getRect(self):
return (self.x, self.y, self.w, self.h) | Returns the window bounds as a tuple of (x,y,w,h) | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L34-L38 | null | class SlidingWindow(object):
"""
Represents a single window into a larger dataset.
"""
def __init__(self, x, y, w, h, dimOrder, transform = None):
"""
Creates a new window with the specified dimensions and transform
"""
self.x = x
self.y = y
self.w = w
self.h = h
self.dimOrder = dimOrder
self.tra... |
adamrehn/slidingwindow | slidingwindow/SlidingWindow.py | SlidingWindow.setRect | python | def setRect(self, rect):
self.x, self.y, self.w, self.h = rect | Sets the window bounds from a tuple of (x,y,w,h) | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L40-L44 | null | class SlidingWindow(object):
"""
Represents a single window into a larger dataset.
"""
def __init__(self, x, y, w, h, dimOrder, transform = None):
"""
Creates a new window with the specified dimensions and transform
"""
self.x = x
self.y = y
self.w = w
self.h = h
self.dimOrder = dimOrder
self.tra... |
adamrehn/slidingwindow | slidingwindow/SlidingWindow.py | SlidingWindow.indices | python | def indices(self, includeChannel=True):
if self.dimOrder == DimOrder.HeightWidthChannel:
# Equivalent to [self.y:self.y+self.h+1, self.x:self.x+self.w+1]
return (
slice(self.y, self.y+self.h),
slice(self.x, self.x+self.w)
)
elif self.dimOrder == DimOrder.ChannelHeightWidth:
if includ... | Retrieves the indices for this window as a tuple of slices | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L46-L78 | null | class SlidingWindow(object):
"""
Represents a single window into a larger dataset.
"""
def __init__(self, x, y, w, h, dimOrder, transform = None):
"""
Creates a new window with the specified dimensions and transform
"""
self.x = x
self.y = y
self.w = w
self.h = h
self.dimOrder = dimOrder
self.tra... |
adamrehn/slidingwindow | slidingwindow/Batching.py | batchWindows | python | def batchWindows(windows, batchSize):
return np.array_split(np.array(windows), len(windows) // batchSize) | Splits a list of windows into a series of batches. | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/Batching.py#L3-L7 | null | import numpy as np
|
adamrehn/slidingwindow | slidingwindow/WindowDistance.py | generateDistanceMatrix | python | def generateDistanceMatrix(width, height):
# Determine the coordinates of the exact centre of the window
originX = width / 2
originY = height / 2
# Generate the distance matrix
distances = zerosFactory((height,width), dtype=np.float)
for index, val in np.ndenumerate(distances):
y,x = index
distances[(y,x)... | Generates a matrix specifying the distance of each point in a window to its centre. | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/WindowDistance.py#L5-L20 | [
"def zerosFactory(shape, dtype=float):\n\t\"\"\"\n\tCreates a new NumPy array using `arrayFactory()` and fills it with zeros.\n\t\"\"\"\n\tarr = arrayFactory(shape=shape, dtype=dtype)\n\tarr.fill(0)\n\treturn arr\n"
] | from .ArrayUtils import *
import numpy as np
import math
def generateDistanceMatrix(width, height):
"""
Generates a matrix specifying the distance of each point in a window to its centre.
"""
# Determine the coordinates of the exact centre of the window
originX = width / 2
originY = height / 2
# Generate the ... |
adamrehn/slidingwindow | slidingwindow/RectangleUtils.py | cropRect | python | def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):
# Unpack the rectangle
x, y, w, h = rect
# Crop by the specified value
x += cropLeft
y += cropTop
w -= (cropLeft + cropRight)
h -= (cropTop + cropBottom)
# Re-pack the padded rect
return (x,y,w,h) | Crops a rectangle by the specified number of pixels on each side.
The input rectangle and return value are both a tuple of (x,y,w,h). | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/RectangleUtils.py#L4-L21 | null | import numpy as np
import math
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):
"""
Crops a rectangle by the specified number of pixels on each side.
The input rectangle and return value are both a tuple of (x,y,w,h).
"""
# Unpack the rectangle
x, y, w, h = rect
# Crop by the specified value
x ... |
adamrehn/slidingwindow | slidingwindow/RectangleUtils.py | padRect | python | def padRect(rect, padTop, padBottom, padLeft, padRight, bounds, clipExcess = True):
# Unpack the rectangle
x, y, w, h = rect
# Pad by the specified value
x -= padLeft
y -= padTop
w += (padLeft + padRight)
h += (padTop + padBottom)
# Determine if we are clipping overflows/underflows or
# shifting the cent... | Pads a rectangle by the specified values on each individual side,
ensuring the padded rectangle falls within the specified bounds.
The input rectangle, bounds, and return value are all a tuple of (x,y,w,h). | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/RectangleUtils.py#L24-L76 | [
"def padRect(rect, padTop, padBottom, padLeft, padRight, bounds, clipExcess = True):\n\t\"\"\"\n\tPads a rectangle by the specified values on each individual side,\n\tensuring the padded rectangle falls within the specified bounds.\n\n\tThe input rectangle, bounds, and return value are all a tuple of (x,y,w,h).\n\t... | import numpy as np
import math
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):
"""
Crops a rectangle by the specified number of pixels on each side.
The input rectangle and return value are both a tuple of (x,y,w,h).
"""
# Unpack the rectangle
x, y, w, h = rect
# Crop by the specified value
x ... |
adamrehn/slidingwindow | slidingwindow/RectangleUtils.py | padRectEqually | python | def padRectEqually(rect, padding, bounds, clipExcess = True):
return padRect(rect, padding, padding, padding, padding, bounds, clipExcess) | Applies equal padding to all sides of a rectangle,
ensuring the padded rectangle falls within the specified bounds.
The input rectangle, bounds, and return value are all a tuple of (x,y,w,h). | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/RectangleUtils.py#L88-L95 | [
"def padRect(rect, padTop, padBottom, padLeft, padRight, bounds, clipExcess = True):\n\t\"\"\"\n\tPads a rectangle by the specified values on each individual side,\n\tensuring the padded rectangle falls within the specified bounds.\n\n\tThe input rectangle, bounds, and return value are all a tuple of (x,y,w,h).\n\t... | import numpy as np
import math
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):
"""
Crops a rectangle by the specified number of pixels on each side.
The input rectangle and return value are both a tuple of (x,y,w,h).
"""
# Unpack the rectangle
x, y, w, h = rect
# Crop by the specified value
x ... |
adamrehn/slidingwindow | slidingwindow/RectangleUtils.py | squareAspect | python | def squareAspect(rect):
# Determine which dimension needs to be cropped
x,y,w,h = rect
if w > h:
cropX = (w - h) // 2
return cropRect(rect, 0, 0, cropX, cropX)
elif w < h:
cropY = (h - w) // 2
return cropRect(rect, cropY, cropY, 0, 0)
# Already a square
return rect | Crops either the width or height, as necessary, to make a rectangle into a square.
The input rectangle and return value are both a tuple of (x,y,w,h). | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/RectangleUtils.py#L98-L115 | [
"def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):\n\t\"\"\"\n\tCrops a rectangle by the specified number of pixels on each side.\n\n\tThe input rectangle and return value are both a tuple of (x,y,w,h).\n\t\"\"\"\n\n\t# Unpack the rectangle\n\tx, y, w, h = rect\n\n\t# Crop by the specified value\n\tx +=... | import numpy as np
import math
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):
"""
Crops a rectangle by the specified number of pixels on each side.
The input rectangle and return value are both a tuple of (x,y,w,h).
"""
# Unpack the rectangle
x, y, w, h = rect
# Crop by the specified value
x ... |
adamrehn/slidingwindow | slidingwindow/RectangleUtils.py | fitToSize | python | def fitToSize(rect, targetWidth, targetHeight, bounds):
# Determine the difference between the current size and target size
x,y,w,h = rect
diffX = w - targetWidth
diffY = h - targetHeight
# Determine if we are cropping or padding the width
if diffX > 0:
cropLeft = math.floor(diffX / 2)
cropRight = diffX ... | Pads or crops a rectangle as necessary to achieve the target dimensions,
ensuring the modified rectangle falls within the specified bounds.
The input rectangle, bounds, and return value are all a tuple of (x,y,w,h). | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/RectangleUtils.py#L118-L151 | [
"def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):\n\t\"\"\"\n\tCrops a rectangle by the specified number of pixels on each side.\n\n\tThe input rectangle and return value are both a tuple of (x,y,w,h).\n\t\"\"\"\n\n\t# Unpack the rectangle\n\tx, y, w, h = rect\n\n\t# Crop by the specified value\n\tx +=... | import numpy as np
import math
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):
"""
Crops a rectangle by the specified number of pixels on each side.
The input rectangle and return value are both a tuple of (x,y,w,h).
"""
# Unpack the rectangle
x, y, w, h = rect
# Crop by the specified value
x ... |
adamrehn/slidingwindow | slidingwindow/Merging.py | mergeWindows | python | def mergeWindows(data, dimOrder, maxWindowSize, overlapPercent, batchSize, transform, progressCallback = None):
# Determine the dimensions of the input data
sourceWidth = data.shape[dimOrder.index('w')]
sourceHeight = data.shape[dimOrder.index('h')]
# Generate the sliding windows and group them into batches
wi... | Generates sliding windows for the specified dataset and applies the specified
transformation function to each window. Where multiple overlapping windows
include an element of the input dataset, the overlap is resolved by computing
the mean transform result value for that element.
Irrespective of the order of the ... | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/Merging.py#L5-L64 | [
"def batchWindows(windows, batchSize):\n\t\"\"\"\n\tSplits a list of windows into a series of batches.\n\t\"\"\"\n\treturn np.array_split(np.array(windows), len(windows) // batchSize)\n",
"def generate(data, dimOrder, maxWindowSize, overlapPercent, transforms = []):\n\t\"\"\"\n\tGenerates a set of sliding windows... | from .SlidingWindow import generate
from .Batching import batchWindows
import numpy as np
def mergeWindows(data, dimOrder, maxWindowSize, overlapPercent, batchSize, transform, progressCallback = None):
"""
Generates sliding windows for the specified dataset and applies the specified
transformation function to each ... |
adamrehn/slidingwindow | slidingwindow/ArrayUtils.py | _requiredSize | python | def _requiredSize(shape, dtype):
return math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize) | Determines the number of bytes required to store a NumPy array with
the specified shape and datatype. | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/ArrayUtils.py#L5-L10 | null | import math, mmap, tempfile
import numpy as np
import psutil
class TempfileBackedArray(np.ndarray):
"""
A NumPy ndarray that uses a memory-mapped temp file as its backing
"""
def __new__(subtype, shape, dtype=float, buffer=None, offset=0, strides=None, order=None, info=None):
# Determine the size in bytes r... |
adamrehn/slidingwindow | slidingwindow/ArrayUtils.py | arrayFactory | python | def arrayFactory(shape, dtype=float):
# Determine the number of bytes required to store the array
requiredBytes = _requiredSize(shape, dtype)
# Determine if there is sufficient available memory
vmem = psutil.virtual_memory()
if vmem.available > requiredBytes:
return np.ndarray(shape=shape, dtype=dtype)
else... | Creates a new ndarray of the specified shape and datatype, storing
it in memory if there is sufficient available space or else using
a memory-mapped temporary file to provide the underlying buffer. | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/ArrayUtils.py#L40-L55 | [
"def _requiredSize(shape, dtype):\n\t\"\"\"\n\tDetermines the number of bytes required to store a NumPy array with\n\tthe specified shape and datatype.\n\t\"\"\"\n\treturn math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)\n"
] | import math, mmap, tempfile
import numpy as np
import psutil
def _requiredSize(shape, dtype):
"""
Determines the number of bytes required to store a NumPy array with
the specified shape and datatype.
"""
return math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)
class TempfileBack... |
adamrehn/slidingwindow | slidingwindow/ArrayUtils.py | zerosFactory | python | def zerosFactory(shape, dtype=float):
arr = arrayFactory(shape=shape, dtype=dtype)
arr.fill(0)
return arr | Creates a new NumPy array using `arrayFactory()` and fills it with zeros. | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/ArrayUtils.py#L58-L64 | [
"def arrayFactory(shape, dtype=float):\n\t\"\"\"\n\tCreates a new ndarray of the specified shape and datatype, storing\n\tit in memory if there is sufficient available space or else using\n\ta memory-mapped temporary file to provide the underlying buffer.\n\t\"\"\"\n\n\t# Determine the number of bytes required to s... | import math, mmap, tempfile
import numpy as np
import psutil
def _requiredSize(shape, dtype):
"""
Determines the number of bytes required to store a NumPy array with
the specified shape and datatype.
"""
return math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)
class TempfileBack... |
adamrehn/slidingwindow | slidingwindow/ArrayUtils.py | arrayCast | python | def arrayCast(source, dtype):
# Determine the number of bytes required to store the array
requiredBytes = _requiredSize(source.shape, dtype)
# Determine if there is sufficient available memory
vmem = psutil.virtual_memory()
if vmem.available > requiredBytes:
return source.astype(dtype, subok=False)
else:
... | Casts a NumPy array to the specified datatype, storing the copy
in memory if there is sufficient available space or else using a
memory-mapped temporary file to provide the underlying buffer. | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/ArrayUtils.py#L67-L84 | [
"def _requiredSize(shape, dtype):\n\t\"\"\"\n\tDetermines the number of bytes required to store a NumPy array with\n\tthe specified shape and datatype.\n\t\"\"\"\n\treturn math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)\n",
"def arrayFactory(shape, dtype=float):\n\t\"\"\"\n\tCre... | import math, mmap, tempfile
import numpy as np
import psutil
def _requiredSize(shape, dtype):
"""
Determines the number of bytes required to store a NumPy array with
the specified shape and datatype.
"""
return math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)
class TempfileBack... |
adamrehn/slidingwindow | slidingwindow/ArrayUtils.py | determineMaxWindowSize | python | def determineMaxWindowSize(dtype, limit=None):
vmem = psutil.virtual_memory()
maxSize = math.floor(math.sqrt(vmem.available / np.dtype(dtype).itemsize))
if limit is None or limit >= maxSize:
return maxSize
else:
return limit | Determines the largest square window size that can be used, based on
the specified datatype and amount of currently available system memory.
If `limit` is specified, then this value will be returned in the event
that it is smaller than the maximum computed size. | train | https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/ArrayUtils.py#L87-L100 | null | import math, mmap, tempfile
import numpy as np
import psutil
def _requiredSize(shape, dtype):
"""
Determines the number of bytes required to store a NumPy array with
the specified shape and datatype.
"""
return math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)
class TempfileBack... |
PyCQA/pylint-django | pylint_django/checkers/__init__.py | register_checkers | python | def register_checkers(linter):
linter.register_checker(ModelChecker(linter))
linter.register_checker(DjangoInstalledChecker(linter))
linter.register_checker(JsonResponseChecker(linter))
linter.register_checker(FormChecker(linter)) | Register checkers. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/checkers/__init__.py#L8-L13 | null | """Checkers."""
from pylint_django.checkers.django_installed import DjangoInstalledChecker
from pylint_django.checkers.models import ModelChecker
from pylint_django.checkers.json_response import JsonResponseChecker
from pylint_django.checkers.forms import FormChecker
|
PyCQA/pylint-django | pylint_django/checkers/db_performance.py | register | python | def register(linter):
linter.register_checker(NewDbFieldWithDefaultChecker(linter))
if not compat.LOAD_CONFIGURATION_SUPPORTED:
load_configuration(linter) | Required method to auto register this checker. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/checkers/db_performance.py#L125-L129 | [
"def load_configuration(linter):\n # don't blacklist migrations for this checker\n new_black_list = list(linter.config.black_list)\n if 'migrations' in new_black_list:\n new_black_list.remove('migrations')\n linter.config.black_list = new_black_list\n"
] | # Copyright (c) 2018 Alexander Todorov <atodorov@MrSenko.com>
# Licensed under the GPL 2.0: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint-django/blob/master/LICENSE
"""
Various DB performance suggestions. Disabled by default! Enable with
pylint --load-plugins=pyl... |
PyCQA/pylint-django | pylint_django/checkers/forms.py | FormChecker.visit_classdef | python | def visit_classdef(self, node):
if not node_is_subclass(node, 'django.forms.models.ModelForm', '.ModelForm'):
# we only care about forms
return
meta = _get_child_meta(node)
if not meta:
return
for child in meta.get_children():
if not isi... | Class visitor. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/checkers/forms.py#L32-L49 | [
"def node_is_subclass(cls, *subclass_names):\n \"\"\"Checks if cls node has parent with subclass_name.\"\"\"\n if not isinstance(cls, (ClassDef, Instance)):\n return False\n\n if cls.bases == Uninferable:\n return False\n for base_cls in cls.bases:\n try:\n for inf in bas... | class FormChecker(BaseChecker):
"""Django model checker."""
__implements__ = IAstroidChecker
name = 'django-form-checker'
msgs = {
'W%d04' % BASE_ID: ("Use explicit fields instead of exclude in ModelForm",
'modelform-uses-exclude',
"Preven... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | ignore_import_warnings_for_related_fields | python | def ignore_import_warnings_for_related_fields(orig_method, self, node):
consumer = self._to_consume[0] # pylint: disable=W0212
# we can disable this warning ('Access to a protected member _to_consume of a client class')
# as it's not actually a client class, but rather, this method is being monkey patched
... | Replaces the leave_module method on the VariablesChecker class to
prevent unused-import warnings which are caused by the ForeignKey
and OneToOneField transformations. By replacing the nodes in the
AST with their type rather than the django field, imports of the
form 'from django.db.models import OneToOn... | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L291-L317 | null | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | foreign_key_sets | python | def foreign_key_sets(chain, node):
quack = False
if node.attrname in MANAGER_ATTRS or node.attrname.endswith('_set'):
# if this is a X_set method, that's a pretty strong signal that this is the default
# Django name, rather than one set by related_name
quack = True
else:
# w... | When a Django model has a ForeignKey to another model, the target
of the foreign key gets a '<modelname>_set' attribute for accessing
a queryset of the model owning the foreign key - eg:
class ModelA(models.Model):
pass
class ModelB(models.Model):
a = models.ForeignKey(ModelA)
Now... | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L320-L373 | [
"def node_is_subclass(cls, *subclass_names):\n \"\"\"Checks if cls node has parent with subclass_name.\"\"\"\n if not isinstance(cls, (ClassDef, Instance)):\n return False\n\n if cls.bases == Uninferable:\n return False\n for base_cls in cls.bases:\n try:\n for inf in bas... | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | is_model_admin_subclass | python | def is_model_admin_subclass(node):
if node.name[-5:] != 'Admin' or isinstance(node.parent, ClassDef):
return False
return node_is_subclass(node, 'django.contrib.admin.options.ModelAdmin') | Checks that node is derivative of ModelAdmin class. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L382-L387 | [
"def node_is_subclass(cls, *subclass_names):\n \"\"\"Checks if cls node has parent with subclass_name.\"\"\"\n if not isinstance(cls, (ClassDef, Instance)):\n return False\n\n if cls.bases == Uninferable:\n return False\n for base_cls in cls.bases:\n try:\n for inf in bas... | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | is_model_factory | python | def is_model_factory(node):
try:
parent_classes = node.expr.inferred()
except: # noqa: E722, pylint: disable=bare-except
return False
parents = ('factory.declarations.LazyFunction',
'factory.declarations.SubFactory',
'factory.django.DjangoModelFactory')
f... | Checks that node is derivative of DjangoModelFactory or SubFactory class. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L428-L449 | [
"def node_is_subclass(cls, *subclass_names):\n \"\"\"Checks if cls node has parent with subclass_name.\"\"\"\n if not isinstance(cls, (ClassDef, Instance)):\n return False\n\n if cls.bases == Uninferable:\n return False\n for base_cls in cls.bases:\n try:\n for inf in bas... | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | is_model_mpttmeta_subclass | python | def is_model_mpttmeta_subclass(node):
if node.name != 'MPTTMeta' or not isinstance(node.parent, ClassDef):
return False
parents = ('django.db.models.base.Model',
'.Model', # for the transformed version used in this plugin
'django.forms.forms.Form',
'.Form',... | Checks that node is derivative of MPTTMeta class. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L469-L480 | [
"def node_is_subclass(cls, *subclass_names):\n \"\"\"Checks if cls node has parent with subclass_name.\"\"\"\n if not isinstance(cls, (ClassDef, Instance)):\n return False\n\n if cls.bases == Uninferable:\n return False\n for base_cls in cls.bases:\n try:\n for inf in bas... | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | _attribute_is_magic | python | def _attribute_is_magic(node, attrs, parents):
if node.attrname not in attrs:
return False
if not node.last_child():
return False
try:
for cls in node.last_child().inferred():
if isinstance(cls, Super):
cls = cls._self_class # pylint: disable=protected-a... | Checks that node is an attribute used inside one of allowed parents | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L483-L498 | null | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | generic_is_view_attribute | python | def generic_is_view_attribute(parents, attrs):
def is_attribute(node):
return _attribute_is_magic(node, attrs, parents)
return is_attribute | Generates is_X_attribute function for given parents and attrs. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L621-L625 | null | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | is_model_view_subclass_method_shouldnt_be_function | python | def is_model_view_subclass_method_shouldnt_be_function(node):
if node.name not in ('get', 'post'):
return False
parent = node.parent
while parent and not isinstance(parent, ScopedClass):
parent = parent.parent
subclass = ('django.views.View',
'django.views.generic.View'... | Checks that node is get or post method of the View class. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L628-L641 | [
"def node_is_subclass(cls, *subclass_names):\n \"\"\"Checks if cls node has parent with subclass_name.\"\"\"\n if not isinstance(cls, (ClassDef, Instance)):\n return False\n\n if cls.bases == Uninferable:\n return False\n for base_cls in cls.bases:\n try:\n for inf in bas... | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | is_model_field_display_method | python | def is_model_field_display_method(node):
if not node.attrname.endswith('_display'):
return False
if not node.attrname.startswith('get_'):
return False
if node.last_child():
# TODO: could validate the names of the fields on the model rather than
# blindly accepting get_*_disp... | Accept model's fields with get_*_display names. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L663-L679 | null | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | is_model_media_valid_attributes | python | def is_model_media_valid_attributes(node):
if node.name not in ('js', ):
return False
parent = node.parent
while parent and not isinstance(parent, ScopedClass):
parent = parent.parent
if parent is None or parent.name != "Media":
return False
return True | Suppress warnings for valid attributes of Media class. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L682-L694 | null | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | is_templatetags_module_valid_constant | python | def is_templatetags_module_valid_constant(node):
if node.name not in ('register', ):
return False
parent = node.parent
while not isinstance(parent, Module):
parent = parent.parent
if "templatetags." not in parent.name:
return False
return True | Suppress warnings for valid constants in templatetags module. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L697-L709 | null | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | is_urls_module_valid_constant | python | def is_urls_module_valid_constant(node):
if node.name not in ('urlpatterns', 'app_name'):
return False
parent = node.parent
while not isinstance(parent, Module):
parent = parent.parent
if not parent.name.endswith('urls'):
return False
return True | Suppress warnings for valid constants in urls module. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L712-L724 | null | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | apply_augmentations | python | def apply_augmentations(linter):
augment_visit(linter, TypeChecker.visit_attribute, foreign_key_sets)
augment_visit(linter, TypeChecker.visit_attribute, foreign_key_ids)
suppress_message(linter, TypeChecker.visit_attribute, 'no-member', is_model_field_display_method)
suppress_message(linter, TypeChecker... | Apply augmentation and suppression rules. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L759-L851 | [
"def generic_is_view_attribute(parents, attrs):\n \"\"\"Generates is_X_attribute function for given parents and attrs.\"\"\"\n def is_attribute(node):\n return _attribute_is_magic(node, attrs, parents)\n return is_attribute\n",
"def is_class(class_name):\n \"\"\"Shortcut for node_is_subclass.\"... | """Augmentations."""
# pylint: disable=invalid-name
import itertools
from astroid import InferenceError
from astroid.objects import Super
from astroid.nodes import ClassDef, ImportFrom, Attribute
from astroid.scoped_nodes import ClassDef as ScopedClass, Module
from pylint.checkers.base import DocStringChecker, NameC... |
PyCQA/pylint-django | pylint_django/checkers/models.py | ModelChecker.visit_classdef | python | def visit_classdef(self, node):
if not node_is_subclass(node, 'django.db.models.base.Model', '.Model'):
# we only care about models
return
for child in node.get_children():
if _is_meta_with_abstract(child):
return
if isinstance(child, Ass... | Class visitor. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/checkers/models.py#L79-L131 | [
"def node_is_subclass(cls, *subclass_names):\n \"\"\"Checks if cls node has parent with subclass_name.\"\"\"\n if not isinstance(cls, (ClassDef, Instance)):\n return False\n\n if cls.bases == Uninferable:\n return False\n for base_cls in cls.bases:\n try:\n for inf in bas... | class ModelChecker(BaseChecker):
"""Django model checker."""
__implements__ = IAstroidChecker
name = 'django-model-checker'
msgs = MESSAGES
@check_messages('model-missing-unicode')
|
PyCQA/pylint-django | pylint_django/plugin.py | load_configuration | python | def load_configuration(linter):
name_checker = get_checker(linter, NameChecker)
name_checker.config.good_names += ('qs', 'urlpatterns', 'register', 'app_name', 'handler500')
# we don't care about South migrations
linter.config.black_list += ('migrations', 'south_migrations') | Amend existing checker config. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/plugin.py#L13-L21 | null | """Common Django module."""
from pylint.checkers.base import NameChecker
from pylint_plugin_utils import get_checker
from pylint_django.checkers import register_checkers
# we want to import the transforms to make sure they get added to the astroid manager,
# however we don't actually access them directly, so we'll di... |
PyCQA/pylint-django | pylint_django/plugin.py | register | python | def register(linter):
# add all of the checkers
register_checkers(linter)
# register any checking fiddlers
try:
from pylint_django.augmentations import apply_augmentations
apply_augmentations(linter)
except ImportError:
# probably trying to execute pylint_django when Django ... | Registering additional checkers. | train | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/plugin.py#L24-L41 | [
"def apply_augmentations(linter):\n \"\"\"Apply augmentation and suppression rules.\"\"\"\n augment_visit(linter, TypeChecker.visit_attribute, foreign_key_sets)\n augment_visit(linter, TypeChecker.visit_attribute, foreign_key_ids)\n suppress_message(linter, TypeChecker.visit_attribute, 'no-member', is_m... | """Common Django module."""
from pylint.checkers.base import NameChecker
from pylint_plugin_utils import get_checker
from pylint_django.checkers import register_checkers
# we want to import the transforms to make sure they get added to the astroid manager,
# however we don't actually access them directly, so we'll di... |
jpype-project/jpype | jpype/_darwin.py | DarwinJVMFinder._javahome_binary | python | def _javahome_binary(self):
import platform
import subprocess
from distutils.version import StrictVersion
current = StrictVersion(platform.mac_ver()[0][:4])
if current >= StrictVersion('10.6') and current < StrictVersion('10.9'):
if hasattr(subprocess, 'check_output'... | for osx > 10.5 we have the nice util /usr/libexec/java_home available. Invoke it and
return its output. It seems this tool has been removed in osx 10.9. | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_darwin.py#L52-L67 | null | class DarwinJVMFinder(LinuxJVMFinder):
"""
Mac OS X JVM library finder class
"""
def __init__(self):
"""
Sets up members
"""
# Call the parent constructor
LinuxJVMFinder.__init__(self)
# Library file name
self._libfile = "libjli.dylib"
se... |
jpype-project/jpype | setupext/build_thunk.py | BuildThunkCommand.run | python | def run(self):
self.announce(
'Building thunks',
level=distutils.log.INFO)
# run short circuit logic here
srcDir = os.path.join("build","lib")
destBody = os.path.join("build","src","jp_thunk.cpp")
destHeader = os.path.join("build","src","jp_thunk.h")
if os.path.isfile(destBody):... | Run command. | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/setupext/build_thunk.py#L118-L145 | [
"def _glob(directory,pattern):\n out = []\n for root, dirnames, filenames in os.walk(directory):\n for filename in fnmatch.filter(filenames, pattern):\n out.append(os.path.join(root,filename))\n return out\n",
"def createThunks(input_dir, output_src, output_header, namespace=\"Thunk\"):... | class BuildThunkCommand(distutils.cmd.Command):
"""A custom command to create thunk file."""
description = 'build dynamic code thunks'
user_options = [
]
def initialize_options(self):
"""Set default values for options."""
pass
def finalize_options(self):
"""Post-process options."""
pass
|
jpype-project/jpype | jpype/_windows.py | WindowsJVMFinder._get_from_registry | python | def _get_from_registry(self):
# Winreg is an optional package in cygwin
winreg = self._get_winreg()
if not winreg:
return None
for location in reg_keys:
try:
jreKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, location)
cv = winreg.Q... | Retrieves the path to the default Java installation stored in the
Windows registry
:return: The path found in the registry, or None | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_windows.py#L99-L122 | null | class WindowsJVMFinder(_jvmfinder.JVMFinder):
"""
Windows JVM library finder class
"""
def __init__(self):
"""
Sets up members
"""
# Call the parent constructor
_jvmfinder.JVMFinder.__init__(self)
# Library file name
self._libfile = "jvm.dll"
... |
jpype-project/jpype | jpype/_linux.py | LinuxJVMFinder._get_from_bin | python | def _get_from_bin(self):
# Find the real interpreter installation path
java_bin = os.path.realpath(self._java)
if os.path.exists(java_bin):
# Get to the home directory
java_home = os.path.abspath(os.path.join(os.path.dirname(java_bin),
... | Retrieves the Java library path according to the real installation of
the java executable
:return: The path to the JVM library, or None | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_linux.py#L49-L64 | [
"def find_libjvm(self, java_home):\n \"\"\"\n Recursively looks for the given file\n\n :param java_home: A Java home folder\n :param filename: Name of the file to find\n :return: The first found file path, or None\n \"\"\"\n found_jamvm = False\n non_supported_jvm = ('cacao', 'jamvm')\n f... | class LinuxJVMFinder(_jvmfinder.JVMFinder):
"""
Linux JVM library finder class
"""
def __init__(self):
"""
Sets up members
"""
# Call the parent constructor
_jvmfinder.JVMFinder.__init__(self)
# Java bin file
self._java = "/usr/bin/java"
... |
jpype-project/jpype | jpype/imports.py | _JImportFactory | python | def _JImportFactory(spec, javaname, cls=_JImport):
def init(self, name):
# Call the base class
cls.__init__(self, name)
def getall(self):
global _exportTypes
d1 = self.__dict__.items()
d2 = self.__class__.__dict__.items()
local = [name for name, attr in d1 if not... | (internal) Factory for creating java modules dynamically.
This is needed to create a new type node to hold static methods. | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/imports.py#L201-L241 | null | # -*- coding: utf-8 -*-
# *****************************************************************************
# Copyright 2017 Karl Einar Nelson
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License... |
jpype-project/jpype | jpype/imports.py | _JModule | python | def _JModule(spec, javaname):
cls = _JImportFactory(spec, javaname)
out = cls(spec.name)
return out | (internal) Front end for creating a java module dynamically | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/imports.py#L243-L247 | [
"def _JImportFactory(spec, javaname, cls=_JImport):\n \"\"\" (internal) Factory for creating java modules dynamically.\n\n This is needed to create a new type node to hold static methods.\n \"\"\"\n def init(self, name):\n # Call the base class\n cls.__init__(self, name)\n\n def getall(... | # -*- coding: utf-8 -*-
# *****************************************************************************
# Copyright 2017 Karl Einar Nelson
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License... |
jpype-project/jpype | jpype/_properties.py | _extract_accessor_pairs | python | def _extract_accessor_pairs(members):
accessor_pairs = {}
for name, member in members.items():
if not (len(name) > _PROPERTY_ACCESSOR_PREFIX_LEN \
and _is_java_method(member)):
continue
access, rest = ( name[:_PROPERTY_ACCESSOR_PREFIX_LEN],
... | Extract pairs of corresponding property access methods
(getter and setter) from a Java class's members (attributes).
If a public method with a property's name exists no pair for
that property will be extracted.
Returns a dictionary with the property name as key and a tuple
of (getter method, sette... | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_properties.py#L26-L62 | [
"def _is_java_method(attribute):\n return isinstance(attribute, _jpype._JavaMethod)\n"
] | #*****************************************************************************
# Copyright 2004-2008 Steve Menard
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.