text
stringlengths
4
1.02M
meta
dict
"""Check that the voiceHAT audio input and output are both working.""" import os import subprocess import sys import tempfile import textwrap import time import traceback sys.path.append(os.path.realpath(os.path.join(__file__, '..', '..')) + '/src/') import aiy.audio # noqa CARDS_PATH = '/proc/asound/cards' VOICEHAT_ID = 'googlevoicehat' SERVICE_NAME = 'voice-recognizer' ACTIVE_STR = 'ActiveState=active' INACTIVE_STR = 'ActiveState=inactive' STOP_DELAY = 1.0 TEST_SOUND_PATH = '/usr/share/sounds/alsa/Front_Center.wav' RECORD_DURATION_SECONDS = 3 def get_sound_cards(): """Read a dictionary of ALSA cards from /proc, indexed by number.""" cards = {} with open(CARDS_PATH) as f: # pylint: disable=invalid-name for line in f.read().splitlines(): try: index = int(line.strip().split()[0]) except (IndexError, ValueError): continue cards[index] = line return cards def is_service_active(): """Return True if the voice-recognizer service is active.""" output = subprocess.check_output(['systemctl', 'show', SERVICE_NAME]).decode('utf-8') if ACTIVE_STR in output: return True elif INACTIVE_STR in output: return False print('WARNING: failed to parse output:') print(output) return False def ask(prompt): """Get a yes or no answer from the user.""" ans = input(prompt + ' (y/n) ') while not ans or ans[0].lower() not in 'yn': ans = input('Please enter y or n: ') return ans[0].lower() == 'y' def stop_service(): """Stop the voice-recognizer so we can use the mic. Returns: True if the service has been stopped. """ if not is_service_active(): return False subprocess.check_call(['sudo', 'systemctl', 'stop', SERVICE_NAME], stdout=subprocess.PIPE) time.sleep(STOP_DELAY) if is_service_active(): print('WARNING: failed to stop service, mic may not work.') return False return True def start_service(): """Start the voice-recognizer again.""" subprocess.check_call(['sudo', 'systemctl', 'start', SERVICE_NAME], stdout=subprocess.PIPE) def check_voicehat_present(): """Check that the voiceHAT is present.""" return any(VOICEHAT_ID in card for card in get_sound_cards().values()) def check_voicehat_is_first_card(): """Check that the voiceHAT is the first card on the system.""" cards = get_sound_cards() return 0 in cards and VOICEHAT_ID in cards[0] def check_speaker_works(): """Check the speaker makes a sound.""" print('Playing a test sound...') aiy.audio.play_wave(TEST_SOUND_PATH) return ask('Did you hear the test sound?') def check_mic_works(): """Check the microphone records correctly.""" temp_file, temp_path = tempfile.mkstemp(suffix='.wav') os.close(temp_file) try: input("When you're ready, press enter and say 'Testing, 1 2 3'...") print('Recording...') aiy.audio.record_to_wave(temp_path, RECORD_DURATION_SECONDS) print('Playing back recorded audio...') aiy.audio.play_wave(temp_path) finally: try: os.unlink(temp_path) except FileNotFoundError: pass return ask('Did you hear your own voice?') def do_checks(): """Run all audio checks and print status.""" if not check_voicehat_present(): print(textwrap.fill( """Failed to find the voiceHAT soundcard. Refer to HACKING.md for how to setup the voiceHAT driver: https://git.io/v99yK""")) return if not check_voicehat_is_first_card(): print(textwrap.fill( """The voiceHAT not the first sound device, so the voice recognizer may be unable to find it. Please try removing other sound drivers.""")) return if not check_speaker_works(): print(textwrap.fill( """There may be a problem with your speaker. Check that it's connected properly.""")) return if not check_mic_works(): print(textwrap.fill( """There may be a problem with your microphone. Check that it's connected properly.""")) return print('The audio seems to be working.') def main(): """Run all checks, stopping the voice-recognizer if necessary.""" should_restart = stop_service() do_checks() if should_restart: start_service() if __name__ == '__main__': try: main() input('Press Enter to close...') except Exception: # pylint: disable=W0703 traceback.print_exc() input('Press Enter to close...')
{ "content_hash": "3a44dbc6770610e362215f94956c6494", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 95, "avg_line_length": 26.192090395480225, "alnum_prop": 0.6285591026747196, "repo_name": "hanmy75/voice-recognizer", "id": "80a7710e43f23f73c17425b74a9fe7dc204d12a9", "size": "5235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "checkpoints/check_audio.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "357" }, { "name": "Python", "bytes": "164594" }, { "name": "Shell", "bytes": "5841" } ], "symlink_target": "" }
"""Version-independent api tests""" import httplib2 from oslo.serialization import jsonutils from glance.tests import functional class TestRootApi(functional.FunctionalTest): def test_version_configurations(self): """Test that versioning is handled properly through all channels""" # v1 and v2 api enabled self.cleanup() self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = {'versions': [ { 'id': 'v2.3', 'status': 'CURRENT', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.2', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.1', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v1.1', 'status': 'CURRENT', 'links': [{'rel': 'self', 'href': url % '1'}], }, { 'id': 'v1.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '1'}], }, ]} versions_json = jsonutils.dumps(versions) # Verify version choices returned. path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) self.assertEqual(versions_json, content) self.stop_servers() # v2 api enabled self.cleanup() self.api_server.enable_v1_api = False self.api_server.enable_v2_api = True self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = {'versions': [ { 'id': 'v2.3', 'status': 'CURRENT', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.2', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.1', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }, ]} versions_json = jsonutils.dumps(versions) # Verify version choices returned. path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) self.assertEqual(versions_json, content) self.stop_servers() # v1 api enabled self.cleanup() self.api_server.enable_v1_api = True self.api_server.enable_v2_api = False self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = {'versions': [ { 'id': 'v1.1', 'status': 'CURRENT', 'links': [{'rel': 'self', 'href': url % '1'}], }, { 'id': 'v1.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '1'}], }, ]} versions_json = jsonutils.dumps(versions) # Verify version choices returned. path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) self.assertEqual(versions_json, content) self.stop_servers() def test_version_variations(self): """Test that versioning is handled properly through all channels""" self.cleanup() self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = {'versions': [ { 'id': 'v2.3', 'status': 'CURRENT', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.2', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.1', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v1.1', 'status': 'CURRENT', 'links': [{'rel': 'self', 'href': url % '1'}], }, { 'id': 'v1.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '1'}], }, ]} versions_json = jsonutils.dumps(versions) images = {'images': []} images_json = jsonutils.dumps(images) # 0. GET / with no Accept: header # Verify version choices returned. # Bug lp:803260 no Accept header causes a 500 in glance-api path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) self.assertEqual(versions_json, content) # 1. GET /images with no Accept: header # Verify version choices returned. path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) self.assertEqual(versions_json, content) # 2. GET /v1/images with no Accept: header # Verify empty images list returned. path = 'http://%s:%d/v1/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(200, response.status) self.assertEqual(images_json, content) # 3. GET / with Accept: unknown header # Verify version choices returned. Verify message in API log about # unknown accept header. path = 'http://%s:%d/' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'unknown'} response, content = http.request(path, 'GET', headers=headers) self.assertEqual(300, response.status) self.assertEqual(versions_json, content) # 4. GET / with an Accept: application/vnd.openstack.images-v1 # Verify empty image list returned path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content = http.request(path, 'GET', headers=headers) self.assertEqual(200, response.status) self.assertEqual(images_json, content) # 5. GET /images with a Accept: application/vnd.openstack.compute-v1 # header. Verify version choices returned. Verify message in API log # about unknown accept header. path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.compute-v1'} response, content = http.request(path, 'GET', headers=headers) self.assertEqual(300, response.status) self.assertEqual(versions_json, content) # 6. GET /v1.0/images with no Accept: header # Verify version choices returned path = 'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) # 7. GET /v1.a/images with no Accept: header # Verify version choices returned path = 'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) # 8. GET /va.1/images with no Accept: header # Verify version choices returned path = 'http://%s:%d/va.1/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) self.assertEqual(versions_json, content) # 9. GET /versions with no Accept: header # Verify version choices returned path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) self.assertEqual(versions_json, content) # 10. GET /versions with a Accept: application/vnd.openstack.images-v1 # header. Verify version choices returned. path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content = http.request(path, 'GET', headers=headers) self.assertEqual(300, response.status) self.assertEqual(versions_json, content) # 11. GET /v1/versions with no Accept: header # Verify 404 returned path = 'http://%s:%d/v1/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(404, response.status) # Verify version choices returned path = 'http://%s:%d/v10' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) self.assertEqual(versions_json, content) # 13. GET /images with a Accept: application/vnd.openstack.compute-v2 # header. Verify version choices returned. Verify message in API log # about unknown version in accept header. path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v10'} response, content = http.request(path, 'GET', headers=headers) self.assertEqual(300, response.status) self.assertEqual(versions_json, content) # 14. GET /v1.2/images with no Accept: header # Verify version choices returned path = 'http://%s:%d/v1.2/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(300, response.status) self.assertEqual(versions_json, content) self.stop_servers()
{ "content_hash": "9c02e7ea932f76e1f44252c8261fd468", "timestamp": "", "source": "github", "line_count": 298, "max_line_length": 78, "avg_line_length": 37.85906040268456, "alnum_prop": 0.5108136855167523, "repo_name": "sigmavirus24/glance", "id": "ca0ee7be3b74527ae9164b37cba0b9c98a61e7bc", "size": "11918", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "glance/tests/functional/test_api.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "3470355" }, { "name": "Shell", "bytes": "7860" } ], "symlink_target": "" }
import errno import os import re import subprocess import sys # these strings will be replaced by git during git-archive git_refnames = "$Format:%d$" git_full = "$Format:%H$" # these strings are filled in when 'setup.py versioneer' creates _version.py tag_prefix = "txrecaptcha-" parentdir_prefix = "txrecaptcha-" versionfile_source = "txrecaptcha/_version.py" def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): assert isinstance(commands, list) p = None for c in commands: try: # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % args[0]) print(e) return None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % args[0]) return None return stdout def versions_from_parentdir(parentdir_prefix, root, verbose=False): # Source tarballs conventionally unpack into a directory that includes # both the project name and a version string. dirname = os.path.basename(root) if not dirname.startswith(parentdir_prefix): if verbose: print("guessing rootdir is '%s', but '%s' doesn't start with " "prefix '%s'" % (root, dirname, parentdir_prefix)) return None return {"version": dirname[len(parentdir_prefix):], "full": ""} def git_get_keywords(versionfile_abs): # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) f.close() except EnvironmentError: pass return keywords def git_versions_from_keywords(keywords, tag_prefix, verbose=False): if not keywords: return {} # keyword-finding function failed to find keywords refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") return {} # unexpanded, so not in an unpacked git-archive tarball refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full": keywords["full"].strip()} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full": keywords["full"].strip()} def git_parse_vcs_describe(git_describe, tag_prefix, verbose=False): # TAG-NUM-gHEX[-dirty] or HEX[-dirty] . TAG might have hyphens. # dirty dirty = git_describe.endswith("-dirty") if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] dirty_suffix = ".dirty" if dirty else "" # now we have TAG-NUM-gHEX or HEX if "-" not in git_describe: # just HEX return "0+untagged.g"+git_describe+dirty_suffix, dirty # just TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? return "0+unparseable"+dirty_suffix, dirty # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) return None, dirty tag = full_tag[len(tag_prefix):] # distance: number of commits since tag distance = int(mo.group(2)) # commit: short hex revision ID commit = mo.group(3) # now build up version string, with post-release "local version # identifier". Our goal: TAG[+NUM.gHEX[.dirty]] . Note that if you get a # tagged build and then dirty it, you'll get TAG+0.gHEX.dirty . So you # can always test version.endswith(".dirty"). version = tag if distance or dirty: version += "+%d.g%s" % (distance, commit) + dirty_suffix return version, dirty def git_versions_from_vcs(tag_prefix, root, verbose=False): # this runs 'git' from the root of the source tree. This only gets called # if the git-archive 'subst' keywords were *not* expanded, and # _version.py hasn't already been rewritten with a short version string, # meaning we're inside a checked out source tree. if not os.path.exists(os.path.join(root, ".git")): if verbose: print("no .git in %s" % root) return {} # get_versions() will try next method GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # if there is a tag, this yields TAG-NUM-gHEX[-dirty] # if there are no tags, this yields HEX[-dirty] (no NUM) stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long"], cwd=root) # --long was added in git-1.5.5 if stdout is None: return {} # try next method version, dirty = git_parse_vcs_describe(stdout, tag_prefix, verbose) # build "full", which is FULLHEX[.dirty] stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if stdout is None: return {} full = stdout.strip() if dirty: full += ".dirty" return {"version": version, "full": full} def get_versions(default={"version": "0+unknown", "full": ""}, verbose=False): # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. keywords = {"refnames": git_refnames, "full": git_full} ver = git_versions_from_keywords(keywords, tag_prefix, verbose) if ver: return ver try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return default return (git_versions_from_vcs(tag_prefix, root, verbose) or versions_from_parentdir(parentdir_prefix, root, verbose) or default)
{ "content_hash": "ae51dcaf5bb37c5cb26918a43ecb0c73", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 78, "avg_line_length": 37.86026200873363, "alnum_prop": 0.595040369088812, "repo_name": "isislovecruft/txrecaptcha", "id": "433fae93fed7838905f4093109ad4a9511a60011", "size": "9149", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "txrecaptcha/_version.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "4374" }, { "name": "Makefile", "bytes": "1263" }, { "name": "Python", "bytes": "115210" } ], "symlink_target": "" }
import requests import xmltodict try: # python 3 from urllib.parse import urlparse, urlunparse, urlencode except ImportError: from urlparse import urlparse, urlunparse from urllib import urlencode from .error import ZillowError from .place import Place class ValuationApi(object): """ A python interface into the Zillow API By default, the Api caches results for 1 minute. Example usage: To create an instance of the zillow.ValuationApi class: >>> import zillow >>> api = zillow.ValuationApi() All available methods include: >>> data = api.GetSearchResults("<your key here>", "<your address here>", "<your zip here>") """ def __init__(self): self.base_url = "https://www.zillow.com/webservice" self._input_encoding = None self._request_headers=None self.__auth = None self._timeout = None def GetSearchResults(self, zws_id, address, citystatezip, retnzestimate=False): """ The GetSearchResults API finds a property for a specified address. The content returned contains the address for the property or properties as well as the Zillow Property ID (ZPID) and current Zestimate. It also includes the date the Zestimate was computed, a valuation range and the Zestimate ranking for the property within its ZIP code. The GetSearchResults API Web Service is located at: http://www.zillow.com/webservice/GetSearchResults.htm :param zws_id: The Zillow Web Service Identifier. Each subscriber to Zillow Web Services is uniquely identified by an ID sequence and every request to Web services requires this ID. :param address: The address of the property to search. This string should be URL encoded. :param citystatezip: The city+state combination and/or ZIP code for which to search. This string should be URL encoded. Note that giving both city and state is required. Using just one will not work. :param retnzestimat: Return Rent Zestimate information if available (boolean true/false, default: false) :return: """ url = '%s/GetSearchResults.htm' % (self.base_url) parameters = {'zws-id': zws_id} if address and citystatezip: parameters['address'] = address parameters['citystatezip'] = citystatezip else: raise ZillowError({'message': "Specify address and citystatezip."}) if retnzestimate: parameters['retnzestimate'] = 'true' resp = self._RequestUrl(url, 'GET', data=parameters) data = resp.content.decode('utf-8') xmltodict_data = xmltodict.parse(data) place = Place() try: place.set_data(xmltodict_data.get('SearchResults:searchresults', None)['response']['results']['result']) except: raise ZillowError({'message': "Zillow did not return a valid response: %s" % data}) return place def GetZEstimate(self, zws_id, zpid, retnzestimate=False): """ The GetZestimate API will only surface properties for which a Zestimate exists. If a request is made for a property that has no Zestimate, an error code is returned. Zillow doesn't have Zestimates for all the homes in its database. For such properties, we do have tax assessment data, but that is not provided through the API. For more information, see our Zestimate coverage. :zws_id: The Zillow Web Service Identifier. :param zpid: The address of the property to search. This string should be URL encoded. :param retnzestimate: Return Rent Zestimate information if available (boolean true/false, default: false) :return: """ url = '%s/GetZestimate.htm' % (self.base_url) parameters = {'zws-id': zws_id, 'zpid': zpid} if retnzestimate: parameters['retnzestimate'] = 'true' resp = self._RequestUrl(url, 'GET', data=parameters) data = resp.content.decode('utf-8') xmltodict_data = xmltodict.parse(data) place = Place() try: place.set_data(xmltodict_data.get('Zestimate:zestimate', None)['response']) except: raise ZillowError({'message': "Zillow did not return a valid response: %s" % data}) return place def GetDeepSearchResults(self, zws_id, address, citystatezip, retnzestimate=False): """ The GetDeepSearchResults API finds a property for a specified address. The result set returned contains the full address(s), zpid and Zestimate data that is provided by the GetSearchResults API. Moreover, this API call also gives rich property data like lot size, year built, bath/beds, last sale details etc. :zws_id: The Zillow Web Service Identifier. :param address: The address of the property to search. This string should be URL encoded. :param citystatezip: The city+state combination and/or ZIP code for which to search. :param retnzestimate: Return Rent Zestimate information if available (boolean true/false, default: false) :return: Example: """ url = '%s/GetDeepSearchResults.htm' % (self.base_url) parameters = {'zws-id': zws_id, 'address': address, 'citystatezip': citystatezip } if retnzestimate: parameters['retnzestimate'] = 'true' resp = self._RequestUrl(url, 'GET', data=parameters) data = resp.content.decode('utf-8') xmltodict_data = xmltodict.parse(data) place = Place(has_extended_data=True) try: place.set_data(xmltodict_data.get('SearchResults:searchresults', None)['response']['results']['result']) except: raise ZillowError({'message': "Zillow did not return a valid response: %s" % data}) return place def GetDeepComps(self, zws_id, zpid, count=10, rentzestimate=False): """ The GetDeepComps API returns a list of comparable recent sales for a specified property. The result set returned contains the address, Zillow property identifier, and Zestimate for the comparable properties and the principal property for which the comparables are being retrieved. This API call also returns rich property data for the comparables. :param zws_id: The Zillow Web Service Identifier. :param zpid: The address of the property to search. This string should be URL encoded. :param count: The number of comparable recent sales to obtain (integer between 1 and 25) :param rentzestimate: Return Rent Zestimate information if available (boolean true/false, default: false) :return: Example >>> data = api.GetDeepComps("<your key here>", 2100641621, 10) """ url = '%s/GetDeepComps.htm' % (self.base_url) parameters = {'zws-id': zws_id, 'zpid': zpid, 'count': count} if rentzestimate: parameters['rentzestimate'] = 'true' resp = self._RequestUrl(url, 'GET', data=parameters) data = resp.content.decode('utf-8') # transform the data to an dict-like object xmltodict_data = xmltodict.parse(data) # get the principal property data principal_place = Place() principal_data = xmltodict_data.get('Comps:comps')['response']['properties']['principal'] try: principal_place.set_data(principal_data) except: raise ZillowError({'message': 'No principal data found: %s' % data}) # get the comps property_data comps = xmltodict_data.get('Comps:comps')['response']['properties']['comparables']['comp'] comp_places = [] for datum in comps: place = Place() try: place.set_data(datum) comp_places.append(place) except: raise ZillowError({'message': 'No valid comp data found %s' % datum}) output = { 'principal': principal_place, 'comps': comp_places } return output def GetComps(self, zws_id, zpid, count=25, rentzestimate=False): """ The GetComps API returns a list of comparable recent sales for a specified property. The result set returned contains the address, Zillow property identifier, and Zestimate for the comparable properties and the principal property for which the comparables are being retrieved. :param zpid: The address of the property to search. This string should be URL encoded. :param count: The number of comparable recent sales to obtain (integer between 1 and 25) :param retnzestimate: Return Rent Zestimate information if available (boolean true/false, default: false) :return: """ url = '%s/GetComps.htm' % (self.base_url) parameters = {'zws-id': zws_id, 'zpid': zpid, 'count': count} if rentzestimate: parameters['rentzestimate'] = 'true' resp = self._RequestUrl(url, 'GET', data=parameters) data = resp.content.decode('utf-8') # transform the data to an dict-like object xmltodict_data = xmltodict.parse(data) # get the principal property data principal_place = Place() principal_data = xmltodict_data.get('Comps:comps')['response']['properties']['principal'] try: principal_place.set_data(principal_data) except: raise ZillowError({'message': 'No principal data found: %s' % data}) # get the comps property_data comps = xmltodict_data.get('Comps:comps')['response']['properties']['comparables']['comp'] comp_places = [] for datum in comps: place = Place() try: place.set_data(datum) comp_places.append(place) except: raise ZillowError({'message': 'No valid comp data found %s' % datum}) output = { 'principal': principal_place, 'comps': comp_places } return output def _RequestUrl(self, url, verb, data=None): """ Request a url. :param url: The web location we want to retrieve. :param verb: GET only (for now). :param data: A dict of (str, unicode) key/value pairs. :return:A JSON object. """ if verb == 'GET': url = self._BuildUrl(url, extra_params=data) try: return requests.get( url, auth=self.__auth, timeout=self._timeout ) except requests.RequestException as e: raise ZillowError(str(e)) return 0 def _BuildUrl(self, url, path_elements=None, extra_params=None): """ Taken from: https://github.com/bear/python-twitter/blob/master/twitter/api.py#L3814-L3836 :param url: :param path_elements: :param extra_params: :return: """ # Break url into constituent parts (scheme, netloc, path, params, query, fragment) = urlparse(url) # Add any additional path elements to the path if path_elements: # Filter out the path elements that have a value of None p = [i for i in path_elements if i] if not path.endswith('/'): path += '/' path += '/'.join(p) # Add any additional query parameters to the query string if extra_params and len(extra_params) > 0: extra_query = self._EncodeParameters(extra_params) # Add it to the existing query if query: query += '&' + extra_query else: query = extra_query # Return the rebuilt URL return urlunparse((scheme, netloc, path, params, query, fragment)) def _EncodeParameters(self, parameters): """ Return a string in key=value&key=value form. :param parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding :return:A URL-encoded string in "key=value&key=value" form """ if parameters is None: return None else: return urlencode(dict([(k, self._Encode(v)) for k, v in list(parameters.items()) if v is not None])) def _Encode(self, s): if self._input_encoding: return str(s, self._input_encoding).encode('utf-8') else: return str(s).encode('utf-8')
{ "content_hash": "46c9c1e1b61b6e5a14035d870c6e6037", "timestamp": "", "source": "github", "line_count": 309, "max_line_length": 207, "avg_line_length": 41.385113268608414, "alnum_prop": 0.6133875508289021, "repo_name": "seme0021/python-zillow", "id": "56dca5becc87e7178727798c741f664df47d5420", "size": "12788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zillow/api.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "817" }, { "name": "Python", "bytes": "26390" } ], "symlink_target": "" }
""" Created on Mon Mar 02 08:59:22 2015 @author: Konstantin """ import configparser, csv from fabric.api import env, execute, task, parallel, sudo, run, put import cuisine @task def update(package=None): if package: cuisine.package_update(package) else: sudo('apt-get -y --allow-unauthenticated --force-yes -o DPkg::Options::="--force-overwrite" -o DPkg::Options::="--force-confdef" update') @task def upgrade(package=None): if package: cmd = str('apt-get -y --allow-unauthenticated --force-yes -o DPkg::Options::="--force-overwrite" -o DPkg::Options::="--force-confdef" upgrade %s' % package) sudo(cmd) else: sudo('apt-get -y --allow-unauthenticated --force-yes -o DPkg::Options::="--force-overwrite" -o DPkg::Options::="--force-confdef" upgrade') @task @parallel def install(package): """ Fabric task to install a package on a VM. """ cmd = str('apt-get -y --allow-unauthenticated --force-yes -o DPkg::Options::="--force-overwrite" -o DPkg::Options::="--force-confdef" install %s' % package) sudo(cmd) @task @parallel def pip_install(package): """ Fabric task to install a package via pip on a VM. """ cmd = str('apt-get -y --allow-unauthenticated --force-yes -o DPkg::Options::="--force-overwrite" -o DPkg::Options::="--force-confdef" install python-pip') sudo(cmd) command = str('pip install %s' % package) sudo(command) @task @parallel def upload_file(remote_location, local_location, sudo=False): """ Fabric task to upload a file to a VM. """ put(remote_path=remote_location, local_path=local_location, use_sudo=sudo) @task @parallel def run_python_program(program=None, sudo=False): """ Fabric task to run a Python program on a VM. """ cuisine.file_ensure('/usr/bin/python') if sudo: sudo('/usr/bin/python %s' % program) else: run('/usr/bin/python %s' % program) def read_hosts_file(path): """ Reads the hosts list to get IPs of the other VMs. """ with open(path, 'rb') as f: reader = csv.reader(f, delimiter=';', quotechar='|') host_ip_list = [row[0] for row in reader] return host_ip_list if __name__ == "__main__": config = configparser.ConfigParser() conf = open('config.ini', 'rb') # conf.readline() config.readfp(conf) # print(config.sections()) vm_credentials = dict(config['SSH_CREDENTIALS']) ssh_username = str(vm_credentials['ssh.username']) ssh_password = str(vm_credentials['ssh.password']) ssh_key_filename = str(vm_credentials['ssh.key_filename']) vm_list = read_hosts_file('/etc/host_ips.csv') print vm_list # vm_control = vm_control.VM_Control() # vm_control.create_vms(vm_list) ## vm_control.stop_vms(vm_list) ## vm_control.start_vms(vm_list) # ip_list = vm_control.get_free_floating_ips() # vm_control.assign_floating_ip_to_vm('vm1',ip_list) # vm_data = vm_control.get_vms_data(vm_list) # ssh_url = vm_control.get_floating_ip('vm1') env.hosts = vm_list env.user = ssh_username env.password = ssh_password env.key_filename = ssh_key_filename env.connection_attempts = 5 env.warn_only=True # execute(update) # execute(upgrade) # execute(install, 'python-pip') # execute(install, 'python-dev') # execute(pip_install, 'dispy') # execute(pip_install, 'ecdsa') # execute(pip_install, 'pycrypto') # execute(pip_install, 'fabric') # execute(pip_install, 'cuisine') execute(update) execute(upgrade) execute(install, 'python-pip') execute(install, 'python-dev') execute(pip_install, 'multiprocessing') execute(pip_install, 'logging') execute(pip_install, 'multiprocessing') # execute(install, 'gcc') execute(upload_file, '/etc/host_ips.csv', '/etc/host_ips.csv', sudo=True) execute(upload_file, '/root/test_program.py', '/root/test_program.py', sudo=True) execute(upload_file, '/root/failures.csv', '/root/failures.csv', sudo=True) execute(upload_file, '/root/response_time.csv', '/root/response_time.csv', sudo=True)
{ "content_hash": "d13e8fa28ea8e996faa47407028eae9b", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 164, "avg_line_length": 32.365671641791046, "alnum_prop": 0.6117131657827992, "repo_name": "icclab/vm-reliability-tester", "id": "7927fe15e31e2e8cb7840b9c02218838fe35cfb4", "size": "4362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_config.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "69952" }, { "name": "R", "bytes": "2039" } ], "symlink_target": "" }
""" gpd_lite_toolboox setup file """ from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext from Cython.Build import cythonize import gpd_lite_toolbox ext = Extension("gpd_lite_toolbox.cycartogram", ["gpd_lite_toolbox/cycartogram.pyx"], ["."]) setup( name='gpd_lite_toolbox', version=gpd_lite_toolbox.__version__, description='Convenience functions acting on GeoDataFrames', author='mthh', ext_modules=cythonize(ext), cmdclass = {'build_ext': build_ext}, packages=['gpd_lite_toolbox'], license='MIT', )
{ "content_hash": "59b7ddc04a3fe9c5f71b639470efc22a", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 64, "avg_line_length": 25.75, "alnum_prop": 0.6925566343042071, "repo_name": "mthh/gpd_lite_toolbox", "id": "1e3c47b642946d55ea1e9237021104ac62cb6673", "size": "642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "setup.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1139" }, { "name": "Python", "bytes": "62765" } ], "symlink_target": "" }
import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='direct_logs', type='direct') severity = sys.argv[1] if len(sys.argv) > 1 else 'info' message = ' '.join(sys.argv[2:]) or 'Hello World!' channel.basic_publish(exchange='direct_logs', routing_key=severity, body=message) print " [x] Sent %r:%r" % (severity, message) connection.close()
{ "content_hash": "c4152d4bef1078b6a0e2166f5f9bee45", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 63, "avg_line_length": 31.41176470588235, "alnum_prop": 0.6329588014981273, "repo_name": "jefersonm/sandbox", "id": "27e71c5f2aae560cde391090b4bb55d9d9c9dff5", "size": "534", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "languages/python/rabbitmq/part_4/emit_log_direct.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2912" }, { "name": "C", "bytes": "1392" }, { "name": "CSS", "bytes": "189387" }, { "name": "Clojure", "bytes": "16595" }, { "name": "Common Lisp", "bytes": "2496" }, { "name": "Erlang", "bytes": "184" }, { "name": "HTML", "bytes": "140080" }, { "name": "Haskell", "bytes": "1037" }, { "name": "Java", "bytes": "874954" }, { "name": "JavaScript", "bytes": "1106171" }, { "name": "Objective-C", "bytes": "1398795" }, { "name": "PHP", "bytes": "2046941" }, { "name": "Python", "bytes": "24059" }, { "name": "Ruby", "bytes": "25424" }, { "name": "Scala", "bytes": "13522" }, { "name": "Shell", "bytes": "324941" }, { "name": "Swift", "bytes": "11463" } ], "symlink_target": "" }
from selenium.webdriver import Remote import nerodia class Screenshot(object): def __init__(self, browser): if isinstance(browser, Remote): nerodia.logger.deprecate('Initializing `Screenshot` with a `selenium.webdriver` ' 'instance', 'a `nerodia.browser` instance', ids=['screenshot_driver']) self.driver = browser else: self.browser = browser self.driver = browser.wd def save(self, path): """ Saves screenshot to given path :param path: file path :Example: browser.screenshot.save('screenshot.png') """ self.driver.save_screenshot(path) def png(self): """ Represents screenshot as PNG image string :rtype: str :Example: browser.screenshot.png #=> '\x95\xC7\x8C@1\xC07\x1C(Edb\x15\xB2\vL' """ return self.driver.get_screenshot_as_png() def base64(self): """ Represents screenshot as Base64 encoded string :rtype: str :Example: browser.screenshot.base64 #=> '7HWJ43tZDscPleeUuPW6HhN3x+z7vU/lufmH0qNTtTum94IBWMT46evImci1vnFGT' """ return self.driver.get_screenshot_as_base64()
{ "content_hash": "be321fa0ac2c00a0247bc1ba564771ff", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 93, "avg_line_length": 26.019607843137255, "alnum_prop": 0.5621703089675961, "repo_name": "lmtierney/watir-snake", "id": "5f86eb38b1aa53288131bf3ffe4d022914b570f0", "size": "1327", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nerodia/screenshot.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "403217" } ], "symlink_target": "" }
import wolframalpha import sys from time import sleep from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate # Initialize the LCD plate. Should auto-detect correct I2C bus. If not, # pass '0' for early 256 MB Model B boards or '1' for all later versions lcd = Adafruit_CharLCDPlate() # Clear display and show greeting, pause 1 sec lcd.clear() lcd.backlight(lcd.WHITE) lcd.message("Searching...") # Get a free API key here http://products.wolframalpha.com/api/ # This is a fake ID, go and get your own, instructions on my blog. app_id='EAL55P-UYQLAH8HJ7' client = wolframalpha.Client(app_id) query = ' '.join(sys.argv[1:]) res = client.query(query) lcd.clear(); if len(res.pods) > 0: texts = "" pod = res.pods[1] if pod.text: texts = pod.text else: texts = "I have no answer for that" # to skip ascii character in case of error texts = texts.encode('ascii', 'ignore') print texts lcd.backlight(lcd.GREEN) lcd.message(texts) else: print "Don't be such a bother." lcd.backlight(lcd.RED) lcd.message("Piss off!") #sleep(5) #lcd.clear() #lcd.backlight(lcd.OFF)
{ "content_hash": "4d8eb6a39c6642b34cf60934aa2bded0", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 73, "avg_line_length": 25.133333333333333, "alnum_prop": 0.6861184792219275, "repo_name": "stevenkword/PiCurious", "id": "f69d8d070d83f4ec3ea754230944ea296f7daf99", "size": "1150", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Diane/querywolfram.py", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "6747" }, { "name": "C++", "bytes": "76244" }, { "name": "JavaScript", "bytes": "6612" }, { "name": "Python", "bytes": "246245" }, { "name": "Shell", "bytes": "37600" } ], "symlink_target": "" }
import track_common class active_applications: ''' the data model which holds all application usage data for one day. That is: app_data: {app_id: application} minutes: {i_min => [app_id], i_cat} where application: (i_secs, i_cat, s_title, s_process) model_list: * sortable by key * can be done with list of keys sorted by given value [(app_id, i_secs, i_cat)] ''' def __init__(self): self.header = ['application title', 'time', 'category'] self._index_min = None self._index_max = None self._sorted_keys = [] # to be persisted self._apps = {} # app identifier => app_info instance self._minutes = {} # i_min => minute def clear(self): # todo: mutex self._index_min = None self._index_max = None self._apps = {} # app identifier => app_info instance self._minutes = {} # i_min => minute def count(self): return len(self._sorted_keys) ''' def _data(self, row, column): # const if column == 0: return self._apps[self._sorted_keys[row]]._wndtitle elif column == 1: return track_common.secs_to_dur(self._apps[self._sorted_keys[row]]._count) elif column == 2: return self._apps[self._sorted_keys[row]]._category return 0 ''' def __eq__(self, other): ''' comparing is only needed for tests ''' if not self._apps == other._apps: return False if not self._minutes == other._minutes: for m in self._minutes: pass return False return True def __data__(self): # const """ we have to create an indexed list here because the minutes dict has to store references to app_info. intermediate: _indexed: {app_id => (i_index, app_info)} result: app: [app_info] minutes: {i_minute: (i_category, [(app_info, i_count)])} """ _indexed = {a: i for i, a in enumerate(self._apps.values())} _apps = [d[1] for d in sorted([(e[1], e[0].__data__()) for e in _indexed.items()])] # print(_apps) _minutes = {i: (m._category, [(_indexed[a], c) for a, c in m._apps.items()]) for i, m in self._minutes.items()} #print(_minutes) return { 'apps': _apps, 'minutes': _minutes} def from_dict(self, data): assert 'apps' in data assert 'minutes' in data _a = data['apps'] _indexed = [track_common.app_info().load(d) for d in _a] _m = data['minutes'] _minutes = { int(i) : track_common.minute().init( ( m[0], { _indexed[a]: c for a, c in m[1] } ) ) for i, m in _m.items() } # x = {i:len({a:0 for a in i}) for i in l} _apps = {a.generate_identifier(): a for a in _indexed} # todo: mutex self._apps = _apps self._minutes = _minutes if len(self._minutes) > 0: self._index_min = min(self._minutes.keys()) self._index_max = max(self._minutes.keys()) else: self._index_min = None self._index_max = None # print(_minutes) def begin_index(self): # const return self._index_min if self._index_min else 0 def end_index(self): # const return self._index_max if self._index_max else 0 def update(self, minute_index, app): # todo: mutex _app_id = app.generate_identifier() if _app_id not in self._apps: self._apps[_app_id] = app # if "Firefox" in _app_id: # app._category = 1 # else: # app._category = 0 # print([a._category for a in self._apps.values()]) _app = self._apps[_app_id] _app._count += 1 if minute_index not in self._minutes: self._minutes[minute_index] = track_common.minute() if not self._index_min or self._index_min > minute_index: self._index_min = minute_index if not self._index_max or self._index_max < minute_index: self._index_max = minute_index self._minutes[minute_index].add(_app) # self.dataChanged.emit(QtCore.QModelIndex(), QtCore.QModelIndex()) def get_chunk_size(self, minute): _begin = minute _end = minute if minute > self._index_max or minute < self._index_min: return (_begin, _end) if self.is_active(minute): _a = self._minutes[minute].get_main_app() else: _a = None _minutes = sorted(self._minutes.keys()) _lower_range = [i for i in _minutes if i < minute] _upper_range = [i for i in _minutes if i > minute] if _a is None: _begin = _lower_range[-1] if _lower_range != [] else _begin _end = _upper_range[0] if _upper_range != [] else _end return (_begin, _end) # print(len(_minutes)) # print(minute) # print(_i) # print(_minutes[_minutes.index(minute)]) # print(list(reversed(range(_i)))) for i in reversed(_lower_range): if _begin - i > 1: break if self._minutes[i].get_main_app() == _a: _begin = i # print(list(range(_i + 1, len(_minutes)))) for i in _upper_range: if i - _end > 1: break if self._minutes[i].get_main_app() == _a: _end = i # todo: currently gap is max 1min - make configurable return (_begin, _end) def info(self, minute): if self.is_active(minute): _activity = self._minutes[minute].get_main_app() else: _activity = 'idle' _cs = self.get_chunk_size(minute) # print(mins_to_str(_cs[1]-_cs[0]) + " / " + str(_cs)) return (_cs, _activity) def is_active(self, minute): if minute in self._minutes: return True return False def is_private(self, minute): if minute not in self._minutes: return False # print("%d: %s" % # (minute, str([global_app_categories[a] # for a in self._minutes[minute]._apps]))) # print(' '.join(reversed(["(%d: %d)" % (s, m._category) # for s, m in self._minutes.items()]))) return self._minutes[minute]._category != 0
{ "content_hash": "62307df86441c6b1f913d8b77657fb17", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 86, "avg_line_length": 31.315315315315317, "alnum_prop": 0.48130034522439585, "repo_name": "itf/track", "id": "fd5ae9668941cf6765a6b3be28b0f598f7a410bb", "size": "7000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "track_base/active_applications.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "71807" }, { "name": "Shell", "bytes": "112" } ], "symlink_target": "" }
import os #Read barcode sequecnes from disk barcode1 = open(snakemake.input["barcode1"]).readline().rstrip() barcode2 = open(snakemake.input["barcode2"]).readline().rstrip() #Construct the full i7 and i5 primer sequences primer1 = "CTGTCTCTTATACACATCTCCGAGCCCACGAGAC" + barcode1 + "ATCTCGTATGCCGTCTTCTGCTTGAAAAAAAAAA" primer2 = "CTGTCTCTTATACACATCTGACGCTGCCGACGA" + barcode2 + "GTGTAGATCTCGGTGGTCGCCGTATCATTAAAAAA" #Construct skewer command output_prefix = snakemake.params["prefix"] skewer_command = " ".join(["skewer -x", primer1, "-y", primer2, "-m pe", snakemake.input["fastq1"], snakemake.input["fastq2"], "-z -o", output_prefix]) os.system(skewer_command)
{ "content_hash": "951ee0cf339ce1f5ee6cc75c3e1b66c1", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 96, "avg_line_length": 44.4, "alnum_prop": 0.7627627627627628, "repo_name": "kauralasoo/Blood_ATAC", "id": "3074ea2d431b2f91aa0221b65374a7808399ef01", "size": "666", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/trim_adapters.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "13807" }, { "name": "R", "bytes": "9459" }, { "name": "Shell", "bytes": "69201" } ], "symlink_target": "" }
import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.append(os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.pngmath'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Portable Computing Language (pocl)' copyright = u'2010-2015, pocl developers' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.11' # The full version, including alpha/beta/rc tags. release = '0.11-pre' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'PortableComputingLanguagepocldoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'PortableComputingLanguagepocl.tex', u'Portable Computing Language (pocl) Documentation', u'pocl developers', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
{ "content_hash": "dbb47197b67da74db310e549b6a8f7c1", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 101, "avg_line_length": 33.149171270718234, "alnum_prop": 0.7135, "repo_name": "hugwijst/pocl", "id": "367151e3d30971bd3571bad745096e4f2579491c", "size": "6445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/sphinx/source/conf.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5323781" }, { "name": "C++", "bytes": "2063382" }, { "name": "Java", "bytes": "2648" }, { "name": "Makefile", "bytes": "13750" }, { "name": "Mathematica", "bytes": "4824" }, { "name": "Objective-C", "bytes": "1729" }, { "name": "Python", "bytes": "58353" }, { "name": "Shell", "bytes": "101947" } ], "symlink_target": "" }
from opbeat.instrumentation.packages.base import AbstractInstrumentedModule from opbeat.traces import trace from opbeat.utils import default_ports from opbeat.utils.compat import urlparse def get_host_from_url(url): parsed_url = urlparse.urlparse(url) host = parsed_url.hostname or " " if ( parsed_url.port and default_ports.get(parsed_url.scheme) != parsed_url.port ): host += ":" + str(parsed_url.port) return host class RequestsInstrumentation(AbstractInstrumentedModule): name = 'requests' instrument_list = [ ("requests.sessions", "Session.send"), ] def call(self, module, method, wrapped, instance, args, kwargs): if 'request' in kwargs: request = kwargs['request'] else: request = args[0] signature = request.method.upper() signature += " " + get_host_from_url(request.url) with trace(signature, "ext.http.requests", {'url': request.url}, leaf=True): return wrapped(*args, **kwargs)
{ "content_hash": "339cd461c4c8b317c73f3b3991ae63a1", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 75, "avg_line_length": 27.973684210526315, "alnum_prop": 0.6312323612417686, "repo_name": "patrys/opbeat_python", "id": "e94bff864d4a72351ce8097de68844bae0fb24bc", "size": "1063", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "opbeat/instrumentation/packages/requests.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "81877" }, { "name": "HTML", "bytes": "377" }, { "name": "Makefile", "bytes": "287" }, { "name": "Python", "bytes": "482619" }, { "name": "Shell", "bytes": "1983" } ], "symlink_target": "" }
""" YES, oor no? """ import datetime import os import sys import json import logging from urllib.request import urlopen import tweepy from device_detector import DeviceDetector from jsondiff import diff from flask import request from flask import Flask, render_template, make_response from google.cloud import storage import google.cloud.logging from google.auth.exceptions import DefaultCredentialsError from google.api_core.exceptions import NotFound import nhlhelpers # https://cloud.google.com/datastore/docs/reference/libraries#client-libraries-usage-python app = Flask(__name__) # /menu is now also /menu/ app.url_map.strict_slashes = False # Setup logging https://cloud.google.com/logging/docs/setup/python CLIENT = google.cloud.logging.Client() CLIENT.setup_logging() # http://exploreflask.com/en/latest/views.html @app.route("/") def view_root(): """No arguments""" return the_root() @app.route("/<string:var1>/") def view_team(var1): """1 argument, team or date""" return the_root(var1, var2=False) @app.route("/<string:var1>/<string:var2>/") def view_teamdate(var1, var2): """2 arguments, hopefully one team and one date""" return the_root(var1, var2) def the_root(var1=False, var2=False): """We use the_root for both /DETROIT and /DETROIT/20220122""" # Set some tomorrow things for when a date or team has not been specified # tomorrow set to today if none is set # because today is like tomorrow if you know what I mean (wink wink) tomorrow = datetime.datetime.now() tomorrow1 = tomorrow.strftime("%Y%m%d") tomorrowurl = f"/{tomorrow1}" ######## team1 = None date1 = None for arg in [var1, var2]: # NHLHelpers we in some dicts replace spaces (%20) with "" .. hmm. if arg and nhlhelpers.get_team(arg.upper().replace(" ", "").replace("%20", "")): team1 = arg.upper().replace(" ", "").replace("%20", "") # If we have a team set tomorrowurl like /teamname/date tomorrowurl = f"/{team1}/{tomorrow1}" elif arg and nhlhelpers.validatedate(arg): date1 = nhlhelpers.validatedate(arg) # If an argument is a date we set tomorrow to one day after that tomorrow = datetime.datetime.strptime( date1, "%Y-%m-%d" ) + datetime.timedelta(days=1) tomorrow1 = tomorrow.strftime("%Y%m%d") tomorrowurl = f"/{tomorrow1}" # Used by the right-arrow on index.html logging.debug(f"var1: {var1} var2: {var2} team1: {team1} date1: {date1}") # If we have a good team and date we have both in tomorrowurl if team1 and date1: tomorrowurl = f"/{team1}/{tomorrow1}" teamlongtext = None if team1: teamlongtext = nhlhelpers.get_team(team1) ######## fgcolor = give_me_a_color(team1) ######## filename = "py3_schedule" if VERSION != "None": filename = "py3_schedule_" + VERSION try: teamdates = json.loads(read_file(filename))["teamdates"] except NotFound: # In case there is no schedule stored for the backend, try to make it logging.info( "Viewing Root but no schedule found, let's try to parse and store it" ) update_schedule() teamdates = json.loads(read_file(filename))["teamdates"] ### Returning something cheap for evil useragent = request.headers.get("User-Agent") logging.debug(f"User-Agent: {useragent}") if useragent: device = DeviceDetector(useragent).parse() else: return render_template("cli.html", yesorno="HMM") if device.is_bot(): return render_template("cli.html", yesorno="NO"), 406 ### The YES/NO logic: yesorno = "NO" if nhlhelpers.yesorno(team1, teamdates, date1): yesorno = "YES" if device.client_type() == "library": return render_template("cli.html", yesorno=yesorno) return render_template( "index.html", yesorno=yesorno, team=team1, teamlongtext=teamlongtext, date=date1, fgcolor=fgcolor, tomorrow=tomorrow, tomorrowurl=tomorrowurl, ) @app.route("/update_schedule") def update_schedule(): """fetches schedule from upstream, parses it, uploads it, sets a version, outputs html for debug""" # default bucket is in this format: project-id.appspot.com # https://cloud.google.com/appengine/docs/standard/python3/using-cloud-storage filename = "py3_schedule_" + VERSION updated_filename = "py3_updated_schedule_" + VERSION logging.info(f"Using filename {filename} and updated_filename {updated_filename}") #### [totalgames, jsondata] = fetch_upstream_schedule(URL) if not jsondata: return ( render_template( "update_schedule.html", version=VERSION, filename=filename, totalgames=totalgames, last_updated=False, changes=False, ), 500, ) changes = False if totalgames == 0: pass else: [teamdates] = parse_schedule(jsondata) content = make_data_json(teamdates) try: old_content = read_file(filename) except NotFound: create_file(filename, content) changes = "just created" logging.info("No schedule found, created it") return ( render_template( "update_schedule.html", version=VERSION, filename=filename, totalgames=totalgames, last_updated=FOR_UPDATED, changes=changes, ), 202, ) if old_content == content: changes = "No changes needed" try: last_updated = read_file(updated_filename) _msg = "Not updating schedule - it is current." logging.info(_msg) except NotFound: create_file(updated_filename, FOR_UPDATED) last_updated = read_file(updated_filename) logging.info(f"Last updated: {last_updated}") else: changes = diff(json.loads(old_content), json.loads(content)) logging.info(f"Changes: {changes}") create_file(filename, content) create_file(updated_filename, FOR_UPDATED) last_updated = read_file(updated_filename) # Only send notifications outside playoffs # (potential spoilers - games are removed from the schedule) if CURRENT_MONTH < 4 or CURRENT_MONTH > 6: logging.info("Sending an update notification") send_an_email(diff(json.loads(old_content), json.loads(content)), True) else: logging.info( "Would have sent an update notification, but it might be playoff folks!" ) return ( render_template( "update_schedule.html", version=VERSION, filename=filename, totalgames=totalgames, last_updated=last_updated, changes=changes, ), 202, ) return render_template( "update_schedule.html", version=VERSION, filename=filename, totalgames=totalgames, last_updated=last_updated, changes=changes, ) @app.route("/get_schedule") def get_schedule(): """Get schedule from GCS and return it as JSON""" if VERSION == "None": filename = "py3_schedule" else: filename = "py3_schedule_" + VERSION logging.info(f"Using filename {filename}") content = json.loads(read_file(filename)) resp = make_response(json.dumps(content, indent=2)) resp.headers["Content-Type"] = "application/json" return resp @app.route("/menu") def menu(): """Return a menu, where one can choose team and some other settings""" allteams = sorted(list(nhlhelpers.get_all_teams().keys())) reallyallteams = nhlhelpers.get_all_teams() return render_template( "menu.html", allteams=allteams, reallyallteams=reallyallteams ) @app.route("/css/menu_team.css") def menu_css(): """Programmatically creates CSS based on the defined teams and their colors""" allteams = sorted(list(nhlhelpers.get_all_teams().keys())) # Recreate give_me_a_color classmethod because I couldn't figure out how to call it colordict = {} # If we use # https://raw.githubusercontent.com/jimniels/teamcolors/master/static/data/teams.json # we would need to pick which of the colors to show. Sometimes it's 3rd, 2nd, first... for ateam in allteams: # Loop through colors and don't pick black as background for the box colors = nhlhelpers.get_team_colors(ateam) backgroundcolor = colors[0] try: backgroundcolor2 = colors[1] except IndexError: backgroundcolor2 = colors[0] if backgroundcolor == "000000": backgroundcolor = backgroundcolor2 colordict[ateam] = backgroundcolor # Make CSS # Default font color is black. # With some backgrounds black is not so readable so we change it to white. # https://en.wikipedia.org/wiki/Template:NHL_team_color might be good, it talks about contrast at least.. whitetext = [ "ARI", "BUF", "CBJ", "DET", "EDM", "NSH", "NYI", "NYR", "TBL", "TOR", "VAN", "WPG", ] yellowtext = ["STL"] # https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Auto-placement_in_CSS_Grid_Layout resp = make_response( render_template( "menu_team.css", allteams=allteams, colordict=colordict, whitetext=whitetext, yellowtext=yellowtext, mimetype="text/css", ) ) resp.headers["Content-Type"] = "text/css" return resp @app.route("/version") def version(): """Fetch a file and render it""" return get_version() # We set_version in update_schedule.py def get_version(): """Fetch a file and return JSON""" # https://cloud.google.com/appengine/docs/standard/python3/using-cloud-storage if VERSION == "None": filename = "py3_updated_schedule" else: filename = "py3_updated_schedule_" + VERSION # If we always store json no need to make it more json jsondata = str(read_file(filename)).replace("'", '"') resp = make_response(jsondata) resp.headers["Content-Type"] = "application/json" return resp def give_me_a_color(team): """Select a color, take second color if the first is black.""" color = nhlhelpers.get_team_colors(team) fgcolor = color[0] try: fgcolor2 = color[1] except IndexError: fgcolor2 = color[0] if fgcolor == "000000": fgcolor = fgcolor2 return fgcolor def create_file(filename, content): """Create a file.""" try: storage_client = storage.Client() except DefaultCredentialsError: logging.error("Could not setup storage client for create_file") return False project_name = os.environ.get( "GOOGLE_CLOUD_PROJECT", "no_GOOGLE_CLOUD_PROJECT_found" ) bucket_name = project_name + ".appspot.com" mybucket = storage_client.bucket(bucket_name) blob = mybucket.blob(filename) logging.info( f"Trying to create filename {filename} in bucket_name {bucket_name}, content size is {get_size(content)}" ) blob.upload_from_string(content, content_type="application/json") return True def stat_file(filename): """stat a file This returns a CLASS, fetch properties in the results with var.id, not var['id'] ??? https://cloud.google.com/storage/docs/viewing-editing-metadata#code-samples """ try: storage_client = storage.Client() except DefaultCredentialsError: logging.error("Could not setup storage client for stat_file") return False project_name = os.environ.get( "GOOGLE_CLOUD_PROJECT", "no_GOOGLE_CLOUD_PROJECT_found" ) bucket_name = project_name + ".appspot.com" mybucket = storage_client.bucket(bucket_name) logging.info(f"Trying to stat filename {filename} in bucket_name {bucket_name}") return mybucket.get_blob(filename) def read_file(filename): """read and return a file!""" try: storage_client = storage.Client() except DefaultCredentialsError: logging.error("Could not setup storage client for read_file") return False project_name = os.environ.get( "GOOGLE_CLOUD_PROJECT", "no_GOOGLE_CLOUD_PROJECT_found" ) bucket_name = project_name + ".appspot.com" mybucket = storage_client.bucket(bucket_name) blob = mybucket.blob(filename) logging.debug(f"Trying to read filename {filename} in bucket_name {bucket_name}") downloaded_blob = blob.download_as_text(encoding="utf-8") return downloaded_blob def get_size(obj, seen=None): """Recursively finds size of objects https://goshippo.com/blog/measure-real-size-any-python-object/ >>> get_size({ "hello": [2,3,[1,2,[2,3]]] }) 674 >>> get_size({ "hello": [2,3,[1,2,[2,3]]], "hello2": [2,3,4,5] }) 869 >>> get_size({}) 280 """ size = sys.getsizeof(obj) if seen is None: seen = set() obj_id = id(obj) if obj_id in seen: return 0 # Important mark as seen *before* entering recursion to gracefully handle # self-referential objects seen.add(obj_id) if isinstance(obj, dict): size += sum([get_size(v, seen) for v in obj.values()]) size += sum([get_size(k, seen) for k in obj.keys()]) elif hasattr(obj, "__dict__"): size += get_size(obj.__dict__, seen) elif hasattr(obj, "__iter__") and not isinstance(obj, (str, bytes, bytearray)): size += sum([get_size(i, seen) for i in obj]) return size def send_an_email(message, twitter=False): """send an e-mail, optionally to the admin""" # Mail is not available in python3 -- only twitter! # Also no implemented way to send the whole change to the Admin real_message = message msgsize = get_size(real_message) # size of 2019-2020 schedule was 530016, unclear how large the jsondiff was 2018->2019 # 50000 is less than 65490 which was in the log of the update # if we change all "Rangers" to "Freeezers" the changes to restore 2019-2020 was 106288 if msgsize > 150000: real_message = f"Msgsize is {msgsize}, see /get_schedule - Hello new season?" logging.info(f" big message: {real_message}") if twitter: # Files uploaded manually, content unquoted # These are strings # Beware of newlines api_key = read_file("API_KEY.TXT") if "\n" in api_key: logging.error( "There's a newline in your twitter API_KEY, doubt that should be in there" ) api_secret_key = read_file("API_SECRET_KEY.TXT") access_token = read_file("ACCESS_TOKEN.TXT") access_token_secret = read_file("ACCESS_TOKEN_SECRET.TXT") # Authenticate to Twitter auth = tweepy.OAuthHandler(api_key, api_secret_key) auth.set_access_token(access_token, access_token_secret) # Create API object api = tweepy.API(auth) # Create a tweet # msgsize: 1577 # changes: {u'teamdates': {u'2019-09-29': {delete: [2]}}} # if msgsize > 1600: # api.update_status(real_message) # else: veri = "testing" if VERSION == "master": veri = "main" api.update_status( f"#NHL {veri} schedule updated on https://wtangy.se - did your team play last night? Try out https://wtangy.se/DETROIT" ) logging.info("Tweeted and message size was %s", msgsize) return True return False def fetch_upstream_schedule(url): """geturl a file and do some health checking""" with urlopen(url) as page: jsondata = json.loads(page.read()) totalgames = jsondata["totalGames"] if totalgames == 0: logging.error("parsing data, 0 games found.") logging.info(f"URL: {url}") return (totalgames, False) return (totalgames, jsondata) def parse_schedule(jsondata): """parse the json data into a dict the app is used to. as a bonus we also sort things The JSON data looks something like this under "dates": {'date': '2022-04-28', 'games': ['teams': {'away': {'team': {'id': 7, 'name': 'Buffalo Sabres'}}, 'home': {'team': {'id': 6, 'name': 'Boston Bruins'}}}} """ dict_of_keys_and_matchups = {} dict_of_keys_and_matchups_s = {} dates = jsondata["dates"] for key in dates: date = key["date"] dict_of_keys_and_matchups[date] = [] games = key["games"] for game in games: twoteams = [] teams = game["teams"] # Montréal and St. Louis Blues are added into the get_team() function # So if someone enters it, it works # But the lookups are then later done with "MTL" or "STL" respectively, # and in some places with "Montreal Canadiens". twoteams.append( teams["away"]["team"]["name"] .replace("Montréal", "Montreal") .replace("St. Louis Blues", "St Louis Blues") ) twoteams.append( teams["home"]["team"]["name"] .replace("Montréal", "Montreal") .replace("St. Louis Blues", "St Louis Blues") ) twoteams_sorted = sorted(twoteams) dict_of_keys_and_matchups[date].append(twoteams_sorted) dict_of_keys_and_matchups_s[date] = sorted(dict_of_keys_and_matchups[date]) logging.info("parsed schedule") return [dict_of_keys_and_matchups_s] def make_data_json(teamdates): """turn parsed data into json, end result in JSON should look like: { "teamdates": { "2017-12-30": [["Boston Bruins", "Ottawa Senators"]], } } """ data = {} data["teamdates"] = teamdates json_data = json.dumps(data, sort_keys=True) logging.info("made json") return json_data if __name__ == "__main__": app.run(host="127.0.0.1", port=8080) # Variables CLIAGENTS = ["curl", "Wget", "Python-urllib"] VERSION = os.environ.get("GAE_VERSION", "no_GAE_VERSION_env_found") NOW = datetime.datetime.now() FOR_UPDATED = str({"version": str(NOW.isoformat())}) [CURRENT_MONTH, CURRENT_YEAR] = NOW.month, NOW.year LAST_YEAR = CURRENT_YEAR - 1 NEXT_YEAR = CURRENT_YEAR + 1 # if now is before August we get last year from September until July if CURRENT_MONTH < 8: START_DATE = f"{LAST_YEAR}-08-01" END_DATE = f"{CURRENT_YEAR}-07-01" # if now is in or after August we get this year from September until July else: START_DATE = f"{CURRENT_YEAR}-08-01" END_DATE = f"{NEXT_YEAR}-07-01" URL = f"https://statsapi.web.nhl.com/api/v1/schedule?startDate={START_DATE}&endDate={END_DATE}"
{ "content_hash": "5c73093e854c42ce6d45c9c6457594f6", "timestamp": "", "source": "github", "line_count": 612, "max_line_length": 131, "avg_line_length": 31.751633986928105, "alnum_prop": 0.6044668587896254, "repo_name": "martbhell/wasthereannhlgamelastnight", "id": "4c103c7b068d1e0ad9e25ca4a8f8665609c35508", "size": "19435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "730" }, { "name": "HTML", "bytes": "8959" }, { "name": "JavaScript", "bytes": "3318" }, { "name": "Python", "bytes": "5989638" } ], "symlink_target": "" }
from CGvsPhoto import Model # to change to your favorite database database_path = '/work/smg/v-nicolas/level-design_raise_100_color/' # database_path = '/work/smg/v-nicolas/face_DB_100_2/' database_path = '/home/nicolas/Database/level-design_raise_100_color/' # to change to the format of your image image_size = 100 # define a single-image classifier clf = Model(database_path, image_size, config = 'Personal', filters = [32,32,64], batch_size = 50, feature_extractor = 'Stats', remove_context = True, remove_filter_size = 5, only_green = False) # trains the classifier and test it on the testing set clf.train(nb_train_batch = 1, nb_test_batch = 80, nb_validation_batch = 40, validation_frequency = 20, show_filters = True)
{ "content_hash": "4c8db4c87be8b0330aaef891258254ef", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 81, "avg_line_length": 34.69565217391305, "alnum_prop": 0.6704260651629073, "repo_name": "NicoRahm/CGvsPhoto", "id": "21f041fa621821ac955c4946927b4fc3e077ffbb", "size": "798", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/test_pipeline.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "155534" } ], "symlink_target": "" }
import praw import smtplib import requests import parsel import re import io import json import os from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from argparse import ArgumentParser from premailer import Premailer HEADERS = requests.utils.default_headers() HEADERS.update({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0'}) SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__)) REDDIT_CSS = os.path.join(SCRIPT_PATH, 'css', 'reddit.css') def _concat_css(input_name, output): with open(input_name, encoding='utf-8') as f: output.write('\n<style>\n') output.write(f.read()) output.write('\n</style>\n') def _extract_external_css(selector): for p in selector.xpath("/html/head/link[@rel='stylesheet']"): href = re.sub(r"^//", r"https://", p.xpath("@href").extract_first()) sheet = requests.get(href, headers=HEADERS).text if href else "" yield sheet def weekly_page(subreddit, file, css=None): if isinstance(file, str): with open(file, 'w', encoding='utf-8') as f: return weekly_page(subreddit, file=f, css=css) r = requests.get("https://www.reddit.com/r/{}/top/?sort=top&t=week".format(subreddit), headers=HEADERS) if r.status_code != 200: raise RuntimeError("Request status code is {}.".format(r.status_code)) if r.encoding.lower() != 'utf-8': raise RuntimeError("Request didn't return a UTF-8 output.") sel = parsel.Selector(text=r.text) file.write('<!DOCTYPE html>') file.write('<html>') if css == 1: # Download External file.write('<head>') file.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">') for stylesheet in _extract_external_css(sel): file.write('\n<style>\n') file.write(stylesheet) file.write('\n</style>\n') file.write('</head>') elif css == 2: # Keep External head = sel.xpath("/html/head").extract_first() head = re.sub(r'="//', '="https://', head) file.write(head) elif isinstance(css, str): file.write('<head>') file.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">') _concat_css(css, file) file.write('</head>') elif isinstance(css, list): file.write('<head>') file.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">') for c in css: _concat_css(c, file) file.write('</head>') else: file.write('<head>') file.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">') file.write('</head>') file.write('<body class="">') file.write('<div class="content" role="main">') for spacer in sel.xpath("/html/body/div[@class='content']/div[@class='spacer' and style]"): content = spacer.extract() content = re.sub(r'="//', r'="https://', content) file.write(content) file.write('</div>') file.write('</body>') file.write('</html>') def send_email(subject, to, message): fromaddr = os.environ['REWE_SENDER'] frompass = os.environ['REWE_PASS'] msg = MIMEMultipart('alternative') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = fromaddr msg['To'] = to msg.attach(MIMEText('Weekly Subreddit', 'plain')) msg.attach(MIMEText(message, 'html')) with smtplib.SMTP(host='smtp.gmail.com', port=587) as server: server.ehlo() server.starttls() server.ehlo() server.login(fromaddr, frompass) server.sendmail(fromaddr, [to], msg.as_string()) def user_subreddits(token): reddit = praw.Reddit(client_id=os.environ['REWE_APP_ID'], client_secret=os.environ['REWE_APP_SECRET'], user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0', refresh_token=token) return reddit.user.subreddits() def send_newsletter(token, email): for subreddit in user_subreddits(token): subreddit = subreddit.display_name with io.StringIO() as body: print("Sending {} weekly for {}...".format(subreddit, email)) weekly_page(subreddit, body, css=REDDIT_CSS) email_body = Premailer(body.getvalue(), base_url='https://www.reddit.com', disable_leftover_css=True).transform() send_email(subject='Reddit weekly r/{}'.format(subreddit), to=email, message=email_body) def main(filepath): with io.open(filepath, 'r') as file: users = json.load(file) for email in users: token = users[email] send_newsletter(token, email) # usage: ./rewe.py -u, --users=<json> if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('-u', '--users', required=True, help='load users and their tokens from a JSON file') opt = parser.parse_args() main(opt.users)
{ "content_hash": "1b09c3b9ae258b3fbcca2dca61a609c8", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 117, "avg_line_length": 36.35664335664335, "alnum_prop": 0.597422581265628, "repo_name": "thelostt/reddit-weekly", "id": "98cc6d6a8f112861f00832568d7927409117c59f", "size": "5215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rewe.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "5215" } ], "symlink_target": "" }
from file_util import * import os import re import shutil import string import sys import textwrap import time import itertools import hashlib class cef_api_hash: """ CEF API hash calculator """ def __init__(self, headerdir, debugdir = None, verbose = False): if headerdir is None or len(headerdir) == 0: raise AssertionError("headerdir is not specified") self.__headerdir = headerdir; self.__debugdir = debugdir; self.__verbose = verbose; self.__debug_enabled = not (self.__debugdir is None) and len(self.__debugdir) > 0; self.platforms = [ "windows", "macosx", "linux" ]; self.platform_files = { "windows": [ "internal/cef_types_win.h" ], "macosx": [ "internal/cef_types_mac.h", ], "linux": [ "internal/cef_types_linux.h" ] }; self.included_files = [ "cef_trace_event.h" ]; self.excluded_files = [ "cef_version.h", "internal/cef_tuple.h", "internal/cef_types_wrappers.h", "internal/cef_string_wrappers.h", "internal/cef_win.h", "internal/cef_mac.h", "internal/cef_linux.h", ]; def calculate(self): filenames = [filename for filename in self.__get_filenames() if not filename in self.excluded_files] objects = [] for filename in filenames: if self.__verbose: print "Processing " + filename + "..." content = read_file(os.path.join(self.__headerdir, filename), True) platforms = list([p for p in self.platforms if self.__is_platform_filename(filename, p)]) # Parse cef_string.h happens in special case: grab only defined CEF_STRING_TYPE_xxx declaration content_objects = None if filename == "internal/cef_string.h": content_objects = self.__parse_string_type(content) else: content_objects = self.__parse_objects(content) for o in content_objects: o["text"] = self.__prepare_text(o["text"]) o["platforms"] = platforms o["filename"] = filename objects.append(o) # objects will be sorted including filename, to make stable universal hashes objects = sorted(objects, key = lambda o: o["name"] + "@" + o["filename"]) if self.__debug_enabled: namelen = max([len(o["name"]) for o in objects]) filenamelen = max([len(o["filename"]) for o in objects]) dumpsig = []; for o in objects: dumpsig.append(format(o["name"], str(namelen) + "s") + "|" + format(o["filename"], "" + str(filenamelen) + "s") + "|" + o["text"]); self.__write_debug_file("objects.txt", dumpsig) revisions = { }; for platform in itertools.chain(["universal"], self.platforms): sig = self.__get_final_sig(objects, platform) if self.__debug_enabled: self.__write_debug_file(platform + ".sig", sig) rev = hashlib.sha1(sig).digest(); revstr = ''.join(format(ord(i),'0>2x') for i in rev) revisions[platform] = revstr return revisions def __parse_objects(self, content): """ Returns array of objects in content file. """ objects = [] content = re.sub("//.*\n", "", content) # function declarations for m in re.finditer("\nCEF_EXPORT\s+?.*?\s+?(\w+)\s*?\(.*?\)\s*?;", content, flags = re.DOTALL): object = { "name": m.group(1), "text": m.group(0).strip() } objects.append(object) # structs for m in re.finditer("\ntypedef\s+?struct\s+?(\w+)\s+?\{.*?\}\s+?(\w+)\s*?;", content, flags = re.DOTALL): object = { "name": m.group(2), "text": m.group(0).strip() } objects.append(object) # enums for m in re.finditer("\nenum\s+?(\w+)\s+?\{.*?\}\s*?;", content, flags = re.DOTALL): object = { "name": m.group(1), "text": m.group(0).strip() } objects.append(object) # typedefs for m in re.finditer("\ntypedef\s+?.*?\s+(\w+);", content, flags = 0): object = { "name": m.group(1), "text": m.group(0).strip() } objects.append(object) return objects def __parse_string_type(self, content): """ Grab defined CEF_STRING_TYPE_xxx """ objects = [] for m in re.finditer("\n\s*?#\s*?define\s+?(CEF_STRING_TYPE_\w+)\s+?.*?\n", content, flags = 0): object = { "name": m.group(1), "text": m.group(0), } objects.append(object) return objects def __prepare_text(self, text): text = text.strip() text = re.sub("\s+", " ", text); text = re.sub("\(\s+", "(", text); return text def __get_final_sig(self, objects, platform): sig = [] for o in objects: if platform == "universal" or platform in o["platforms"]: sig.append(o["text"]) return "\n".join(sig) def __get_filenames(self): """ Returns file names to be processed, relative to headerdir """ headers = [os.path.join(self.__headerdir, filename) for filename in self.included_files]; headers = itertools.chain(headers, get_files(os.path.join(self.__headerdir, "capi", "*.h"))) headers = itertools.chain(headers, get_files(os.path.join(self.__headerdir, "internal", "*.h"))) for v in self.platform_files.values(): headers = itertools.chain(headers, [os.path.join(self.__headerdir, f) for f in v]) normalized = [os.path.relpath(filename, self.__headerdir) for filename in headers]; normalized = [f.replace('\\', '/').lower() for f in normalized]; return list(set(normalized)); def __is_platform_filename(self, filename, platform): if platform == "universal": return True if not platform in self.platform_files: return False listed = False for p in self.platforms: if filename in self.platform_files[p]: if p == platform: return True else: listed = True return not listed def __write_debug_file(self, filename, content): make_dir(self.__debugdir); outfile = os.path.join(self.__debugdir, filename); dir = os.path.dirname(outfile); make_dir(dir); if not isinstance(content, basestring): content = "\n".join(content) write_file(outfile, content) if __name__ == "__main__": from optparse import OptionParser import time disc = """ This utility calculates CEF API hash. """ parser = OptionParser(description=disc) parser.add_option('--cpp-header-dir', dest='cppheaderdir', metavar='DIR', help='input directory for C++ header files [required]') parser.add_option('--debug-dir', dest='debugdir', metavar='DIR', help='intermediate directory for easy debugging') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='output detailed status information') (options, args) = parser.parse_args() # the cppheader option is required if options.cppheaderdir is None: parser.print_help(sys.stdout) sys.exit() # calculate c_start_time = time.time() calc = cef_api_hash(options.cppheaderdir, options.debugdir, options.verbose); revisions = calc.calculate(); c_completed_in = time.time() - c_start_time print "{" for k in sorted(revisions.keys()): print format("\"" + k + "\"", ">12s") + ": \"" + revisions[k] + "\"" print "}" # print # print 'Completed in: ' + str(c_completed_in) # print # print "Press any key to continue..."; # sys.stdin.readline();
{ "content_hash": "a4dbca3b179748d725516f302345c103", "timestamp": "", "source": "github", "line_count": 242, "max_line_length": 147, "avg_line_length": 34.553719008264466, "alnum_prop": 0.5287012676393207, "repo_name": "denzp/cef3", "id": "36c71010ac8aaae2458f66305ad5ed8ec07bd249", "size": "8548", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/cef_api_hash.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "87567" }, { "name": "C++", "bytes": "4045051" }, { "name": "Objective-C", "bytes": "120349" }, { "name": "Python", "bytes": "66559" }, { "name": "Shell", "bytes": "109" } ], "symlink_target": "" }
import os from glob import glob from ..templates.admin.updatehistory import selectfile, updatehistorysummary, updatehistoryspace from ..templates.admin.updatedatabase import restoreprogress import sqlite3 class UpdateHistory: __dispatch__ = 'resource' __resource__ = 'updatehistory' def __init__(self, context, name, *arg, **args): self._ctx = context ctx = context self.uploaddir = os.path.join('privatefilearea', context.djname) def get(self, *arg, **args): if self._ctx.queries.is_updating(): return selectdatabasefile('Updating Database', self._ctx) if self._ctx.queries.is_restoring(): return restoreprogress('Restoring Database', self._ctx) files = sorted(glob(os.path.join(self.uploaddir, 'history-*.sqlite')), reverse=True) if len(files) == 1: return self.view(fileselection=os.path.split(files[0])[-1]) return selectfile("Select History File", self._ctx, files) def view(self, *arg, **args): print('View', arg, args) fn = os.path.join(self.uploaddir, args['fileselection']) sqdb = sqlite3.connect(fn) sqdb.row_factory = sqlite3.Row cursor = sqdb.cursor() summary = {} valid_fields = ('empty', 'dash', 'space', 'updated') if 'details' in args: if args['details'] not in valid_fields: print('Bad details arg') return None x = cursor.execute('select count(id) as fcount, id from fixedtable where recordtype=:rtype group by id', {'rtype':args['details']}) return updatehistoryspace('Update Details', self._ctx, x, cursor, args) for t in valid_fields: x = cursor.execute('select count(distinct id) as tcount from fixedtable where recordtype=:rtype', {'rtype': t}).fetchone() summary[t] = x['tcount'] summary['stats'] = cursor.execute('select * from stats').fetchone() return updatehistorysummary('Update Summary', self._ctx, summary, args['fileselection'])
{ "content_hash": "cdc0601994e983b9c6e18cf1094d8817", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 143, "avg_line_length": 44.93478260869565, "alnum_prop": 0.6289308176100629, "repo_name": "bmillham/djrq2", "id": "f496e17dfa0a85324b686d23170127577a3b15ca", "size": "2086", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/app/djrq/admin/updatehistory.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22622" }, { "name": "JavaScript", "bytes": "59510" }, { "name": "Python", "bytes": "267514" }, { "name": "Shell", "bytes": "1030" } ], "symlink_target": "" }
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase class BaseViewTests(TestCase): def test_shouldHideLoginAndSignup_AndHideLogout_WhenUserLoggedIn(self): # Given user = User.objects.create_user(username="someusername", password="mysecurepassword") form_data = { 'username': 'someusername', 'password': 'mysecurepassword', } self.client.post(reverse('learn:login'), data=form_data) # When response = self.client.get(reverse('learn:dictionaries')) # Then self.assertInHTML( '<li><a href="' + reverse('learn:logout') + '">Log out</a></li>', response.content.decode('utf8'), count=2) self.assertInHTML( '<li><a href="' + reverse('learn:signup') + '">Sign up</a></li>', response.content.decode('utf8'), count=0) self.assertInHTML( '<li><a href="' + reverse('learn:login') + '">Log in</a></li>', response.content.decode('utf8'), count=0)
{ "content_hash": "6483068382fc6cdaebaccad96ca51dcc", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 114, "avg_line_length": 39.964285714285715, "alnum_prop": 0.5871313672922251, "repo_name": "Aigrefin/py3learn", "id": "485122dc8df141bb7fcc4ab48e5f004ef7e60860", "size": "1119", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "learn/tests/tests_views/tests_int/tests_int_baseview.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1112" }, { "name": "HTML", "bytes": "13577" }, { "name": "Python", "bytes": "105197" } ], "symlink_target": "" }
from linqy import utils class Comparison(object): def __init__(self, key): self.key = key def __eq__(self, other): return self.key == other.key def __ne__(self, other): return self.key != other.key def __lt__(self, other): return self.key < other.key def __le__(self, other): return self.key <= other.key def __gt__(self, other): return self.key > other.key def __ge__(self, other): return self.key >= other.key class Reverse(Comparison): __lt__ = utils.not_(Comparison.__lt__) __le__ = utils.not_(Comparison.__le__) __gt__ = utils.not_(Comparison.__gt__) __ge__ = utils.not_(Comparison.__ge__)
{ "content_hash": "37c13f204549e6bbb7945994e2248663", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 42, "avg_line_length": 22.741935483870968, "alnum_prop": 0.5460992907801419, "repo_name": "mashiro/linqy", "id": "84facc067333e512991059f713e7dd3c5c4f24ab", "size": "751", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "linqy/comparison.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "45711" } ], "symlink_target": "" }
import logging logging.basicConfig(level=logging.WARNING) logger1 = logging.getLogger('package1.module1') logger2 = logging.getLogger('package2.module2') logger1.warning('This message comes from one module') logger2.warning('This comes from another module')
{ "content_hash": "558f341624141d0e80ec72c5586f329b", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 53, "avg_line_length": 26.2, "alnum_prop": 0.7977099236641222, "repo_name": "jasonwee/asus-rt-n14uhp-mrtg", "id": "9770288675e97bb160d2d8670e325aeb95f60eab", "size": "262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/lesson_application_building_blocks/logging_modules_example.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "45876" }, { "name": "HTML", "bytes": "107072" }, { "name": "JavaScript", "bytes": "161335" }, { "name": "Python", "bytes": "6923750" }, { "name": "Shell", "bytes": "7616" } ], "symlink_target": "" }
import re import numpy as np from Orange.data import Table, Domain, DiscreteVariable ANNOTATED_DATA_SIGNAL_NAME = "Data" ANNOTATED_DATA_FEATURE_NAME = "Selected" def _get_next_name(names, name): """ Returns next 'possible' attribute name. The name should not be duplicated and is generated using name parameter, appended by smallest possible index. :param names: list :param name: str :return: str """ indexes = [int(a.group(2)) for x in names for a in re.finditer("(^{} \()(\d{{1,}})(\)$)".format(name), x)] if name not in names and not indexes: return name return "{} ({})".format(name, max(indexes, default=1) + 1) def create_annotated_table(data, selected_indices): """ Returns data with concatenated flag column. Flag column represents whether data instance has been selected (Yes) or not (No), which is determined in selected_indices parameter. :param data: Table :param selected_indices: list or ndarray :return: Table """ if data is None: return None names = [var.name for var in data.domain.variables + data.domain.metas] name = _get_next_name(names, ANNOTATED_DATA_FEATURE_NAME) metas = data.domain.metas + (DiscreteVariable(name, ("No", "Yes")),) domain = Domain(data.domain.attributes, data.domain.class_vars, metas) annotated = np.zeros((len(data), 1)) if selected_indices is not None: annotated[selected_indices] = 1 table = Table(domain, data.X, data.Y, metas=np.hstack((data.metas, annotated))) table.attributes = data.attributes return table
{ "content_hash": "317df3351fa3c225c1eec9a96d053431", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 79, "avg_line_length": 34.787234042553195, "alnum_prop": 0.6593272171253822, "repo_name": "cheral/orange3", "id": "1f7d477d66e198f6b6705958fbc397ff8faa92fe", "size": "1635", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Orange/widgets/utils/annotated_data.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "20412" }, { "name": "C++", "bytes": "1992" }, { "name": "GLSL", "bytes": "75" }, { "name": "HTML", "bytes": "3503" }, { "name": "JavaScript", "bytes": "12023" }, { "name": "Jupyter Notebook", "bytes": "6662" }, { "name": "NSIS", "bytes": "20217" }, { "name": "Python", "bytes": "4139574" }, { "name": "Shell", "bytes": "47441" } ], "symlink_target": "" }
#!/usr/bin/python # # Copyright 2013, Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. import base64 import logging import os import threading import struct import time import unittest from vtdb import keyrange_constants import environment import utils import tablet keyspace_id_type = keyrange_constants.KIT_UINT64 pack_keyspace_id = struct.Struct('!Q').pack # initial shards # range "" - 80 shard_0_master = tablet.Tablet() shard_0_replica = tablet.Tablet() # range 80 - "" shard_1_master = tablet.Tablet() shard_1_slave1 = tablet.Tablet() shard_1_slave2 = tablet.Tablet() shard_1_rdonly = tablet.Tablet() # split shards # range 80 - C0 shard_2_master = tablet.Tablet() shard_2_replica1 = tablet.Tablet() shard_2_replica2 = tablet.Tablet() # range C0 - "" shard_3_master = tablet.Tablet() shard_3_replica = tablet.Tablet() shard_3_rdonly = tablet.Tablet() def setUpModule(): try: environment.topo_server_setup() setup_procs = [ shard_0_master.init_mysql(), shard_0_replica.init_mysql(), shard_1_master.init_mysql(), shard_1_slave1.init_mysql(), shard_1_slave2.init_mysql(), shard_1_rdonly.init_mysql(), shard_2_master.init_mysql(), shard_2_replica1.init_mysql(), shard_2_replica2.init_mysql(), shard_3_master.init_mysql(), shard_3_replica.init_mysql(), shard_3_rdonly.init_mysql(), ] utils.wait_procs(setup_procs) except: tearDownModule() raise def tearDownModule(): if utils.options.skip_teardown: return teardown_procs = [ shard_0_master.teardown_mysql(), shard_0_replica.teardown_mysql(), shard_1_master.teardown_mysql(), shard_1_slave1.teardown_mysql(), shard_1_slave2.teardown_mysql(), shard_1_rdonly.teardown_mysql(), shard_2_master.teardown_mysql(), shard_2_replica1.teardown_mysql(), shard_2_replica2.teardown_mysql(), shard_3_master.teardown_mysql(), shard_3_replica.teardown_mysql(), shard_3_rdonly.teardown_mysql(), ] utils.wait_procs(teardown_procs, raise_on_error=False) environment.topo_server_teardown() utils.kill_sub_processes() utils.remove_tmp_files() shard_0_master.remove_tree() shard_0_replica.remove_tree() shard_1_master.remove_tree() shard_1_slave1.remove_tree() shard_1_slave2.remove_tree() shard_1_rdonly.remove_tree() shard_2_master.remove_tree() shard_2_replica1.remove_tree() shard_2_replica2.remove_tree() shard_3_master.remove_tree() shard_3_replica.remove_tree() shard_3_rdonly.remove_tree() # InsertThread will insert a value into the timestamps table, and then # every 1/5s will update its value with the current timestamp class InsertThread(threading.Thread): def __init__(self, tablet, object_name, user_id, keyspace_id): threading.Thread.__init__(self) self.tablet = tablet self.object_name = object_name self.user_id = user_id self.keyspace_id = keyspace_id if keyspace_id_type == keyrange_constants.KIT_BYTES: self.str_keyspace_id = base64.b64encode(pack_keyspace_id(keyspace_id)) else: self.str_keyspace_id = "%u" % keyspace_id self.done = False self.tablet.mquery('vt_test_keyspace', [ 'begin', 'insert into timestamps(name, time_milli, keyspace_id) values("%s", %u, 0x%x) /* EMD keyspace_id:%s user_id:%u */' % (self.object_name, long(time.time() * 1000), self.keyspace_id, self.str_keyspace_id, self.user_id), 'commit' ], write=True, user='vt_app') self.start() def run(self): try: while not self.done: self.tablet.mquery('vt_test_keyspace', [ 'begin', 'update timestamps set time_milli=%u where name="%s" /* EMD keyspace_id:%s user_id:%u */' % (long(time.time() * 1000), self.object_name, self.str_keyspace_id, self.user_id), 'commit' ], write=True, user='vt_app') time.sleep(0.2) except Exception as e: logging.error("InsertThread got exception: %s", e) # MonitorLagThread will get values from a database, and compare the timestamp # to evaluate lag. Since the qps is really low, and we send binlogs as chuncks, # the latency is pretty high (a few seconds). class MonitorLagThread(threading.Thread): def __init__(self, tablet, object_name): threading.Thread.__init__(self) self.tablet = tablet self.object_name = object_name self.done = False self.max_lag = 0 self.lag_sum = 0 self.sample_count = 0 self.start() def run(self): try: while not self.done: result = self.tablet.mquery('vt_test_keyspace', 'select time_milli from timestamps where name="%s"' % self.object_name) if result: lag = long(time.time() * 1000) - long(result[0][0]) logging.debug("MonitorLagThread(%s) got %u", self.object_name, lag) self.sample_count += 1 self.lag_sum += lag if lag > self.max_lag: self.max_lag = lag time.sleep(1.0) except Exception as e: logging.error("MonitorLagThread got exception: %s", e) class TestResharding(unittest.TestCase): # create_schema will create the same schema on the keyspace # then insert some values def _create_schema(self): if keyspace_id_type == keyrange_constants.KIT_BYTES: t = 'varbinary(64)' else: t = 'bigint(20) unsigned' create_table_template = '''create table %s( id bigint auto_increment, msg varchar(64), keyspace_id ''' + t + ''' not null, primary key (id), index by_msg (msg) ) Engine=InnoDB''' create_view_template = '''create view %s(id, msg, keyspace_id) as select id, msg, keyspace_id from %s''' create_timestamp_table = '''create table timestamps( name varchar(64), time_milli bigint(20) unsigned not null, keyspace_id ''' + t + ''' not null, primary key (name) ) Engine=InnoDB''' create_unrelated_table = '''create table unrelated( name varchar(64), primary key (name) ) Engine=InnoDB''' utils.run_vtctl(['ApplySchemaKeyspace', '-simple', '-sql=' + create_table_template % ("resharding1"), 'test_keyspace'], auto_log=True) utils.run_vtctl(['ApplySchemaKeyspace', '-simple', '-sql=' + create_table_template % ("resharding2"), 'test_keyspace'], auto_log=True) utils.run_vtctl(['ApplySchemaKeyspace', '-simple', '-sql=' + create_view_template % ("view1", "resharding1"), 'test_keyspace'], auto_log=True) utils.run_vtctl(['ApplySchemaKeyspace', '-simple', '-sql=' + create_timestamp_table, 'test_keyspace'], auto_log=True) utils.run_vtctl(['ApplySchemaKeyspace', '-simple', '-sql=' + create_unrelated_table, 'test_keyspace'], auto_log=True) # _insert_value inserts a value in the MySQL database along with the comments # required for routing. def _insert_value(self, tablet, table, id, msg, keyspace_id): if keyspace_id_type == keyrange_constants.KIT_BYTES: k = base64.b64encode(pack_keyspace_id(keyspace_id)) else: k = "%u" % keyspace_id tablet.mquery('vt_test_keyspace', [ 'begin', 'insert into %s(id, msg, keyspace_id) values(%u, "%s", 0x%x) /* EMD keyspace_id:%s user_id:%u */' % (table, id, msg, keyspace_id, k, id), 'commit' ], write=True) def _get_value(self, tablet, table, id): return tablet.mquery('vt_test_keyspace', 'select id, msg, keyspace_id from %s where id=%u' % (table, id)) def _check_value(self, tablet, table, id, msg, keyspace_id, should_be_here=True): result = self._get_value(tablet, table, id) if keyspace_id_type == keyrange_constants.KIT_BYTES: fmt = "%s" keyspace_id = pack_keyspace_id(keyspace_id) else: fmt = "%x" if should_be_here: self.assertEqual(result, ((id, msg, keyspace_id),), ("Bad row in tablet %s for id=%u, keyspace_id=" + fmt + ", row=%s") % (tablet.tablet_alias, id, keyspace_id, str(result))) else: self.assertEqual(len(result), 0, ("Extra row in tablet %s for id=%u, keyspace_id=" + fmt + ": %s") % (tablet.tablet_alias, id, keyspace_id, str(result))) # _is_value_present_and_correct tries to read a value. # if it is there, it will check it is correct and return True if it is. # if not correct, it will self.fail. # if not there, it will return False. def _is_value_present_and_correct(self, tablet, table, id, msg, keyspace_id): result = self._get_value(tablet, table, id) if len(result) == 0: return False if keyspace_id_type == keyrange_constants.KIT_BYTES: fmt = "%s" keyspace_id = pack_keyspace_id(keyspace_id) else: fmt = "%x" self.assertEqual(result, ((id, msg, keyspace_id),), ("Bad row in tablet %s for id=%u, keyspace_id=" + fmt) % ( tablet.tablet_alias, id, keyspace_id)) return True def _insert_startup_values(self): self._insert_value(shard_0_master, 'resharding1', 1, 'msg1', 0x1000000000000000) self._insert_value(shard_1_master, 'resharding1', 2, 'msg2', 0x9000000000000000) self._insert_value(shard_1_master, 'resharding1', 3, 'msg3', 0xD000000000000000) def _check_startup_values(self): # check first value is in the right shard self._check_value(shard_2_master, 'resharding1', 2, 'msg2', 0x9000000000000000) self._check_value(shard_2_replica1, 'resharding1', 2, 'msg2', 0x9000000000000000) self._check_value(shard_2_replica2, 'resharding1', 2, 'msg2', 0x9000000000000000) self._check_value(shard_3_master, 'resharding1', 2, 'msg2', 0x9000000000000000, should_be_here=False) self._check_value(shard_3_replica, 'resharding1', 2, 'msg2', 0x9000000000000000, should_be_here=False) self._check_value(shard_3_rdonly, 'resharding1', 2, 'msg2', 0x9000000000000000, should_be_here=False) # check second value is in the right shard too self._check_value(shard_2_master, 'resharding1', 3, 'msg3', 0xD000000000000000, should_be_here=False) self._check_value(shard_2_replica1, 'resharding1', 3, 'msg3', 0xD000000000000000, should_be_here=False) self._check_value(shard_2_replica2, 'resharding1', 3, 'msg3', 0xD000000000000000, should_be_here=False) self._check_value(shard_3_master, 'resharding1', 3, 'msg3', 0xD000000000000000) self._check_value(shard_3_replica, 'resharding1', 3, 'msg3', 0xD000000000000000) self._check_value(shard_3_rdonly, 'resharding1', 3, 'msg3', 0xD000000000000000) def _insert_lots(self, count, base=0): for i in xrange(count): self._insert_value(shard_1_master, 'resharding1', 10000 + base + i, 'msg-range1-%u' % i, 0xA000000000000000 + base + i) self._insert_value(shard_1_master, 'resharding1', 20000 + base + i, 'msg-range2-%u' % i, 0xE000000000000000 + base + i) # _check_lots returns how many of the values we have, in percents. def _check_lots(self, count, base=0): found = 0 for i in xrange(count): if self._is_value_present_and_correct(shard_2_replica2, 'resharding1', 10000 + base + i, 'msg-range1-%u' % i, 0xA000000000000000 + base + i): found += 1 if self._is_value_present_and_correct(shard_3_replica, 'resharding1', 20000 + base + i, 'msg-range2-%u' % i, 0xE000000000000000 + base + i): found += 1 percent = found * 100 / count / 2 logging.debug("I have %u%% of the data", percent) return percent def _check_lots_timeout(self, count, threshold, timeout, base=0): while True: value = self._check_lots(count, base=base) if value >= threshold: return if timeout == 0: self.fail("timeout waiting for %u%% of the data" % threshold) logging.debug("sleeping until we get %u%%", threshold) time.sleep(1) timeout -= 1 # _check_lots_not_present makes sure no data is in the wrong shard def _check_lots_not_present(self, count, base=0): found = 0 for i in xrange(count): self._check_value(shard_3_replica, 'resharding1', 10000 + base + i, 'msg-range1-%u' % i, 0xA000000000000000 + base + i, should_be_here=False) self._check_value(shard_2_replica2, 'resharding1', 20000 + base + i, 'msg-range2-%u' % i, 0xE000000000000000 + base + i, should_be_here=False) def _check_binlog_server_vars(self, tablet): v = utils.get_vars(tablet.port) self.assertTrue('UpdateStreamKeyRangeStatements' in v) self.assertTrue('UpdateStreamKeyRangeTransactions' in v) def _check_binlog_player_vars(self, tablet, seconds_behind_master_max = 0): v = utils.get_vars(tablet.port) self.assertTrue('BinlogPlayerMapSize' in v) self.assertTrue('BinlogPlayerSecondsBehindMaster' in v) self.assertTrue('BinlogPlayerSecondsBehindMasterMap' in v) self.assertTrue('BinlogPlayerGroupIdMap' in v) self.assertTrue('0' in v['BinlogPlayerGroupIdMap']) self.assertTrue('BinlogPlayerSourceShardNameMap' in v) self.assertTrue('0' in v['BinlogPlayerSourceShardNameMap']) self.assertEquals(v['BinlogPlayerSourceShardNameMap']['0'], 'test_keyspace/80-') self.assertTrue('BinlogPlayerSourceTabletAliasMap' in v) self.assertTrue('0' in v['BinlogPlayerSourceTabletAliasMap']) if seconds_behind_master_max != 0: self.assertTrue(v['BinlogPlayerSecondsBehindMaster'] < seconds_behind_master_max, 'BinlogPlayerSecondsBehindMaster is too high: %u > %u' % ( v['BinlogPlayerSecondsBehindMaster'], seconds_behind_master_max)) self.assertTrue(v['BinlogPlayerSecondsBehindMasterMap']['0'] < seconds_behind_master_max, 'BinlogPlayerSecondsBehindMasterMap is too high: %u > %u' % ( v['BinlogPlayerSecondsBehindMasterMap']['0'], seconds_behind_master_max)) def test_resharding(self): utils.run_vtctl(['CreateKeyspace', '--sharding_column_name', 'bad_column', '--sharding_column_type', 'bytes', 'test_keyspace']) utils.run_vtctl(['SetKeyspaceShardingInfo', 'test_keyspace', 'keyspace_id', 'uint64'], expect_fail=True) utils.run_vtctl(['SetKeyspaceShardingInfo', '-force', 'test_keyspace', 'keyspace_id', keyspace_id_type]) shard_0_master.init_tablet( 'master', 'test_keyspace', '-80') shard_0_replica.init_tablet('replica', 'test_keyspace', '-80') shard_1_master.init_tablet( 'master', 'test_keyspace', '80-') shard_1_slave1.init_tablet('replica', 'test_keyspace', '80-') shard_1_slave2.init_tablet('spare', 'test_keyspace', '80-') shard_1_rdonly.init_tablet('rdonly', 'test_keyspace', '80-') utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True) # we set full_mycnf_args to True as a test in the KIT_BYTES case full_mycnf_args = keyspace_id_type == keyrange_constants.KIT_BYTES # create databases so vttablet can start behaving normally for t in [shard_0_master, shard_0_replica, shard_1_master, shard_1_slave1, shard_1_slave2, shard_1_rdonly]: t.create_db('vt_test_keyspace') t.start_vttablet(wait_for_state=None, full_mycnf_args=full_mycnf_args) # wait for the tablets shard_0_master.wait_for_vttablet_state('SERVING') shard_0_replica.wait_for_vttablet_state('SERVING') shard_1_master.wait_for_vttablet_state('SERVING') shard_1_slave1.wait_for_vttablet_state('SERVING') shard_1_slave2.wait_for_vttablet_state('NOT_SERVING') # spare shard_1_rdonly.wait_for_vttablet_state('SERVING') # reparent to make the tablets work utils.run_vtctl(['ReparentShard', '-force', 'test_keyspace/-80', shard_0_master.tablet_alias], auto_log=True) utils.run_vtctl(['ReparentShard', '-force', 'test_keyspace/80-', shard_1_master.tablet_alias], auto_log=True) # create the tables self._create_schema() self._insert_startup_values() # create the split shards shard_2_master.init_tablet( 'master', 'test_keyspace', '80-C0') shard_2_replica1.init_tablet('spare', 'test_keyspace', '80-C0') shard_2_replica2.init_tablet('spare', 'test_keyspace', '80-C0') shard_3_master.init_tablet( 'master', 'test_keyspace', 'C0-') shard_3_replica.init_tablet('spare', 'test_keyspace', 'C0-') shard_3_rdonly.init_tablet('rdonly', 'test_keyspace', 'C0-') # start vttablet on the split shards (no db created, # so they're all not serving) for t in [shard_2_master, shard_2_replica1, shard_2_replica2, shard_3_master, shard_3_replica, shard_3_rdonly]: t.start_vttablet(wait_for_state=None) for t in [shard_2_master, shard_2_replica1, shard_2_replica2, shard_3_master, shard_3_replica, shard_3_rdonly]: t.wait_for_vttablet_state('NOT_SERVING') utils.run_vtctl(['ReparentShard', '-force', 'test_keyspace/80-C0', shard_2_master.tablet_alias], auto_log=True) utils.run_vtctl(['ReparentShard', '-force', 'test_keyspace/C0-', shard_3_master.tablet_alias], auto_log=True) utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True) utils.check_srv_keyspace('test_nj', 'test_keyspace', 'Partitions(master): -80 80-\n' + 'Partitions(rdonly): -80 80-\n' + 'Partitions(replica): -80 80-\n' + 'TabletTypes: master,rdonly,replica', keyspace_id_type=keyspace_id_type) # take the snapshot for the split utils.run_vtctl(['MultiSnapshot', '--spec=80-C0-', '--exclude_tables=unrelated', shard_1_slave1.tablet_alias], auto_log=True) # the snapshot_copy hook will copy the snapshot files to # VTDATAROOT/tmp/... as a test. We want to use these for one half, # but not for the other, so we test both scenarios. os.unlink(os.path.join(environment.tmproot, "snapshot-from-%s-for-%s.tar" % (shard_1_slave1.tablet_alias, "80-C0"))) # wait for tablet's binlog server service to be enabled after snapshot shard_1_slave1.wait_for_binlog_server_state("Enabled") # perform the restores: first one from source tablet. We removed the # storage backup, so it's coming from the tablet itself. # we also delay starting the binlog player, then enable it. utils.run_vtctl(['ShardMultiRestore', '-strategy=populateBlpCheckpoint,dontStartBinlogPlayer', 'test_keyspace/80-C0', shard_1_slave1.tablet_alias], auto_log=True) timeout = 10 while True: shard_2_master_status = shard_2_master.get_status() if not "not starting because flag &#39;DontStart&#39; is set" in shard_2_master_status: timeout = utils.wait_step('shard 2 master has not failed starting yet', timeout) continue logging.info("shard 2 master is waiting on flag removal, good") break qr = utils.run_vtctl_json(['ExecuteFetch', shard_2_master.tablet_alias, 'update _vt.blp_checkpoint set flags="" where source_shard_uid=0']) self.assertEqual(qr['RowsAffected'], 1) timeout = 10 while True: shard_2_master_status = shard_2_master.get_status() if "not starting because flag &#39;DontStart&#39; is set" in shard_2_master_status: timeout = utils.wait_step('shard 2 master has not started replication yet', timeout) continue logging.info("shard 2 master has started replication, good") break # second restore from storage: to be sure, we stop vttablet, and restart # it afterwards shard_1_slave1.kill_vttablet() utils.run_vtctl(['ShardMultiRestore', '-strategy=populateBlpCheckpoint', 'test_keyspace/C0-', shard_1_slave1.tablet_alias], auto_log=True) shard_1_slave1.start_vttablet(wait_for_state=None) shard_1_slave1.wait_for_binlog_server_state("Enabled") # check the startup values are in the right place self._check_startup_values() # check the schema too utils.run_vtctl(['ValidateSchemaKeyspace', '--exclude_tables=unrelated', 'test_keyspace'], auto_log=True) # check the binlog players are running and exporting vars shard_2_master.wait_for_binlog_player_count(1) shard_3_master.wait_for_binlog_player_count(1) self._check_binlog_player_vars(shard_2_master) self._check_binlog_player_vars(shard_3_master) # check that binlog server exported the stats vars self._check_binlog_server_vars(shard_1_slave1) # testing filtered replication: insert a bunch of data on shard 1, # check we get most of it after a few seconds, wait for binlog server # timeout, check we get all of it. logging.debug("Inserting lots of data on source shard") self._insert_lots(1000) logging.debug("Checking 80 percent of data is sent quickly") self._check_lots_timeout(1000, 80, 5) logging.debug("Checking all data goes through eventually") self._check_lots_timeout(1000, 100, 20) logging.debug("Checking no data was sent the wrong way") self._check_lots_not_present(1000) self._check_binlog_player_vars(shard_2_master, seconds_behind_master_max=30) self._check_binlog_player_vars(shard_3_master, seconds_behind_master_max=30) # use the vtworker checker to compare the data logging.debug("Running vtworker SplitDiff") utils.run_vtworker(['-cell', 'test_nj', 'SplitDiff', 'test_keyspace/C0-'], auto_log=True) utils.run_vtctl(['ChangeSlaveType', shard_1_rdonly.tablet_alias, 'rdonly'], auto_log=True) utils.run_vtctl(['ChangeSlaveType', shard_3_rdonly.tablet_alias, 'rdonly'], auto_log=True) utils.pause("Good time to test vtworker for diffs") # get status for a destination master tablet, make sure we have it all shard_2_master_status = shard_2_master.get_status() self.assertIn('Binlog player state: Running', shard_2_master_status) self.assertIn('<td><b>All</b>: 6000<br><b>Query</b>: 4000<br><b>Transaction</b>: 2000<br></td>', shard_2_master_status) self.assertIn('</html>', shard_2_master_status) # start a thread to insert data into shard_1 in the background # with current time, and monitor the delay insert_thread_1 = InsertThread(shard_1_master, "insert_low", 10000, 0x9000000000000000) insert_thread_2 = InsertThread(shard_1_master, "insert_high", 10001, 0xD000000000000000) monitor_thread_1 = MonitorLagThread(shard_2_replica2, "insert_low") monitor_thread_2 = MonitorLagThread(shard_3_replica, "insert_high") # tests a failover switching serving to a different replica utils.run_vtctl(['ChangeSlaveType', shard_1_slave2.tablet_alias, 'replica']) utils.run_vtctl(['ChangeSlaveType', shard_1_slave1.tablet_alias, 'spare']) shard_1_slave2.wait_for_vttablet_state('SERVING') shard_1_slave1.wait_for_vttablet_state('NOT_SERVING') # test data goes through again logging.debug("Inserting lots of data on source shard") self._insert_lots(1000, base=1000) logging.debug("Checking 80 percent of data was sent quickly") self._check_lots_timeout(1000, 80, 5, base=1000) # check we can't migrate the master just yet utils.run_vtctl(['MigrateServedTypes', 'test_keyspace/80-', 'master'], expect_fail=True) # now serve rdonly from the split shards utils.run_vtctl(['MigrateServedTypes', 'test_keyspace/80-', 'rdonly'], auto_log=True) utils.check_srv_keyspace('test_nj', 'test_keyspace', 'Partitions(master): -80 80-\n' + 'Partitions(rdonly): -80 80-C0 C0-\n' + 'Partitions(replica): -80 80-\n' + 'TabletTypes: master,rdonly,replica', keyspace_id_type=keyspace_id_type) # then serve replica from the split shards utils.run_vtctl(['MigrateServedTypes', 'test_keyspace/80-', 'replica'], auto_log=True) utils.check_srv_keyspace('test_nj', 'test_keyspace', 'Partitions(master): -80 80-\n' + 'Partitions(rdonly): -80 80-C0 C0-\n' + 'Partitions(replica): -80 80-C0 C0-\n' + 'TabletTypes: master,rdonly,replica', keyspace_id_type=keyspace_id_type) # move replica back and forth utils.run_vtctl(['MigrateServedTypes', '-reverse', 'test_keyspace/80-', 'replica'], auto_log=True) utils.check_srv_keyspace('test_nj', 'test_keyspace', 'Partitions(master): -80 80-\n' + 'Partitions(rdonly): -80 80-C0 C0-\n' + 'Partitions(replica): -80 80-\n' + 'TabletTypes: master,rdonly,replica', keyspace_id_type=keyspace_id_type) utils.run_vtctl(['MigrateServedTypes', 'test_keyspace/80-', 'replica'], auto_log=True) utils.check_srv_keyspace('test_nj', 'test_keyspace', 'Partitions(master): -80 80-\n' + 'Partitions(rdonly): -80 80-C0 C0-\n' + 'Partitions(replica): -80 80-C0 C0-\n' + 'TabletTypes: master,rdonly,replica', keyspace_id_type=keyspace_id_type) # reparent shard_2 to shard_2_replica1, then insert more data and # see it flow through still utils.run_vtctl(['ReparentShard', 'test_keyspace/80-C0', shard_2_replica1.tablet_alias]) logging.debug("Inserting lots of data on source shard after reparenting") self._insert_lots(3000, base=2000) logging.debug("Checking 80 percent of data was sent fairly quickly") self._check_lots_timeout(3000, 80, 10, base=2000) # use the vtworker checker to compare the data again logging.debug("Running vtworker SplitDiff") utils.run_vtworker(['-cell', 'test_nj', 'SplitDiff', 'test_keyspace/C0-'], auto_log=True) utils.run_vtctl(['ChangeSlaveType', shard_1_rdonly.tablet_alias, 'rdonly'], auto_log=True) utils.run_vtctl(['ChangeSlaveType', shard_3_rdonly.tablet_alias, 'rdonly'], auto_log=True) # going to migrate the master now, check the delays monitor_thread_1.done = True monitor_thread_2.done = True insert_thread_1.done = True insert_thread_2.done = True logging.debug("DELAY 1: %s max_lag=%u avg_lag=%u", monitor_thread_1.object_name, monitor_thread_1.max_lag, monitor_thread_1.lag_sum / monitor_thread_1.sample_count) logging.debug("DELAY 2: %s max_lag=%u avg_lag=%u", monitor_thread_2.object_name, monitor_thread_2.max_lag, monitor_thread_2.lag_sum / monitor_thread_2.sample_count) # then serve master from the split shards utils.run_vtctl(['MigrateServedTypes', 'test_keyspace/80-', 'master'], auto_log=True) utils.check_srv_keyspace('test_nj', 'test_keyspace', 'Partitions(master): -80 80-C0 C0-\n' + 'Partitions(rdonly): -80 80-C0 C0-\n' + 'Partitions(replica): -80 80-C0 C0-\n' + 'TabletTypes: master,rdonly,replica', keyspace_id_type=keyspace_id_type) # check the binlog players are gone now shard_2_master.wait_for_binlog_player_count(0) shard_3_master.wait_for_binlog_player_count(0) # get status for a destination master tablet, make sure it's good shard_2_master_status = shard_2_master.get_status() self.assertIn('No binlog player is running', shard_2_master_status) self.assertIn('</html>', shard_2_master_status) # scrap the original tablets in the original shard for t in [shard_1_master, shard_1_slave1, shard_1_slave2, shard_1_rdonly]: utils.run_vtctl(['ScrapTablet', t.tablet_alias], auto_log=True) tablet.kill_tablets([shard_1_master, shard_1_slave1, shard_1_slave2, shard_1_rdonly]) for t in [shard_1_master, shard_1_slave1, shard_1_slave2, shard_1_rdonly]: utils.run_vtctl(['DeleteTablet', t.tablet_alias], auto_log=True) # rebuild the serving graph, all mentions of the old shards shoud be gone utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True) # test RemoveShardCell utils.run_vtctl(['RemoveShardCell', 'test_keyspace/-80', 'test_nj'], auto_log=True, expect_fail=True) utils.run_vtctl(['RemoveShardCell', 'test_keyspace/80-', 'test_nj'], auto_log=True) shard = utils.run_vtctl_json(['GetShard', 'test_keyspace/80-']) if shard['Cells']: self.fail("Non-empty Cells record for shard: %s" % str(shard)) # delete the original shard utils.run_vtctl(['DeleteShard', 'test_keyspace/80-'], auto_log=True) # kill everything tablet.kill_tablets([shard_0_master, shard_0_replica, shard_2_master, shard_2_replica1, shard_2_replica2, shard_3_master, shard_3_replica, shard_3_rdonly]) if __name__ == '__main__': utils.main()
{ "content_hash": "393619bbb8b1ec425e726c84410bae27", "timestamp": "", "source": "github", "line_count": 711, "max_line_length": 185, "avg_line_length": 43.479606188466946, "alnum_prop": 0.6087856634534515, "repo_name": "apmichaud/vitess-apm", "id": "a6a4a27c338d72571b068f6989b675d110824e16", "size": "30914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/resharding.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "39092" }, { "name": "Go", "bytes": "2605337" }, { "name": "Java", "bytes": "100152" }, { "name": "Python", "bytes": "604118" }, { "name": "Shell", "bytes": "11552" } ], "symlink_target": "" }
import os import platform import subprocess _ON_WINDOWS = (platform.system().lower() == 'windows') def _determine_number_of_cpus(): """ Number of virtual or physical CPUs on this system, i.e. user/real as output by time(1) when called with an optimally scaling userspace-only program """ # Python 2.6+ try: import multiprocessing return multiprocessing.cpu_count() except (ImportError, NotImplementedError): pass # POSIX try: res = int(os.sysconf('SC_NPROCESSORS_ONLN')) if res > 0: return res except (AttributeError, ValueError): pass # Windows try: res = int(os.environ['NUMBER_OF_PROCESSORS']) if res > 0: return res except (KeyError, ValueError): pass # jython try: from java.lang import Runtime runtime = Runtime.getRuntime() res = runtime.availableProcessors() if res > 0: return res except ImportError: pass # BSD try: sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'], stdout=subprocess.PIPE) sc_stdout = sysctl.communicate()[0] res = int(sc_stdout) if res > 0: return res except (OSError, ValueError): pass # Linux try: res = open('/proc/cpuinfo').read().count('processor\t:') if res > 0: return res except IOError: pass # Solaris try: pseudo_devices = os.listdir('/devices/pseudo/') import re expr = re.compile('^cpuid@[0-9]+$') res = 0 for pd in pseudo_devices: if expr.match(pd) is not None: res += 1 if res > 0: return res except OSError: pass # Other UNIXes (heuristic) try: try: dmesg = open('/var/run/dmesg.boot').read() except IOError: dmesg_process = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE) dmesg = dmesg_process.communicate()[0] res = 0 while '\ncpu' + str(res) + ':' in dmesg: res += 1 if res > 0: return res except OSError: pass raise Exception('Can not determine number of CPUs on this system') # set up some global variables NUMBER_OF_PROCESSORS = _determine_number_of_cpus() MAKE_COMMAND = ['make', '-j', str(NUMBER_OF_PROCESSORS)] CLEAN_COMMAND = ['make', 'clean'] MAKE_TARGET = 'Unix Makefiles' if _ON_WINDOWS: MAKE_COMMAND = ['jom'] CLEAN_COMMAND = ['jom', 'clean'] MAKE_TARGET = 'NMake Makefiles'
{ "content_hash": "d7931ee00eadcb25f33eb8fc7090afd1", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 86, "avg_line_length": 23.114035087719298, "alnum_prop": 0.5555977229601518, "repo_name": "koborit/SpaceSwitcherSample", "id": "c6d5323bdf59bcb2054805a716f2c6d062c9952e", "size": "2635", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Ecosystem/ecosystem/settings.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "887" }, { "name": "Python", "bytes": "20750" }, { "name": "Shell", "bytes": "837" } ], "symlink_target": "" }
"""Python Dataflow error classes.""" # pytype: skip-file from __future__ import absolute_import class BeamError(Exception): """Base class for all Beam errors.""" class PipelineError(BeamError): """An error in the pipeline object (e.g. a PValue not linked to it).""" class PValueError(BeamError): """An error related to a PValue object (e.g. value is not computed).""" class RunnerError(BeamError): """An error related to a Runner object (e.g. cannot find a runner to run).""" class RuntimeValueProviderError(RuntimeError): """An error related to a ValueProvider object raised during runtime.""" class SideInputError(BeamError): """An error related to a side input to a parallel Do operation.""" class TransformError(BeamError): """An error related to a PTransform object."""
{ "content_hash": "e5c67ce737c4214bc138b8b6411ba0ef", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 79, "avg_line_length": 24.393939393939394, "alnum_prop": 0.7192546583850932, "repo_name": "iemejia/incubator-beam", "id": "3165842e481a807c04c0bc0f56bad5b979e04f23", "size": "1590", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdks/python/apache_beam/error.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "22216" }, { "name": "Java", "bytes": "9687045" }, { "name": "Protocol Buffer", "bytes": "1407" }, { "name": "Shell", "bytes": "10104" } ], "symlink_target": "" }
import unittest from pyrep.const import ObjectType from tests.core import TestCore from pyrep.objects.shape import Shape from pyrep.objects.dummy import Dummy from pyrep.objects.object import Object from pyrep.objects.vision_sensor import VisionSensor import numpy as np class TestObjects(TestCore): def setUp(self): super().setUp() self.dynamic_cube = Shape('dynamic_cube') self.cubes_under_dummy = Dummy('cubes_under_dummy') self.cube0 = Shape('cube0') self.dummy = Dummy('dummy') self.simple_model = Shape('simple_model') def test_get_object_type(self): self.assertEqual(Object.get_object_type('dynamic_cube'), ObjectType.SHAPE) self.assertEqual(Object.get_object_type('dummy'), ObjectType.DUMMY) def test_get_object_name(self): self.assertEqual(Object.get_object_name('dynamic_cube'), 'dynamic_cube') self.assertEqual( Object.get_object_name(self.dynamic_cube.get_handle()), 'dynamic_cube') def test_get_object(self): self.assertEqual(Object.get_object('dynamic_cube'), self.dynamic_cube) self.assertEqual(Object.get_object('dummy'), self.dummy) self.assertEqual(Object.get_object(self.dynamic_cube.get_handle()), self.dynamic_cube) self.assertEqual(Object.get_object(self.dummy.get_handle()), self.dummy) def test_equality(self): cube2 = Shape('dynamic_cube') self.assertEqual(self.dynamic_cube, cube2) def test_get_handle(self): self.assertGreater(self.dynamic_cube.get_handle(), 0) def test_get_type(self): self.assertEqual(self.dynamic_cube.get_type(), ObjectType.SHAPE) def test_still_exists(self): self.assertTrue(self.dynamic_cube.still_exists()) self.dynamic_cube.remove() self.assertFalse(self.dynamic_cube.still_exists()) def test_object_exists(self): yes = Object.exists('dynamic_cube') no = Object.exists('dynamic_cubeee') self.assertTrue(yes) self.assertFalse(no) def test_get_set_name(self): self.dynamic_cube.set_name('test1') self.assertEqual(self.dynamic_cube.get_name(), 'test1') def test_get_set_position(self): position = self.cube0.get_position() self.assertIsInstance(position, np.ndarray) self.assertEqual(position.shape, (3,)) self.cube0.set_position([0.1, 0.1, 0.1], self.cubes_under_dummy) self.assertTrue(np.allclose( self.cube0.get_position(self.cubes_under_dummy), [0.1, 0.1, 0.1])) self.cube0.set_position([0.2, 0.2, 0.2]) self.assertTrue(np.allclose(self.cube0.get_position(), [0.2, 0.2, 0.2])) def test_get_set_orientation(self): orientation = self.cube0.get_orientation() self.assertIsInstance(orientation, np.ndarray) self.assertEqual(orientation.shape, (3,)) self.cube0.set_orientation([0.0, 0.0, 0.2], self.cubes_under_dummy) self.assertTrue(np.allclose( self.cube0.get_orientation(self.cubes_under_dummy), [0.0, 0.0, 0.2])) self.cube0.set_orientation([0.0, 0.0, 0.3]) self.assertTrue(np.allclose( self.cube0.get_orientation(), [0.0, 0.0, 0.3])) def test_get_set_quaternion(self): quaternion = self.cube0.get_quaternion() self.assertIsInstance(quaternion, np.ndarray) self.assertEqual(quaternion.shape, (4,)) # x, y, z, w self.cube0.set_quaternion([1., 0., 0., 0.], self.cubes_under_dummy) self.assertTrue(np.allclose( self.cube0.get_quaternion(self.cubes_under_dummy), [1., 0., 0., 0.])) self.cube0.set_quaternion([np.sqrt(0.5), 0, 0., np.sqrt(0.5)]) self.assertTrue(np.allclose( self.cube0.get_quaternion(), [np.sqrt(0.5), 0, 0., np.sqrt(0.5)])) def test_get_velocity(self): linear_vel, angular_vel = self.cube0.get_velocity() self.assertIsInstance(linear_vel, np.ndarray) self.assertEqual(linear_vel.shape, (3,)) self.assertIsInstance(angular_vel, np.ndarray) self.assertEqual(angular_vel.shape, (3,)) def test_get_set_parent(self): self.dynamic_cube.set_parent(self.dummy) parent = self.dynamic_cube.get_parent() self.assertEqual(parent, self.dummy) def test_get_set_parent_not_in_place(self): init_pos = self.dynamic_cube.get_position() self.dynamic_cube.set_parent(self.dummy, keep_in_place=False) parent = self.dynamic_cube.get_parent() self.assertEqual(parent, self.dummy) self.assertFalse(np.allclose( init_pos, self.dynamic_cube.get_position())) def test_get_parent_when_orphan(self): parent = self.dummy.get_parent() self.assertIsNone(parent) def test_get_set_matrix(self): m = self.dynamic_cube.get_matrix() self.assertEqual(m.shape, (4, 4)) self.simple_model.set_matrix(m) self.assertListEqual(self.simple_model.get_matrix().tolist(), m.tolist()) def test_get_set_collidable(self): self.dynamic_cube.set_collidable(False) self.assertFalse(self.dynamic_cube.is_collidable()) self.dynamic_cube.set_collidable(True) self.assertTrue(self.dynamic_cube.is_collidable()) def test_get_contact(self): contact = self.dynamic_cube.get_contact(self.simple_model, get_contact_normal=True) self.assertTrue(len(contact) == 0) for _ in range(20): self.pyrep.step() c1 = Shape('colliding_cube1') c0 = Shape('colliding_cube0') contact = c1.get_contact(None, True) self.assertTrue(len(contact) > 0) contact = c0.get_contact(None, True) self.assertTrue(len(contact) > 0) def test_get_set_measurable(self): self.dynamic_cube.set_measurable(False) self.assertFalse(self.dynamic_cube.is_measurable()) self.dynamic_cube.set_measurable(True) self.assertTrue(self.dynamic_cube.is_measurable()) def test_get_set_detectable(self): self.dynamic_cube.set_detectable(False) self.assertFalse(self.dynamic_cube.is_detectable()) self.dynamic_cube.set_detectable(True) self.assertTrue(self.dynamic_cube.is_detectable()) def test_get_set_renderable(self): self.dynamic_cube.set_renderable(False) self.assertFalse(self.dynamic_cube.is_renderable()) self.dynamic_cube.set_renderable(True) self.assertTrue(self.dynamic_cube.is_renderable()) def test_is_model(self): self.assertFalse(self.dynamic_cube.is_model()) self.assertTrue(self.simple_model.is_model()) def test_set_model(self): self.simple_model.set_model(False) self.dynamic_cube.set_model(True) self.assertFalse(self.simple_model.is_model()) self.assertTrue(self.dynamic_cube.is_model()) def test_remove(self): self.dynamic_cube.remove() self.simple_model.remove() self.assertFalse(self.dynamic_cube.still_exists()) self.assertFalse(self.simple_model.still_exists()) self.assertFalse(Object.exists('dynamic_cube')) self.assertFalse(Object.exists('simple_model')) def test_dynamic_object(self): # Can't really test this. So lets just make sure it doesn't error self.dynamic_cube.reset_dynamic_object() def test_get_bounding_box(self): bb = self.dynamic_cube.get_bounding_box() self.assertTrue(np.allclose(bb, [-0.05, 0.05] * 3)) def test_get_objects_in_tree(self): dummys = [Dummy('nested_dummy%d' % i) for i in range(3)] objects = dummys[0].get_objects_in_tree( exclude_base=False, first_generation_only=False) self.assertListEqual(objects, dummys) for obj in objects: self.assertIs(type(obj), Dummy) self.assertListEqual( dummys[0].get_objects_in_tree( exclude_base=True, first_generation_only=False), dummys[1:]) self.assertListEqual( dummys[0].get_objects_in_tree( exclude_base=False,first_generation_only=True), dummys[:-1]) def test_get_extention_string(self): self.assertEqual(self.dynamic_cube.get_extension_string(), 'test') def test_get_configuration_tree(self): config = self.dynamic_cube.get_configuration_tree() self.assertIsNotNone(config) def test_rotate(self): self.dynamic_cube.rotate([0.02, 0.04, 0.06]) self.assertTrue(np.allclose( self.dynamic_cube.get_orientation(), [0.02, 0.04, 0.06])) def test_get_set_model_collidable(self): self.simple_model.set_model_collidable(False) self.assertFalse(self.simple_model.is_model_collidable()) self.simple_model.set_model_collidable(True) self.assertTrue(self.simple_model.is_model_collidable()) def test_get_set_model_measurable(self): self.simple_model.set_model_measurable(False) self.assertFalse(self.simple_model.is_model_measurable()) self.simple_model.set_model_measurable(True) self.assertTrue(self.simple_model.is_model_measurable()) def test_get_set_model_detectable(self): self.simple_model.set_model_detectable(False) self.assertFalse(self.simple_model.is_model_detectable()) self.simple_model.set_model_detectable(True) self.assertTrue(self.simple_model.is_model_detectable()) def test_get_set_model_renderable(self): self.simple_model.set_model_renderable(False) self.assertFalse(self.simple_model.is_model_renderable()) self.simple_model.set_model_renderable(True) self.assertTrue(self.simple_model.is_model_renderable()) def test_get_set_model_dynamic(self): self.simple_model.set_model_dynamic(False) self.assertFalse(self.simple_model.is_model_dynamic()) self.simple_model.set_model_dynamic(True) self.assertTrue(self.simple_model.is_model_dynamic()) def test_get_set_model_respondable(self): self.simple_model.set_model_respondable(False) self.assertFalse(self.simple_model.is_model_respondable()) self.simple_model.set_model_respondable(True) self.assertTrue(self.simple_model.is_model_respondable()) def test_check_collision(self): c1 = Shape('colliding_cube0') c2 = Shape('colliding_cube1') self.assertTrue(c1.check_collision(c2)) def test_check_collision_all(self): c1 = Shape('colliding_cube0') self.assertTrue(c1.check_collision(None)) def test_copy(self): cube1 = self.cube0.copy() self.assertGreater(cube1.get_handle(), 0) self.assertIsInstance(cube1, Shape) self.assertNotEqual(self.cube0, cube1) def test_check_distance(self): dist = self.dummy.check_distance(self.cube0) self.assertAlmostEqual(dist, 1.4629, places=3) def test_set_get_bullet_friction(self): self.dynamic_cube.set_bullet_friction(0.7) friction = self.dynamic_cube.get_bullet_friction() self.assertAlmostEqual(friction, 0.7, places=1) def test_set_get_explicit_handling(self): cam = VisionSensor.create((640, 480)) flag_orig = cam.get_explicit_handling() cam.set_explicit_handling(value=1) flag = cam.get_explicit_handling() self.assertEqual(flag, 1) cam.set_explicit_handling(value=0) flag = cam.get_explicit_handling() self.assertEqual(flag, 0) cam.set_explicit_handling(flag_orig) cam.remove() if __name__ == '__main__': unittest.main()
{ "content_hash": "84fa768e24a1de726d74807a6c49bfec", "timestamp": "", "source": "github", "line_count": 307, "max_line_length": 91, "avg_line_length": 38.63192182410423, "alnum_prop": 0.6398819561551433, "repo_name": "stepjam/PyRep", "id": "82ee444a4ad8bd2d9711366ed6eeaa100c4adc47", "size": "11860", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_objects.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "56307" }, { "name": "Lua", "bytes": "16854" }, { "name": "Python", "bytes": "428818" } ], "symlink_target": "" }
from pygw.config import geowave_pkg from ..statistic import FieldStatistic from ..statistic_type import FieldStatisticType from ...base import GeoWaveObject from ...base.java_transformer import JavaTransformer from ...base.type_conversions import PrimitiveDoubleArrayType, PrimitiveLongArrayType class FixedBinNumericHistogramStatistic(FieldStatistic): """ Fixed number of bins for a histogram. Unless configured, the range will expand dynamically, redistributing the data as necessary into the wider bins. The advantage of constraining the range of the statistic is to ignore values outside the range, such as erroneous values. Erroneous values force extremes in the histogram. For example, if the expected range of values falls between 0 and 1 and a value of 10000 occurs, then a single bin contains the entire population between 0 and 1, a single bin represents the single value of 10000. If there are extremes in the data, then use NumericHistogramStatistic instead. """ STATS_TYPE = FieldStatisticType( geowave_pkg.core.store.statistics.field.FixedBinNumericHistogramStatistic.STATS_TYPE) def __init__(self, type_name=None, field_name=None, bins=1024, min_value=None, max_value=None, java_ref=None): if java_ref is None: if type_name is None and field_name is None: java_ref = geowave_pkg.core.store.statistics.field.FixedBinNumericHistogramStatistic() else: java_ref = geowave_pkg.core.store.statistics.field.FixedBinNumericHistogramStatistic( type_name, field_name, bins, float(min_value), float(max_value)) super().__init__(java_ref, FixedBinNumericHistogramTransformer()) def set_num_bins(self, num_bins): self._java_ref.setNumBins(num_bins) def get_num_bins(self): return self._java_ref.getNumBins() def set_min_value(self, min_value): self._java_ref.setMinValue(float(min_value)) def get_min_value(self): return self._java_ref.getMinValue() def set_max_value(self, max_value): self._java_ref.setMaxValue(float(max_value)) def get_max_value(self): return self._java_ref.getMaxValue() class FixedBinNumericHistogramTransformer(JavaTransformer): def transform(self, j_object): return FixedBinNumericHistogram(j_object) class FixedBinNumericHistogram(GeoWaveObject): def bin_quantiles(self, bins): return PrimitiveDoubleArrayType().from_java(self._java_ref.quantile(int(bins))) def quantile(self, percentage): return self._java_ref.quantile(float(percentage)) def cdf(self, val): return self._java_ref.cdf(float(val)) def sum(self, val, inclusive=True): return self._java_ref.sum(float(val), inclusive) def percent_population_over_range(self, start, stop): return self._java_ref.percentPopulationOverRange(float(start), float(stop)) def total_sample_size(self): return self._java_ref.totalSampleSize() def count(self, bins): return PrimitiveLongArrayType().from_java(self._java_ref.count(bins)) def get_total_count(self): return self._java_ref.getTotalCount() def get_num_bins(self): return self._java_ref.getNumBins() def get_min_value(self): return self._java_ref.getMinValue() def get_max_value(self): return self._java_ref.getMaxValue()
{ "content_hash": "f41cf813d83e0337cd8a03142b3fb016", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 117, "avg_line_length": 39.02272727272727, "alnum_prop": 0.7052999417588818, "repo_name": "ngageoint/geowave", "id": "0e5ac059e7647d2e46592a3be0e32dc3affbd806", "size": "3953", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/src/main/python/pygw/statistics/field/fixed_bin_numeric_histogram_statistic.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "5073" }, { "name": "CMake", "bytes": "2032" }, { "name": "FreeMarker", "bytes": "2879" }, { "name": "Gnuplot", "bytes": "57750" }, { "name": "Groovy", "bytes": "1323" }, { "name": "HTML", "bytes": "1903" }, { "name": "Java", "bytes": "7103026" }, { "name": "Protocol Buffer", "bytes": "1525" }, { "name": "Puppet", "bytes": "4039" }, { "name": "Scala", "bytes": "26507" }, { "name": "Scheme", "bytes": "20491" }, { "name": "Shell", "bytes": "68381" } ], "symlink_target": "" }
''' An "Always Approved" eauth interface to test against, not intended for production use ''' def auth(username, password): ''' Authenticate! ''' return True
{ "content_hash": "9cb48f610c99856b1d7776dc7cc45f90", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 70, "avg_line_length": 16, "alnum_prop": 0.6534090909090909, "repo_name": "MadeiraCloud/salt", "id": "592b96beff434291e849c79b6cba3eafa24e9182", "size": "200", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sources/salt/auth/auto.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "10058" }, { "name": "Makefile", "bytes": "1815" }, { "name": "Python", "bytes": "4530204" }, { "name": "Shell", "bytes": "169676" } ], "symlink_target": "" }
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from aspen.simplates import pagination #SPLIT TESTS ############ def check_page_content(raw, comp_pages): ''' Pattern function. Splits a raw, then checks the number of pages generated, and that each page's content matches the contents of comp_pages. Interpretation of comp_pages is as follows: comp_pages is am item or a list of items. Each item is a string, tuple, or None. If it is a string, the page's content is matched; if it is a tuple, the page's content and/or header are checked. If any of the items are None, that comparison is ignored. ''' #Convert to single-element list if not isinstance(comp_pages, list): comp_pages = [comp_pages] #Convert all non-tuples to tuples comp_pages = [item if isinstance(item, tuple) else (item, None) for item in comp_pages] #execute resources.split pages = list(pagination.split(raw)) assert len(pages) == len(comp_pages) for generated_page, (content, header) in zip(pages, comp_pages): if content is not None: assert generated_page.content == content, repr(generated_page.content) + " should be " + repr(content) if header is not None: assert generated_page.header == header, repr(generated_page.header) + " should be " + repr(header) def test_empty_content(): check_page_content('', '') def test_no_page_breaks(): content = 'this is some content\nwith newlines' check_page_content(content, content) def test_only_page_break(): check_page_content('[---]\n', ['', '']) def test_basic_page_break(): check_page_content('Page 1\n[---]\nPage 2\n', ['Page 1\n', 'Page 2\n']) def test_two_page_breaks(): raw = '''\ 1 [---] 2 [---] 3 ''' check_page_content(raw, ['1\n', '2\n', '3\n']) def test_no_inline_page_break(): content = 'this is an[---]inline page break' check_page_content(content, [None]) def test_headers(): raw = '''\ page1 [---] header2 page2 [---] header3 page3 ''' pages = [ ('page1\n', ''), ('page2\n', 'header2'), ('page3\n', 'header3')] check_page_content(raw, pages) #ESCAPE TESTS ############# def check_escape(content_to_escape, expected): actual = pagination.escape(content_to_escape) assert actual == expected, repr(actual) + " should be " + repr(expected) def test_basic_escape_1(): check_escape('\[---]', '[---]') def test_basic_escape_2(): check_escape('\\\\\\[---]', '\\\[---]') def test_inline_sep_ignored_1(): check_escape('inline[---]break', 'inline[---]break') def test_inline_sep_ignored_2(): check_escape('inline\\\[---]break', 'inline\\\[---]break') def test_escape_preserves_extra_content(): check_escape('\\\\[---] content ', '\[---] content ') def test_multiple_escapes(): to_escape = '1\n\[---]\n2\n\[---]' result = '1\n[---]\n2\n[---]' check_escape(to_escape, result) def test_long_break(): check_escape('\[----------]', '[----------]') def test_escaped_pages(): raw = '''\ 1 [---] 2 \[---] 3 ''' check_page_content(raw, ['1\n', '2\n\\[---]\n3\n']) #SPECLINE TESTS ############### def check_specline(header, media_type, renderer): assert pagination.parse_specline(header) == (media_type, renderer) def test_empty_header_1(): check_specline('', '', '') def test_empty_header_2(): check_specline(' ', '', '') def test_media_only(): check_specline('text/plain', 'text/plain', '') def test_renderer_only(): check_specline('via renderer', '', 'renderer') def test_basic_specline(): check_specline('media/type via renderer', 'media/type', 'renderer') def test_funky_whitespace(): check_specline( ' media/type via renderer ' , 'media/type' , 'renderer' ) def test_whitespace_in_fields(): check_specline( 'media type via content renderer' , 'media type' , 'content renderer' ) def test_extra_funky_whitespace(): header = ' this is a type via some sort of renderer ' media_type = 'this is a type' renderer = 'some sort of renderer' check_specline(header, media_type, renderer)
{ "content_hash": "30dd212810076fcaa27246549be2c45a", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 114, "avg_line_length": 27.44375, "alnum_prop": 0.5953085857435664, "repo_name": "jaraco/aspen", "id": "e5c9e3c5da4e0f2a0f26c62dc46c9a167f7782ed", "size": "4391", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_resources_generics.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "20" }, { "name": "Makefile", "bytes": "231" }, { "name": "Python", "bytes": "388419" }, { "name": "Shell", "bytes": "1328" } ], "symlink_target": "" }
"""Tests for Santa log parser.""" from __future__ import unicode_literals import unittest from plaso.parsers import santa from tests.parsers import test_lib class SantaUnitTest(test_lib.ParserTestCase): """Tests for Santa log parser.""" def testParse(self): """Tests the Parse function.""" parser = santa.SantaParser() storage_writer = self._ParseFile(['santa.log'], parser) # Test file contains 194 lines # - 3 lines should be skipped in the results. # - 17 new events should be added from existing lines. self.assertEqual(storage_writer.number_of_warnings, 0) self.assertEqual(storage_writer.number_of_events, 208) # The order in which parser generates events is nondeterministic hence # we sort the events. events = list(storage_writer.GetSortedEvents()) # Execution event with quarantine url. event = events[46] self.CheckTimestamp(event.timestamp, '2018-08-19 03:17:55.765000') event_data = self._GetEventDataOfEvent(storage_writer, event) self.assertEqual( event_data.quarantine_url, 'https://endpoint920510.azureedge.net/s4l/s4l/download/mac/' 'Skype-8.28.0.41.dmg') expected_message = ( 'Santa ALLOW process: /Applications/Skype.app/Contents/MacOS/Skype hash' ': 78b43a13b5b608fe1a5a590f5f3ff112ff16ece7befc29fc84347125f6b9ca78') expected_short_message = ( 'ALLOW process: /Applications/Skype.app/Contents/MacOS/Skype') self._TestGetMessageStrings( event_data, expected_message, expected_short_message) # File operation event log event = events[159] self.CheckTimestamp(event.timestamp, '2018-08-19 04:02:47.911000') event_data = self._GetEventDataOfEvent(storage_writer, event) # Test common fields in file operation event. self.assertEqual(event_data.action, 'WRITE') self.assertEqual(event_data.file_path, '/Users/qwerty/newfile') self.assertEqual(event_data.pid, '303') self.assertEqual(event_data.ppid, '1') self.assertEqual(event_data.process, 'Finder') self.assertEqual( event_data.process_path, '/System/Library/CoreServices/Finder.app/Contents/MacOS/Finder') self.assertEqual(event_data.uid, '501') self.assertEqual(event_data.user, 'qwerty') self.assertEqual(event_data.gid, '20') self.assertEqual(event_data.group, 'staff') expected_message = ( 'Santa WRITE event /Users/qwerty/newfile by process: ' '/System/Library/CoreServices/Finder.app/Contents/MacOS/Finder') expected_short_message = 'File WRITE on: /Users/qwerty/newfile' self._TestGetMessageStrings( event_data, expected_message, expected_short_message) # Disk mounts event log. event = events[38] self.CheckTimestamp(event.timestamp, '2018-08-19 03:17:29.036000') # Test common fields in file Disk mounts event. event_data = self._GetEventDataOfEvent(storage_writer, event) self.assertEqual(event_data.action, 'DISKAPPEAR') self.assertEqual(event_data.mount, '') self.assertEqual(event_data.volume, 'Skype') self.assertEqual(event_data.bsd_name, 'disk2s1') self.assertEqual(event_data.fs, 'hfs') self.assertEqual(event_data.model, 'Apple Disk Image') self.assertEqual(event_data.serial, '') self.assertEqual(event_data.bus, 'Virtual Interface') self.assertEqual( event_data.dmg_path, '/Users/qwerty/Downloads/Skype-8.28.0.41.dmg') self.assertEqual(event_data.appearance, '2018-08-19T03:17:28.982Z') expected_message = ( 'Santa DISKAPPEAR for (/Users/qwerty/Downloads/Skype-8.28.0.41.dmg)') expected_short_message = 'DISKAPPEAR Skype' self._TestGetMessageStrings( event_data, expected_message, expected_short_message) # Test Disk event created from appearance timestamp. event = events[35] self.CheckTimestamp(event.timestamp, '2018-08-19 03:17:28.982000') self.assertEqual(event.timestamp_desc, 'First Connection Time') if __name__ == '__main__': unittest.main()
{ "content_hash": "8f577b33b7aa63a3ade0cc1043efe08c", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 80, "avg_line_length": 36.95412844036697, "alnum_prop": 0.7025819265143992, "repo_name": "rgayon/plaso", "id": "5739a76f60b8e6b599acca5a4e06bbb6dba2fa62", "size": "4070", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/parsers/santa.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "415" }, { "name": "Dockerfile", "bytes": "1047" }, { "name": "Makefile", "bytes": "712" }, { "name": "PowerShell", "bytes": "17771" }, { "name": "Python", "bytes": "4803191" }, { "name": "Ruby", "bytes": "926" }, { "name": "Shell", "bytes": "46225" } ], "symlink_target": "" }
from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.environment.adapters.indexentries import IndexEntries from sphinx.writers.html5 import HTML5Translator class DPYHTML5Translator(HTML5Translator): def visit_section(self, node): self.section_level += 1 self.body.append( self.starttag(node, 'section')) def depart_section(self, node): self.section_level -= 1 self.body.append('</section>\n') def visit_table(self, node): self.body.append('<div class="table-wrapper">') super().visit_table(node) def depart_table(self, node): super().depart_table(node) self.body.append('</div>') class DPYStandaloneHTMLBuilder(StandaloneHTMLBuilder): # This is mostly copy pasted from Sphinx. def write_genindex(self) -> None: # the total count of lines for each index letter, used to distribute # the entries into two columns genindex = IndexEntries(self.env).create_index(self, group_entries=False) indexcounts = [] for _k, entries in genindex: indexcounts.append(sum(1 + len(subitems) for _, (_, subitems, _) in entries)) genindexcontext = { 'genindexentries': genindex, 'genindexcounts': indexcounts, 'split_index': self.config.html_split_index, } if self.config.html_split_index: self.handle_page('genindex', genindexcontext, 'genindex-split.html') self.handle_page('genindex-all', genindexcontext, 'genindex.html') for (key, entries), count in zip(genindex, indexcounts): ctx = {'key': key, 'entries': entries, 'count': count, 'genindexentries': genindex} self.handle_page('genindex-' + key, ctx, 'genindex-single.html') else: self.handle_page('genindex', genindexcontext, 'genindex.html') def add_custom_jinja2(app): env = app.builder.templates.environment env.tests['prefixedwith'] = str.startswith env.tests['suffixedwith'] = str.endswith def add_builders(app): """This is necessary because RTD injects their own for some reason.""" app.set_translator('html', DPYHTML5Translator, override=True) app.add_builder(DPYStandaloneHTMLBuilder, override=True) try: original = app.registry.builders['readthedocs'] except KeyError: pass else: injected_mro = tuple(base if base is not StandaloneHTMLBuilder else DPYStandaloneHTMLBuilder for base in original.mro()[1:]) new_builder = type(original.__name__, injected_mro, {'name': 'readthedocs'}) app.set_translator('readthedocs', DPYHTML5Translator, override=True) app.add_builder(new_builder, override=True) def setup(app): add_builders(app) app.connect('builder-inited', add_custom_jinja2)
{ "content_hash": "fadb6e43eb2444563d175754a61af8d5", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 100, "avg_line_length": 39.22077922077922, "alnum_prop": 0.6201986754966887, "repo_name": "Harmon758/discord.py", "id": "3f2b2594501946e4e3d507068315d676c49029f2", "size": "3020", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/extensions/builder.py", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "782" }, { "name": "Python", "bytes": "2149050" } ], "symlink_target": "" }
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import os, sys, warnings if six.PY3: warnings.warn( "The gtk* backends have not been tested with Python 3.x", ImportWarning) try: import gobject import gtk; gdk = gtk.gdk import pango except ImportError: raise ImportError("Gtk* backend requires pygtk to be installed.") pygtk_version_required = (2,4,0) if gtk.pygtk_version < pygtk_version_required: raise ImportError ("PyGTK %d.%d.%d is installed\n" "PyGTK %d.%d.%d or later is required" % (gtk.pygtk_version + pygtk_version_required)) del pygtk_version_required _new_tooltip_api = (gtk.pygtk_version[1] >= 12) import matplotlib from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase, cursors) from matplotlib.backends.backend_gdk import RendererGDK, FigureCanvasGDK from matplotlib.cbook import is_writable_file_like, warn_deprecated from matplotlib.figure import Figure from matplotlib.widgets import SubplotTool from matplotlib import ( cbook, colors as mcolors, lines, markers, rcParams, verbose) backend_version = "%d.%d.%d" % gtk.pygtk_version # the true dots per inch on the screen; should be display dependent # see http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5 for some info about screen dpi PIXELS_PER_INCH = 96 # Hide the benign warning that it can't stat a file that doesn't warnings.filterwarnings('ignore', '.*Unable to retrieve the file info for.*', gtk.Warning) cursord = { cursors.MOVE : gdk.Cursor(gdk.FLEUR), cursors.HAND : gdk.Cursor(gdk.HAND2), cursors.POINTER : gdk.Cursor(gdk.LEFT_PTR), cursors.SELECT_REGION : gdk.Cursor(gdk.TCROSS), cursors.WAIT : gdk.Cursor(gdk.WATCH), } # ref gtk+/gtk/gtkwidget.h def GTK_WIDGET_DRAWABLE(w): flags = w.flags(); return flags & gtk.VISIBLE != 0 and flags & gtk.MAPPED != 0 class TimerGTK(TimerBase): ''' Subclass of :class:`backend_bases.TimerBase` using GTK for timer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. callbacks : list Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions `add_callback` and `remove_callback` can be used. ''' def _timer_start(self): # Need to stop it, otherwise we potentially leak a timer id that will # never be stopped. self._timer_stop() self._timer = gobject.timeout_add(self._interval, self._on_timer) def _timer_stop(self): if self._timer is not None: gobject.source_remove(self._timer) self._timer = None def _timer_set_interval(self): # Only stop and restart it if the timer has already been started if self._timer is not None: self._timer_stop() self._timer_start() def _on_timer(self): TimerBase._on_timer(self) # Gtk timeout_add() requires that the callback returns True if it # is to be called again. if len(self.callbacks) > 0 and not self._single: return True else: self._timer = None return False class FigureCanvasGTK (gtk.DrawingArea, FigureCanvasBase): keyvald = {65507 : 'control', 65505 : 'shift', 65513 : 'alt', 65508 : 'control', 65506 : 'shift', 65514 : 'alt', 65361 : 'left', 65362 : 'up', 65363 : 'right', 65364 : 'down', 65307 : 'escape', 65470 : 'f1', 65471 : 'f2', 65472 : 'f3', 65473 : 'f4', 65474 : 'f5', 65475 : 'f6', 65476 : 'f7', 65477 : 'f8', 65478 : 'f9', 65479 : 'f10', 65480 : 'f11', 65481 : 'f12', 65300 : 'scroll_lock', 65299 : 'break', 65288 : 'backspace', 65293 : 'enter', 65379 : 'insert', 65535 : 'delete', 65360 : 'home', 65367 : 'end', 65365 : 'pageup', 65366 : 'pagedown', 65438 : '0', 65436 : '1', 65433 : '2', 65435 : '3', 65430 : '4', 65437 : '5', 65432 : '6', 65429 : '7', 65431 : '8', 65434 : '9', 65451 : '+', 65453 : '-', 65450 : '*', 65455 : '/', 65439 : 'dec', 65421 : 'enter', 65511 : 'super', 65512 : 'super', 65406 : 'alt', 65289 : 'tab', } # Setting this as a static constant prevents # this resulting expression from leaking event_mask = (gdk.BUTTON_PRESS_MASK | gdk.BUTTON_RELEASE_MASK | gdk.EXPOSURE_MASK | gdk.KEY_PRESS_MASK | gdk.KEY_RELEASE_MASK | gdk.ENTER_NOTIFY_MASK | gdk.LEAVE_NOTIFY_MASK | gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK) def __init__(self, figure): if self.__class__ == matplotlib.backends.backend_gtk.FigureCanvasGTK: warn_deprecated('2.0', message="The GTK backend is " "deprecated. It is untested, known to be " "broken and will be removed in Matplotlib 2.2. " "Use the GTKAgg backend instead. " "See Matplotlib usage FAQ for" " more info on backends.", alternative="GTKAgg") FigureCanvasBase.__init__(self, figure) gtk.DrawingArea.__init__(self) self._idle_draw_id = 0 self._need_redraw = True self._pixmap_width = -1 self._pixmap_height = -1 self._lastCursor = None self.connect('scroll_event', self.scroll_event) self.connect('button_press_event', self.button_press_event) self.connect('button_release_event', self.button_release_event) self.connect('configure_event', self.configure_event) self.connect('expose_event', self.expose_event) self.connect('key_press_event', self.key_press_event) self.connect('key_release_event', self.key_release_event) self.connect('motion_notify_event', self.motion_notify_event) self.connect('leave_notify_event', self.leave_notify_event) self.connect('enter_notify_event', self.enter_notify_event) self.set_events(self.__class__.event_mask) self.set_double_buffered(False) self.set_flags(gtk.CAN_FOCUS) self._renderer_init() self.last_downclick = {} def destroy(self): #gtk.DrawingArea.destroy(self) self.close_event() if self._idle_draw_id != 0: gobject.source_remove(self._idle_draw_id) def scroll_event(self, widget, event): x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y if event.direction==gdk.SCROLL_UP: step = 1 else: step = -1 FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) return False # finish event propagation? def button_press_event(self, widget, event): x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y dblclick = (event.type == gdk._2BUTTON_PRESS) if not dblclick: # GTK is the only backend that generates a DOWN-UP-DOWN-DBLCLICK-UP event # sequence for a double click. All other backends have a DOWN-UP-DBLCLICK-UP # sequence. In order to provide consistency to matplotlib users, we will # eat the extra DOWN event in the case that we detect it is part of a double # click. # first, get the double click time in milliseconds. current_time = event.get_time() last_time = self.last_downclick.get(event.button,0) dblclick_time = gtk.settings_get_for_screen(gdk.screen_get_default()).get_property('gtk-double-click-time') delta_time = current_time-last_time if delta_time < dblclick_time: del self.last_downclick[event.button] # we do not want to eat more than one event. return False # eat. self.last_downclick[event.button] = current_time FigureCanvasBase.button_press_event(self, x, y, event.button, dblclick=dblclick, guiEvent=event) return False # finish event propagation? def button_release_event(self, widget, event): x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y FigureCanvasBase.button_release_event(self, x, y, event.button, guiEvent=event) return False # finish event propagation? def key_press_event(self, widget, event): key = self._get_key(event) FigureCanvasBase.key_press_event(self, key, guiEvent=event) return True # stop event propagation def key_release_event(self, widget, event): key = self._get_key(event) FigureCanvasBase.key_release_event(self, key, guiEvent=event) return True # stop event propagation def motion_notify_event(self, widget, event): if event.is_hint: x, y, state = event.window.get_pointer() else: x, y, state = event.x, event.y, event.state # flipy so y=0 is bottom of canvas y = self.allocation.height - y FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event) return False # finish event propagation? def leave_notify_event(self, widget, event): FigureCanvasBase.leave_notify_event(self, event) def enter_notify_event(self, widget, event): x, y, state = event.window.get_pointer() FigureCanvasBase.enter_notify_event(self, event, xy=(x, y)) def _get_key(self, event): if event.keyval in self.keyvald: key = self.keyvald[event.keyval] elif event.keyval < 256: key = chr(event.keyval) else: key = None for key_mask, prefix in ( [gdk.MOD4_MASK, 'super'], [gdk.MOD1_MASK, 'alt'], [gdk.CONTROL_MASK, 'ctrl'], ): if event.state & key_mask: key = '{0}+{1}'.format(prefix, key) return key def configure_event(self, widget, event): if widget.window is None: return w, h = event.width, event.height if w < 3 or h < 3: return # empty fig # resize the figure (in inches) dpi = self.figure.dpi self.figure.set_size_inches(w/dpi, h/dpi, forward=False) self._need_redraw = True return False # finish event propagation? def draw(self): # Note: FigureCanvasBase.draw() is inconveniently named as it clashes # with the deprecated gtk.Widget.draw() self._need_redraw = True if GTK_WIDGET_DRAWABLE(self): self.queue_draw() # do a synchronous draw (its less efficient than an async draw, # but is required if/when animation is used) self.window.process_updates (False) def draw_idle(self): if self._idle_draw_id != 0: return def idle_draw(*args): try: self.draw() finally: self._idle_draw_id = 0 return False self._idle_draw_id = gobject.idle_add(idle_draw) def _renderer_init(self): """Override by GTK backends to select a different renderer Renderer should provide the methods: set_pixmap () set_width_height () that are used by _render_figure() / _pixmap_prepare() """ self._renderer = RendererGDK (self, self.figure.dpi) def _pixmap_prepare(self, width, height): """ Make sure _._pixmap is at least width, height, create new pixmap if necessary """ create_pixmap = False if width > self._pixmap_width: # increase the pixmap in 10%+ (rather than 1 pixel) steps self._pixmap_width = max (int (self._pixmap_width * 1.1), width) create_pixmap = True if height > self._pixmap_height: self._pixmap_height = max (int (self._pixmap_height * 1.1), height) create_pixmap = True if create_pixmap: self._pixmap = gdk.Pixmap (self.window, self._pixmap_width, self._pixmap_height) self._renderer.set_pixmap (self._pixmap) def _render_figure(self, pixmap, width, height): """used by GTK and GTKcairo. GTKAgg overrides """ self._renderer.set_width_height (width, height) self.figure.draw (self._renderer) def expose_event(self, widget, event): """Expose_event for all GTK backends. Should not be overridden. """ toolbar = self.toolbar if toolbar: toolbar.set_cursor(cursors.WAIT) if GTK_WIDGET_DRAWABLE(self): if self._need_redraw: x, y, w, h = self.allocation self._pixmap_prepare (w, h) self._render_figure(self._pixmap, w, h) self._need_redraw = False x, y, w, h = event.area self.window.draw_drawable (self.style.fg_gc[self.state], self._pixmap, x, y, x, y, w, h) if toolbar: toolbar.set_cursor(toolbar._lastCursor) return False # finish event propagation? filetypes = FigureCanvasBase.filetypes.copy() filetypes['jpg'] = 'JPEG' filetypes['jpeg'] = 'JPEG' filetypes['png'] = 'Portable Network Graphics' def print_jpeg(self, filename, *args, **kwargs): return self._print_image(filename, 'jpeg') print_jpg = print_jpeg def print_png(self, filename, *args, **kwargs): return self._print_image(filename, 'png') def _print_image(self, filename, format, *args, **kwargs): if self.flags() & gtk.REALIZED == 0: # for self.window(for pixmap) and has a side effect of altering # figure width,height (via configure-event?) gtk.DrawingArea.realize(self) width, height = self.get_width_height() pixmap = gdk.Pixmap (self.window, width, height) self._renderer.set_pixmap (pixmap) self._render_figure(pixmap, width, height) # jpg colors don't match the display very well, png colors match # better pixbuf = gdk.Pixbuf(gdk.COLORSPACE_RGB, 0, 8, width, height) pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, width, height) # set the default quality, if we are writing a JPEG. # http://www.pygtk.org/docs/pygtk/class-gdkpixbuf.html#method-gdkpixbuf--save options = {k: kwargs[k] for k in ['quality'] if k in kwargs} if format in ['jpg', 'jpeg']: options.setdefault('quality', rcParams['savefig.jpeg_quality']) options['quality'] = str(options['quality']) if isinstance(filename, six.string_types): try: pixbuf.save(filename, format, options=options) except gobject.GError as exc: error_msg_gtk('Save figure failure:\n%s' % (exc,), parent=self) elif is_writable_file_like(filename): if hasattr(pixbuf, 'save_to_callback'): def save_callback(buf, data=None): data.write(buf) try: pixbuf.save_to_callback(save_callback, format, user_data=filename, options=options) except gobject.GError as exc: error_msg_gtk('Save figure failure:\n%s' % (exc,), parent=self) else: raise ValueError("Saving to a Python file-like object is only supported by PyGTK >= 2.8") else: raise ValueError("filename must be a path or a file-like object") def new_timer(self, *args, **kwargs): """ Creates a new backend-specific subclass of :class:`backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. Other Parameters ---------------- interval : scalar Timer interval in milliseconds callbacks : list Sequence of (func, args, kwargs) where ``func(*args, **kwargs)`` will be executed by the timer every *interval*. """ return TimerGTK(*args, **kwargs) def flush_events(self): gtk.gdk.threads_enter() while gtk.events_pending(): gtk.main_iteration(True) gtk.gdk.flush() gtk.gdk.threads_leave() class FigureManagerGTK(FigureManagerBase): """ Attributes ---------- canvas : `FigureCanvas` The FigureCanvas instance num : int or str The Figure number toolbar : gtk.Toolbar The gtk.Toolbar (gtk only) vbox : gtk.VBox The gtk.VBox containing the canvas and toolbar (gtk only) window : gtk.Window The gtk.Window (gtk only) """ def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) self.window = gtk.Window() self.window.set_wmclass("matplotlib", "Matplotlib") self.set_window_title("Figure %d" % num) if window_icon: try: self.window.set_icon_from_file(window_icon) except: # some versions of gtk throw a glib.GError but not # all, so I am not sure how to catch it. I am unhappy # diong a blanket catch here, but an not sure what a # better way is - JDH verbose.report('Could not load matplotlib icon: %s' % sys.exc_info()[1]) self.vbox = gtk.VBox() self.window.add(self.vbox) self.vbox.show() self.canvas.show() self.vbox.pack_start(self.canvas, True, True) self.toolbar = self._get_toolbar(canvas) # calculate size for window w = int (self.canvas.figure.bbox.width) h = int (self.canvas.figure.bbox.height) if self.toolbar is not None: self.toolbar.show() self.vbox.pack_end(self.toolbar, False, False) tb_w, tb_h = self.toolbar.size_request() h += tb_h self.window.set_default_size (w, h) def destroy(*args): Gcf.destroy(num) self.window.connect("destroy", destroy) self.window.connect("delete_event", destroy) if matplotlib.is_interactive(): self.window.show() self.canvas.draw_idle() def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolbar is not None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) self.canvas.grab_focus() def destroy(self, *args): if hasattr(self, 'toolbar') and self.toolbar is not None: self.toolbar.destroy() if hasattr(self, 'vbox'): self.vbox.destroy() if hasattr(self, 'window'): self.window.destroy() if hasattr(self, 'canvas'): self.canvas.destroy() self.__dict__.clear() #Is this needed? Other backends don't have it. if Gcf.get_num_fig_managers()==0 and \ not matplotlib.is_interactive() and \ gtk.main_level() >= 1: gtk.main_quit() def show(self): # show the figure window self.window.show() # raise the window above others and relase the "above lock" self.window.set_keep_above(True) self.window.set_keep_above(False) def full_screen_toggle(self): self._full_screen_flag = not self._full_screen_flag if self._full_screen_flag: self.window.fullscreen() else: self.window.unfullscreen() _full_screen_flag = False def _get_toolbar(self, canvas): # must be inited after the window, drawingArea and figure # attrs are set if rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2GTK (canvas, self.window) else: toolbar = None return toolbar def get_window_title(self): return self.window.get_title() def set_window_title(self, title): self.window.set_title(title) def resize(self, width, height): 'set the canvas size in pixels' #_, _, cw, ch = self.canvas.allocation #_, _, ww, wh = self.window.allocation #self.window.resize (width-cw+ww, height-ch+wh) self.window.resize(width, height) class NavigationToolbar2GTK(NavigationToolbar2, gtk.Toolbar): def __init__(self, canvas, window): self.win = window gtk.Toolbar.__init__(self) NavigationToolbar2.__init__(self, canvas) def set_message(self, s): self.message.set_label(s) def set_cursor(self, cursor): self.canvas.window.set_cursor(cursord[cursor]) gtk.main_iteration() def release(self, event): try: del self._pixmapBack except AttributeError: pass def draw_rubberband(self, event, x0, y0, x1, y1): 'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744' drawable = self.canvas.window if drawable is None: return gc = drawable.new_gc() height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 w = abs(x1 - x0) h = abs(y1 - y0) rect = [int(val)for val in (min(x0,x1), min(y0, y1), w, h)] try: lastrect, pixmapBack = self._pixmapBack except AttributeError: #snap image back if event.inaxes is None: return ax = event.inaxes l,b,w,h = [int(val) for val in ax.bbox.bounds] b = int(height)-(b+h) axrect = l,b,w,h self._pixmapBack = axrect, gtk.gdk.Pixmap(drawable, w, h) self._pixmapBack[1].draw_drawable(gc, drawable, l, b, 0, 0, w, h) else: drawable.draw_drawable(gc, pixmapBack, 0, 0, *lastrect) drawable.draw_rectangle(gc, False, *rect) def _init_toolbar(self): self.set_style(gtk.TOOLBAR_ICONS) self._init_toolbar2_4() def _init_toolbar2_4(self): basedir = os.path.join(rcParams['datapath'],'images') if not _new_tooltip_api: self.tooltips = gtk.Tooltips() for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.insert( gtk.SeparatorToolItem(), -1 ) continue fname = os.path.join(basedir, image_file + '.png') image = gtk.Image() image.set_from_file(fname) tbutton = gtk.ToolButton(image, text) self.insert(tbutton, -1) tbutton.connect('clicked', getattr(self, callback)) if _new_tooltip_api: tbutton.set_tooltip_text(tooltip_text) else: tbutton.set_tooltip(self.tooltips, tooltip_text, 'Private') toolitem = gtk.SeparatorToolItem() self.insert(toolitem, -1) # set_draw() not making separator invisible, # bug #143692 fixed Jun 06 2004, will be in GTK+ 2.6 toolitem.set_draw(False) toolitem.set_expand(True) toolitem = gtk.ToolItem() self.insert(toolitem, -1) self.message = gtk.Label() toolitem.add(self.message) self.show_all() def get_filechooser(self): fc = FileChooserDialog( title='Save the figure', parent=self.win, path=os.path.expanduser(rcParams['savefig.directory']), filetypes=self.canvas.get_supported_filetypes(), default_filetype=self.canvas.get_default_filetype()) fc.set_current_name(self.canvas.get_default_filename()) return fc def save_figure(self, *args): chooser = self.get_filechooser() fname, format = chooser.get_filename_from_user() chooser.destroy() if fname: # Save dir for next time, unless empty str (i.e., use cwd). if startpath != "": rcParams['savefig.directory'] = ( os.path.dirname(six.text_type(fname))) try: self.canvas.figure.savefig(fname, format=format) except Exception as e: error_msg_gtk(str(e), parent=self) def configure_subplots(self, button): toolfig = Figure(figsize=(6,3)) canvas = self._get_canvas(toolfig) toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) w = int(toolfig.bbox.width) h = int(toolfig.bbox.height) window = gtk.Window() if window_icon: try: window.set_icon_from_file(window_icon) except: # we presumably already logged a message on the # failure of the main plot, don't keep reporting pass window.set_title("Subplot Configuration Tool") window.set_default_size(w, h) vbox = gtk.VBox() window.add(vbox) vbox.show() canvas.show() vbox.pack_start(canvas, True, True) window.show() def _get_canvas(self, fig): return FigureCanvasGTK(fig) class FileChooserDialog(gtk.FileChooserDialog): """GTK+ 2.4 file selector which presents the user with a menu of supported image formats """ def __init__ (self, title = 'Save file', parent = None, action = gtk.FILE_CHOOSER_ACTION_SAVE, buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK), path = None, filetypes = [], default_filetype = None ): super(FileChooserDialog, self).__init__(title, parent, action, buttons) super(FileChooserDialog, self).set_do_overwrite_confirmation(True) self.set_default_response(gtk.RESPONSE_OK) if not path: path = os.getcwd() + os.sep # create an extra widget to list supported image formats self.set_current_folder (path) self.set_current_name ('image.' + default_filetype) hbox = gtk.HBox(spacing=10) hbox.pack_start(gtk.Label ("File Format:"), expand=False) liststore = gtk.ListStore(gobject.TYPE_STRING) cbox = gtk.ComboBox(liststore) cell = gtk.CellRendererText() cbox.pack_start(cell, True) cbox.add_attribute(cell, 'text', 0) hbox.pack_start(cbox) self.filetypes = filetypes self.sorted_filetypes = sorted(six.iteritems(filetypes)) default = 0 for i, (ext, name) in enumerate(self.sorted_filetypes): cbox.append_text("%s (*.%s)" % (name, ext)) if ext == default_filetype: default = i cbox.set_active(default) self.ext = default_filetype def cb_cbox_changed (cbox, data=None): """File extension changed""" head, filename = os.path.split(self.get_filename()) root, ext = os.path.splitext(filename) ext = ext[1:] new_ext = self.sorted_filetypes[cbox.get_active()][0] self.ext = new_ext if ext in self.filetypes: filename = root + '.' + new_ext elif ext == '': filename = filename.rstrip('.') + '.' + new_ext self.set_current_name(filename) cbox.connect("changed", cb_cbox_changed) hbox.show_all() self.set_extra_widget(hbox) def get_filename_from_user (self): while True: filename = None if self.run() != int(gtk.RESPONSE_OK): break filename = self.get_filename() break return filename, self.ext class DialogLineprops(object): """ A GUI dialog for controlling lineprops """ signals = ( 'on_combobox_lineprops_changed', 'on_combobox_linestyle_changed', 'on_combobox_marker_changed', 'on_colorbutton_linestyle_color_set', 'on_colorbutton_markerface_color_set', 'on_dialog_lineprops_okbutton_clicked', 'on_dialog_lineprops_cancelbutton_clicked', ) linestyles = [ls for ls in lines.Line2D.lineStyles if ls.strip()] linestyled = {s: i for i, s in enumerate(linestyles)} markers = [m for m in markers.MarkerStyle.markers if isinstance(m, six.string_types)] markerd = {s: i for i, s in enumerate(markers)} def __init__(self, lines): import gtk.glade datadir = matplotlib.get_data_path() gladefile = os.path.join(datadir, 'lineprops.glade') if not os.path.exists(gladefile): raise IOError( 'Could not find gladefile lineprops.glade in %s' % datadir) self._inited = False self._updateson = True # suppress updates when setting widgets manually self.wtree = gtk.glade.XML(gladefile, 'dialog_lineprops') self.wtree.signal_autoconnect( {s: getattr(self, s) for s in self.signals}) self.dlg = self.wtree.get_widget('dialog_lineprops') self.lines = lines cbox = self.wtree.get_widget('combobox_lineprops') cbox.set_active(0) self.cbox_lineprops = cbox cbox = self.wtree.get_widget('combobox_linestyles') for ls in self.linestyles: cbox.append_text(ls) cbox.set_active(0) self.cbox_linestyles = cbox cbox = self.wtree.get_widget('combobox_markers') for m in self.markers: cbox.append_text(m) cbox.set_active(0) self.cbox_markers = cbox self._lastcnt = 0 self._inited = True def show(self): 'populate the combo box' self._updateson = False # flush the old cbox = self.cbox_lineprops for i in range(self._lastcnt-1,-1,-1): cbox.remove_text(i) # add the new for line in self.lines: cbox.append_text(line.get_label()) cbox.set_active(0) self._updateson = True self._lastcnt = len(self.lines) self.dlg.show() def get_active_line(self): 'get the active line' ind = self.cbox_lineprops.get_active() line = self.lines[ind] return line def get_active_linestyle(self): 'get the active lineinestyle' ind = self.cbox_linestyles.get_active() ls = self.linestyles[ind] return ls def get_active_marker(self): 'get the active lineinestyle' ind = self.cbox_markers.get_active() m = self.markers[ind] return m def _update(self): 'update the active line props from the widgets' if not self._inited or not self._updateson: return line = self.get_active_line() ls = self.get_active_linestyle() marker = self.get_active_marker() line.set_linestyle(ls) line.set_marker(marker) button = self.wtree.get_widget('colorbutton_linestyle') color = button.get_color() r, g, b = [val/65535. for val in (color.red, color.green, color.blue)] line.set_color((r,g,b)) button = self.wtree.get_widget('colorbutton_markerface') color = button.get_color() r, g, b = [val/65535. for val in (color.red, color.green, color.blue)] line.set_markerfacecolor((r,g,b)) line.figure.canvas.draw() def on_combobox_lineprops_changed(self, item): 'update the widgets from the active line' if not self._inited: return self._updateson = False line = self.get_active_line() ls = line.get_linestyle() if ls is None: ls = 'None' self.cbox_linestyles.set_active(self.linestyled[ls]) marker = line.get_marker() if marker is None: marker = 'None' self.cbox_markers.set_active(self.markerd[marker]) rgba = mcolors.to_rgba(line.get_color()) color = gtk.gdk.Color(*[int(val*65535) for val in rgba[:3]]) button = self.wtree.get_widget('colorbutton_linestyle') button.set_color(color) rgba = mcolors.to_rgba(line.get_markerfacecolor()) color = gtk.gdk.Color(*[int(val*65535) for val in rgba[:3]]) button = self.wtree.get_widget('colorbutton_markerface') button.set_color(color) self._updateson = True def on_combobox_linestyle_changed(self, item): self._update() def on_combobox_marker_changed(self, item): self._update() def on_colorbutton_linestyle_color_set(self, button): self._update() def on_colorbutton_markerface_color_set(self, button): 'called colorbutton marker clicked' self._update() def on_dialog_lineprops_okbutton_clicked(self, button): self._update() self.dlg.hide() def on_dialog_lineprops_cancelbutton_clicked(self, button): self.dlg.hide() # set icon used when windows are minimized # Unfortunately, the SVG renderer (rsvg) leaks memory under earlier # versions of pygtk, so we have to use a PNG file instead. try: if gtk.pygtk_version < (2, 8, 0) or sys.platform == 'win32': icon_filename = 'matplotlib.png' else: icon_filename = 'matplotlib.svg' window_icon = os.path.join(rcParams['datapath'], 'images', icon_filename) except: window_icon = None verbose.report('Could not load matplotlib icon: %s' % sys.exc_info()[1]) def error_msg_gtk(msg, parent=None): if parent is not None: # find the toplevel gtk.Window parent = parent.get_toplevel() if parent.flags() & gtk.TOPLEVEL == 0: parent = None if not isinstance(msg, six.string_types): msg = ','.join(map(str,msg)) dialog = gtk.MessageDialog( parent = parent, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_OK, message_format = msg) dialog.run() dialog.destroy() @_Backend.export class _BackendGTK(_Backend): FigureCanvas = FigureCanvasGTK FigureManager = FigureManagerGTK @staticmethod def trigger_manager_draw(manager): manager.canvas.draw_idle() @staticmethod def mainloop(): if gtk.main_level() == 0: gtk.main()
{ "content_hash": "029f69e28c18ebc08002681153b6a55b", "timestamp": "", "source": "github", "line_count": 1031, "max_line_length": 166, "avg_line_length": 35.00581959262852, "alnum_prop": 0.5684519686348397, "repo_name": "louisLouL/pair_trading", "id": "45dd67442611c27e8d55f87ded37abca63bba0b7", "size": "36091", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "capstone_env/lib/python3.6/site-packages/matplotlib/backends/backend_gtk.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "148513" }, { "name": "C++", "bytes": "172384" }, { "name": "CSS", "bytes": "5382" }, { "name": "Fortran", "bytes": "8281" }, { "name": "HTML", "bytes": "568460" }, { "name": "JavaScript", "bytes": "25360" }, { "name": "Jupyter Notebook", "bytes": "16254" }, { "name": "Python", "bytes": "30357437" }, { "name": "Shell", "bytes": "3260" }, { "name": "Smarty", "bytes": "2045" } ], "symlink_target": "" }
from pyglfw.libapi import * if __name__ == '__main__': @GLFWkeyfun def InputKey(window, key, scancode, action, mods): print(window, key, scancode, action, mods) def show_error(code, message): print(code, message) def _utf(obj): if bytes is str: return obj else: return obj.encode() def _str(obj): if bytes is str: return obj else: return obj.decode() ShowError = GLFWerrorfun(show_error) glfwSetErrorCallback(ShowError) if not glfwInit(): raise RuntimeError() print(_str(glfwGetVersionString())) w, h, use_monitor = 0, 0, None monitors = glfwGetMonitors() for monitor in monitors: vidmodes = glfwGetVideoModes(monitor) for vidmode in vidmodes: if (vidmode.height * vidmode.width) > w * h: w, h, use_monitor = vidmode.width, vidmode.height, monitor glfwSetGamma(monitors[0], -1.0) gammar = glfwGetGammaRamp(monitors[0]) glfwSetGammaRamp(monitors[0], gammar) window = glfwCreateWindow(800, 600, _utf("Привет, Мир!"), None, None) #window = glfwCreateWindow(w, h, "Привет, Мир!", use_monitor, None) if not window: glfwTerminate() raise SystemExit() glfwMakeContextCurrent(window) glfwSetClipboardString(window, _utf("Тест")) print(_str(glfwGetClipboardString(window))) glfwSwapInterval(1) size = glfwGetFramebufferSize(window) glfwSetWindowUserPointer(window, size) fps, was = 0, glfwGetTime() glfwSetKeyCallback(window, InputKey) while not glfwWindowShouldClose(window): glfwSwapBuffers(window) fps, now = fps + 1, glfwGetTime() if now - was >= 1.0: # print (fps) fps, was = 0, now glfwPollEvents() if glfwGetKey(window, GLFW_KEY_ESCAPE): glfwSetWindowShouldClose(window, True) try: print (glfwGetWindowUserPointer(window)) except: print ('Set/Get UserPointer is not supported') glfwDestroyWindow(window) glfwTerminate()
{ "content_hash": "36cdd6f8d7aaab243a6af5386ad806ef", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 74, "avg_line_length": 26.261904761904763, "alnum_prop": 0.5906618313689936, "repo_name": "lhl/vrdev", "id": "b758d56ca840fed4fd542b608a8b6d3fc0356beb", "size": "2244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "002-pyopengl/examples/raw_api.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "195562" }, { "name": "JavaScript", "bytes": "1624" }, { "name": "Jupyter Notebook", "bytes": "1091162" }, { "name": "Python", "bytes": "856749" }, { "name": "Shell", "bytes": "832" } ], "symlink_target": "" }
from django.contrib import admin from models import Page, TPage, Content, TContent class PageAdmin(admin.ModelAdmin): exclude = ['posted'] #fields = ['posted', 'title'] list_display = ('title', 'posted', 'slug') prepopulated_fields = {'slug': ('title',)} class TPageAdmin(admin.ModelAdmin): list_display = ('title', 'language', 'page') #prepopulated_fields = {'slug': ('title',)} class ContentAdmin(admin.ModelAdmin): exclude = ['posted'] #fields = ['posted', 'title'] list_display = ('code', 'posted', 'page') prepopulated_fields = {'slug': ('code',)} class TContentAdmin(admin.ModelAdmin): #change_form_template = 'page/admin/change_form.html' list_display = ('content', 'language', 'page') #prepopulated_fields = {'slug': ('title',)} admin.site.register(Page, PageAdmin) admin.site.register(TPage, TPageAdmin) admin.site.register(Content, ContentAdmin) admin.site.register(TContent, TContentAdmin)
{ "content_hash": "e2cf98f5399395c996431fc021533d59", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 57, "avg_line_length": 34.357142857142854, "alnum_prop": 0.6704781704781705, "repo_name": "vollov/isda.ca", "id": "8fcddfaed81f00d794d68d4c51ff780007aa6a7b", "size": "962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "isda_backend/page/admin.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8065" }, { "name": "HTML", "bytes": "38798" }, { "name": "JavaScript", "bytes": "72575" }, { "name": "Python", "bytes": "10861" } ], "symlink_target": "" }
"""Functions for computing Fleiss's kappa (𝜅), a measure of inter-annotator agreement between several (more than 2) annotators.""" import numpy as np def kappa(data): """Computes Fleiss's 𝜅 coefficient given a matrix of subject ratings. The data must be an N x M matrix where N is the number of subjects and M is the number of labels. P̅ - P̅(e) Fleiss's 𝜅 = ---------- 1 - P̅(e) Where... P̅ = the percentage of observed agreement P̅(e) = the percentage of expected agreement.""" if not issubclass(data.dtype.type, np.integer): raise TypeError('expected integer type') if len(data.shape) != 2: raise ValueError('input must be 2-dimensional array') if not np.isfinite(data).all(): raise ValueError('all data must be finite') if (data < 0).any(): raise ValueError('all data must be non-negative') if np.sum(data) <= 0: raise ValueError('total data must sum to positive value') if not len(set(sum(data.T))) == 1: raise ValueError('all subjects must have the same number of ratings') observation = observed(data) expectation = expected(data) perfection = 1.0 k = np.divide( observation - expectation, perfection - expectation ) return k def label_proportions(data): """Computes the proportion of ratings, p(j), assigned to each label. I.e., for each label j, what percentage of all ratings, were assigned to that label.""" label_proportions = np.divide(sum(data).astype(float), data.sum()) return label_proportions def subject_agreements(data): """Computes the per-subject agreement, P(i), for each subject. I.e., compute how many inter-rater pairs are in agreement, relative to the number of all possible pairs: 𝛴(j=1 → k)[n(i,j)² - n] P(i) = ----------------------- n(n - 1) Where... i = a subject (i.e., row) index j = a label (i.e., column) index k = the number of labels n(i,j) = how many raters assigned the j-th label to the i-th subject n = number of ratings per subject (i.e., the sum of one row)""" subject_indices, label_indices = map(range, data.shape) dot_products = np.array([np.dot(data[i], data[i]) for i in subject_indices]) sums = data.sum(axis=1).astype(float) numerators = dot_products - sums denominators = np.array([sums[i] * (sums[i] - 1) for i in subject_indices]) subject_agreements = np.divide(numerators, denominators) return subject_agreements def observed(data): """Computes the observed agreement, P̅.""" percent_agreement = np.mean(subject_agreements(data)) return percent_agreement def expected(data): """Computes the expected agreement, P̅(e).""" proportions = label_proportions(data) percent_expected = np.dot(proportions, proportions) return percent_expected
{ "content_hash": "0adeb392dd349d0bf6fbb4d8528f0131", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 80, "avg_line_length": 37.074074074074076, "alnum_prop": 0.623043623043623, "repo_name": "zyocum/IAA", "id": "36e225ef67f7f3d75fdd2ec7c01a54487a50007c", "size": "3086", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fleiss.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "41445" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('game', '0006_auto_20160214_2303'), ] operations = [ migrations.AlterField( model_name='room', name='exits', field=models.ManyToManyField(blank=True, null=True, to='game.Exit'), ), ]
{ "content_hash": "212499c67e79648d89ca0996e66ab68b", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 80, "avg_line_length": 22.333333333333332, "alnum_prop": 0.5945273631840796, "repo_name": "josh-perry/venture", "id": "5b8467dfc1365003eaca7fa1d87529ff69f82603", "size": "474", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "game/migrations/0007_auto_20160214_2304.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "40" }, { "name": "Python", "bytes": "12549" } ], "symlink_target": "" }
import os.path from .. import bundle as bmod from .common import fake_file_system from nbx.tools import assert_items_equal def wrap_bundles(td, cls): bundles = ['second.ipynb', 'test.ipynb'] bundles = (cls(os.path.join(td, name)) for name in bundles) bundles = {bundle.name: bundle for bundle in bundles} return bundles class TestBundle: def test_files(self): """ Test .files property """ with fake_file_system() as td: bundles = wrap_bundles(td, bmod.Bundle) correct_files = {} correct_files['second.ipynb'] = ['second.ipynb', 'data.py'] correct_files['test.ipynb'] = ['test.ipynb'] for name, b in bundles.items(): assert not isinstance(b, bmod.NotebookBundle) correct = correct_files[b.name] assert_items_equal(list(b.files), correct) class TestNotebookBundle: def test_files(self): """ Test .files property """ with fake_file_system() as td: bundles = wrap_bundles(td, bmod.NotebookBundle) correct_files = {} correct_files['second.ipynb'] = ['data.py'] correct_files['test.ipynb'] = [] for name, b in bundles.items(): correct = correct_files[b.name] assert_items_equal(b.files, correct) def test_notebook_content(self): """ Test .notebook_content property """ with fake_file_system() as td: bundles = wrap_bundles(td, bmod.NotebookBundle) for name, b in bundles.items(): test = b.notebook_content['metadata']['filename'] assert test == b.name
{ "content_hash": "f0b281088debfcd41c04ad1f60a5b5f0", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 71, "avg_line_length": 30.49122807017544, "alnum_prop": 0.5627157652474108, "repo_name": "dalejung/nbx", "id": "5f3572c1fe6d2a127aa1528690c0eb22b66d87f2", "size": "1738", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nbx/nbmanager/bundle/tests/test_bundle.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "13" }, { "name": "JavaScript", "bytes": "37358" }, { "name": "Python", "bytes": "137690" }, { "name": "Shell", "bytes": "289" } ], "symlink_target": "" }
from __future__ import division from plugin import plugin @plugin('timeconv') class timeconv(): """ timeconv Documentation. timeconv is a time converter. Supports: picosecond, nanosecond, microsecond, millisecond, second, minute, hour, day, week, month, year Usage: The input time measurement units are: ps : picosecond, ns : nanosecond, mum : microsecond, mm : millisecond, s : second, min : minute, h : hour, d : day, wk : week, mon : month, yr : year First you will be asked to enter the amount you want to convert. Second you will be asked to enter the time measurement unit of the amount. And then you will be asked to enter to which time measurement unit you want to convert. """ time_units = [ "yr", "mon", "wk", "d", "h", "min", "s", "ms", "mus", "ns", "ps" ] units = { "ps": "picosecond", "ns": "nanosecond", "mus": "microsecond", "ms": "millisecond", "s": "second", "min": "minute", "h": "hour", "d": "day", "wk": "week", "mon": "month", "yr": "year" } units_data = { "yr2mon": 12, "mon2wk": 4.34812141, "wk2d": 7, "d2h": 24, "h2min": 60, "min2s": 60, "s2ms": 1000, "ms2mus": 1000, "mus2ns": 1000, "ns2ps": 1000 } def __call__(self, jarvis, s): while True: amount = jarvis.input_number('Enter an amount: ') from_unit = self.get_units(jarvis, 'Enter from which unit: ') to_unit = self.get_units(jarvis, 'Enter to which unit: ') if (from_unit != to_unit): break else: jarvis.say('Please enter different units') convamount = self.time_convert(jarvis, amount, from_unit, to_unit) precision = 0 if (convamount.is_integer() is False): precision = jarvis.input_number("Please enter precision (max:12): ") while True: if (precision.is_integer() and precision <= 12): break else: precision = jarvis.input_number("Please enter an integer (max:12): ") convamount = round(convamount, int(precision)) outputText = self.txt_build(amount, convamount, from_unit, to_unit) jarvis.say(outputText) def time_convert(self, jarvis, amount, fr, to): for i in range(len(self.time_units)): if (self.time_units[i] == fr): start = i if (self.time_units[i] == to): end = i if ((end - start) > 0): reverse = False if ((end - start) < 0): reverse = True tmp = start start = end end = tmp multiplier = 1 convamount = multiplier for i in range(start, end, 1): kbuild = self.time_units[i] + "2" + self.time_units[i + 1] multiplier = multiplier * self.units_data.get(kbuild) mulitplier = round(multiplier, 17) if reverse: convamount = (1 / multiplier) * amount else: convamount = multiplier * amount convamount = round(convamount, 12) return convamount def get_units(self, jarvis, prompt): while True: u = jarvis.input(prompt).lower() if u in self.time_units: return u else: prompt = 'Please enter a valid unit: ' continue def txt_build(self, amount, convamount, from_unit, to_unit): if (amount == 1): fromdisp = self.units.get(from_unit) else: fromdisp = self.units.get(from_unit) + "s" if (convamount == 1): todisp = self.units.get(to_unit) else: todisp = self.units.get(to_unit) + "s" txt = str(amount) + " " + fromdisp + " is equal to " + str(convamount) + " " + todisp return txt
{ "content_hash": "c7c9e8a3c38524a988ae9ac16f147bba", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 108, "avg_line_length": 27.711409395973153, "alnum_prop": 0.5073867764591911, "repo_name": "appi147/Jarvis", "id": "1e05b9293268825101d49c9dc3e5f31f6c8ee235", "size": "4129", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jarviscli/plugins/timeconv.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1191" }, { "name": "Dockerfile", "bytes": "333" }, { "name": "Makefile", "bytes": "310" }, { "name": "Python", "bytes": "300174" }, { "name": "Shell", "bytes": "2295" } ], "symlink_target": "" }
r""" ========================================================== Create a new coordinate class (for the Sagittarius stream) ========================================================== This document describes in detail how to subclass and define a custom spherical coordinate frame, as discussed in :ref:`astropy:astropy-coordinates-design` and the docstring for `~astropy.coordinates.BaseCoordinateFrame`. In this example, we will define a coordinate system defined by the plane of orbit of the Sagittarius Dwarf Galaxy (hereafter Sgr; as defined in Majewski et al. 2003). The Sgr coordinate system is often referred to in terms of two angular coordinates, :math:`\Lambda,B`. To do this, we need to define a subclass of `~astropy.coordinates.BaseCoordinateFrame` that knows the names and units of the coordinate system angles in each of the supported representations. In this case we support `~astropy.coordinates.SphericalRepresentation` with "Lambda" and "Beta". Then we have to define the transformation from this coordinate system to some other built-in system. Here we will use Galactic coordinates, represented by the `~astropy.coordinates.Galactic` class. See Also -------- * The `gala package <http://gala.adrian.pw/>`_, which defines a number of Astropy coordinate frames for stellar stream coordinate systems. * Majewski et al. 2003, "A Two Micron All Sky Survey View of the Sagittarius Dwarf Galaxy. I. Morphology of the Sagittarius Core and Tidal Arms", https://arxiv.org/abs/astro-ph/0304198 * Law & Majewski 2010, "The Sagittarius Dwarf Galaxy: A Model for Evolution in a Triaxial Milky Way Halo", https://arxiv.org/abs/1003.1132 * David Law's Sgr info page https://www.stsci.edu/~dlaw/Sgr/ *By: Adrian Price-Whelan, Erik Tollerud* *License: BSD* """ ############################################################################## # Make `print` work the same in all versions of Python, set up numpy, # matplotlib, and use a nicer set of plot parameters: import numpy as np import matplotlib.pyplot as plt from astropy.visualization import astropy_mpl_style plt.style.use(astropy_mpl_style) ############################################################################## # Import the packages necessary for coordinates from astropy.coordinates import frame_transform_graph from astropy.coordinates.matrix_utilities import rotation_matrix, matrix_product, matrix_transpose import astropy.coordinates as coord import astropy.units as u ############################################################################## # The first step is to create a new class, which we'll call # ``Sagittarius`` and make it a subclass of # `~astropy.coordinates.BaseCoordinateFrame`: class Sagittarius(coord.BaseCoordinateFrame): """ A Heliocentric spherical coordinate system defined by the orbit of the Sagittarius dwarf galaxy, as described in https://ui.adsabs.harvard.edu/abs/2003ApJ...599.1082M and further explained in https://www.stsci.edu/~dlaw/Sgr/. Parameters ---------- representation : `~astropy.coordinates.BaseRepresentation` or None A representation object or None to have no data (or use the other keywords) Lambda : `~astropy.coordinates.Angle`, optional, must be keyword The longitude-like angle corresponding to Sagittarius' orbit. Beta : `~astropy.coordinates.Angle`, optional, must be keyword The latitude-like angle corresponding to Sagittarius' orbit. distance : `~astropy.units.Quantity`, optional, must be keyword The Distance for this object along the line-of-sight. pm_Lambda_cosBeta : `~astropy.units.Quantity`, optional, must be keyword The proper motion along the stream in ``Lambda`` (including the ``cos(Beta)`` factor) for this object (``pm_Beta`` must also be given). pm_Beta : `~astropy.units.Quantity`, optional, must be keyword The proper motion in Declination for this object (``pm_ra_cosdec`` must also be given). radial_velocity : `~astropy.units.Quantity`, optional, keyword-only The radial velocity of this object. """ default_representation = coord.SphericalRepresentation default_differential = coord.SphericalCosLatDifferential frame_specific_representation_info = { coord.SphericalRepresentation: [ coord.RepresentationMapping('lon', 'Lambda'), coord.RepresentationMapping('lat', 'Beta'), coord.RepresentationMapping('distance', 'distance')] } ############################################################################## # Breaking this down line-by-line, we define the class as a subclass of # `~astropy.coordinates.BaseCoordinateFrame`. Then we include a descriptive # docstring. The final lines are class-level attributes that specify the # default representation for the data, default differential for the velocity # information, and mappings from the attribute names used by representation # objects to the names that are to be used by the ``Sagittarius`` frame. In this # case we override the names in the spherical representations but don't do # anything with other representations like cartesian or cylindrical. # # Next we have to define the transformation from this coordinate system to some # other built-in coordinate system; we will use Galactic coordinates. We can do # this by defining functions that return transformation matrices, or by simply # defining a function that accepts a coordinate and returns a new coordinate in # the new system. Because the transformation to the Sagittarius coordinate # system is just a spherical rotation from Galactic coordinates, we'll just # define a function that returns this matrix. We'll start by constructing the # transformation matrix using pre-determined Euler angles and the # ``rotation_matrix`` helper function: SGR_PHI = (180 + 3.75) * u.degree # Euler angles (from Law & Majewski 2010) SGR_THETA = (90 - 13.46) * u.degree SGR_PSI = (180 + 14.111534) * u.degree # Generate the rotation matrix using the x-convention (see Goldstein) D = rotation_matrix(SGR_PHI, "z") C = rotation_matrix(SGR_THETA, "x") B = rotation_matrix(SGR_PSI, "z") A = np.diag([1.,1.,-1.]) SGR_MATRIX = matrix_product(A, B, C, D) ############################################################################## # Since we already constructed the transformation (rotation) matrix above, and # the inverse of a rotation matrix is just its transpose, the required # transformation functions are very simple: @frame_transform_graph.transform(coord.StaticMatrixTransform, coord.Galactic, Sagittarius) def galactic_to_sgr(): """ Compute the transformation matrix from Galactic spherical to heliocentric Sgr coordinates. """ return SGR_MATRIX ############################################################################## # The decorator ``@frame_transform_graph.transform(coord.StaticMatrixTransform, # coord.Galactic, Sagittarius)`` registers this function on the # ``frame_transform_graph`` as a coordinate transformation. Inside the function, # we simply return the previously defined rotation matrix. # # We then register the inverse transformation by using the transpose of the # rotation matrix (which is faster to compute than the inverse): @frame_transform_graph.transform(coord.StaticMatrixTransform, Sagittarius, coord.Galactic) def sgr_to_galactic(): """ Compute the transformation matrix from heliocentric Sgr coordinates to spherical Galactic. """ return matrix_transpose(SGR_MATRIX) ############################################################################## # Now that we've registered these transformations between ``Sagittarius`` and # `~astropy.coordinates.Galactic`, we can transform between *any* coordinate # system and ``Sagittarius`` (as long as the other system has a path to # transform to `~astropy.coordinates.Galactic`). For example, to transform from # ICRS coordinates to ``Sagittarius``, we would do: icrs = coord.SkyCoord(280.161732*u.degree, 11.91934*u.degree, frame='icrs') sgr = icrs.transform_to(Sagittarius) print(sgr) ############################################################################## # Or, to transform from the ``Sagittarius`` frame to ICRS coordinates (in this # case, a line along the ``Sagittarius`` x-y plane): sgr = coord.SkyCoord(Lambda=np.linspace(0, 2*np.pi, 128)*u.radian, Beta=np.zeros(128)*u.radian, frame='sagittarius') icrs = sgr.transform_to(coord.ICRS) print(icrs) ############################################################################## # As an example, we'll now plot the points in both coordinate systems: fig, axes = plt.subplots(2, 1, figsize=(8, 10), subplot_kw={'projection': 'aitoff'}) axes[0].set_title("Sagittarius") axes[0].plot(sgr.Lambda.wrap_at(180*u.deg).radian, sgr.Beta.radian, linestyle='none', marker='.') axes[1].set_title("ICRS") axes[1].plot(icrs.ra.wrap_at(180*u.deg).radian, icrs.dec.radian, linestyle='none', marker='.') plt.show() ############################################################################## # This particular transformation is just a spherical rotation, which is a # special case of an Affine transformation with no vector offset. The # transformation of velocity components is therefore natively supported as # well: sgr = coord.SkyCoord(Lambda=np.linspace(0, 2*np.pi, 128)*u.radian, Beta=np.zeros(128)*u.radian, pm_Lambda_cosBeta=np.random.uniform(-5, 5, 128)*u.mas/u.yr, pm_Beta=np.zeros(128)*u.mas/u.yr, frame='sagittarius') icrs = sgr.transform_to(coord.ICRS) print(icrs) fig, axes = plt.subplots(3, 1, figsize=(8, 10), sharex=True) axes[0].set_title("Sagittarius") axes[0].plot(sgr.Lambda.degree, sgr.pm_Lambda_cosBeta.value, linestyle='none', marker='.') axes[0].set_xlabel(r"$\Lambda$ [deg]") axes[0].set_ylabel( fr"$\mu_\Lambda \, \cos B$ [{sgr.pm_Lambda_cosBeta.unit.to_string('latex_inline')}]") axes[1].set_title("ICRS") axes[1].plot(icrs.ra.degree, icrs.pm_ra_cosdec.value, linestyle='none', marker='.') axes[1].set_ylabel( fr"$\mu_\alpha \, \cos\delta$ [{icrs.pm_ra_cosdec.unit.to_string('latex_inline')}]") axes[2].set_title("ICRS") axes[2].plot(icrs.ra.degree, icrs.pm_dec.value, linestyle='none', marker='.') axes[2].set_xlabel("RA [deg]") axes[2].set_ylabel( fr"$\mu_\delta$ [{icrs.pm_dec.unit.to_string('latex_inline')}]") plt.show()
{ "content_hash": "17299910f538dbdc0ddfc451b334dc06", "timestamp": "", "source": "github", "line_count": 241, "max_line_length": 98, "avg_line_length": 43.82572614107884, "alnum_prop": 0.6618064760462034, "repo_name": "StuartLittlefair/astropy", "id": "1c5724d4e121ecebcf258121e9d99c0299b3222f", "size": "10562", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "examples/coordinates/plot_sgr-coordinate-frame.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "11034753" }, { "name": "C++", "bytes": "47001" }, { "name": "Cython", "bytes": "78631" }, { "name": "HTML", "bytes": "1172" }, { "name": "Lex", "bytes": "183333" }, { "name": "M4", "bytes": "18757" }, { "name": "Makefile", "bytes": "52457" }, { "name": "Python", "bytes": "12224600" }, { "name": "Shell", "bytes": "17024" }, { "name": "TeX", "bytes": "853" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('beekeepers', '0009_apiary_uniquetogether'), ] operations = [ migrations.RemoveField( model_name='usersurvey', name='email', ), migrations.AlterField( model_name='usersurvey', name='equipment', field=models.TextField(help_text='What kind of equipment do you use?Check all that apply.', blank=True), ), migrations.AlterField( model_name='usersurvey', name='income', field=models.CharField(help_text='Do you obtain income for your bees? What do you receive income from? Check all that apply.', max_length=255, blank=True), ), migrations.AlterField( model_name='usersurvey', name='organization', field=models.TextField(help_text="Are you part of a Beekeeper's Organization or Club? Which one?", null=True, blank=True), ), migrations.AlterField( model_name='usersurvey', name='phone', field=models.CharField(help_text='Phone', max_length=255, blank=True), ), migrations.AlterField( model_name='usersurvey', name='purchased_queens_sources', field=models.TextField(help_text='Please provide the state(s) where your purchased bees originated from', null=True, blank=True), ), migrations.AlterField( model_name='usersurvey', name='resistant_queens_genetics', field=models.TextField(help_text='Describe their genetics', null=True, blank=True), ), migrations.AlterField( model_name='usersurvey', name='varroa_management_trigger', field=models.TextField(help_text='How do you decide when to manage for Varroa?', null=True, blank=True), ), migrations.AlterField( model_name='usersurvey', name='total_colonies', field=models.CharField(help_text='How many total colonies do you manage?', max_length=255, choices=[('BETWEEN_1_AND_3', '1-3'), ('BETWEEN_4_AND_7', '4-7'), ('BETWEEN_8_AND_25', '8-25'), ('BETWEEN_26_AND_59', '26-59'), ('BETWEEN_60_AND_99', '60-99'), ('BETWEEN_100_AND_499', '100-499'), ('BETWEEN_500_AND_2000', '500-2000'), ('MORE_THAN_2000', 'More than 2000')]), ) ]
{ "content_hash": "035779857b0a8963b779dcc5d70414b5", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 375, "avg_line_length": 43.68421052631579, "alnum_prop": 0.5967871485943775, "repo_name": "project-icp/bee-pollinator-app", "id": "c69fffbed9436cd38fc40e7db01713bb9d1f8401", "size": "2514", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/icp/apps/beekeepers/migrations/0010_edit_usersurvey_fields_for_form_compatibility.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7443" }, { "name": "HTML", "bytes": "70570" }, { "name": "JavaScript", "bytes": "1120839" }, { "name": "Python", "bytes": "367148" }, { "name": "SCSS", "bytes": "165023" }, { "name": "Shell", "bytes": "24001" } ], "symlink_target": "" }
from statistics import mean import numpy as np import matplotlib.pyplot as plt from matplotlib import style import random style.use('ggplot') # xs = np.array([1, 2, 3, 4, 5], dtype=np.float64) # ys = np.array([5, 4, 6, 5, 6], dtype=np.float64) def create_dataset(hm, variance, step=2, correlation=False): val = 1 ys = [] for i in range(hm): y = val + random.randrange(-variance, variance) ys.append(y) if correlation and correlation == 'pos': val += step elif correlation and correlation == 'neg': val -= step xs = [i for i in range(len(ys))] return np.array(xs, dtype=np.float64), np.array(ys, dtype=np.float64) def best_fit_slope_and_intercept(xs, ys): m = (((mean(xs) * mean(ys)) - mean(xs * ys)) / ((mean(xs) * mean(xs)) - mean(xs * xs))) b = mean(ys) - m * mean(xs) return m, b def squared_error(ys_orig, ys_line): return sum((ys_line - ys_orig) * (ys_line - ys_orig)) def coefficient_of_determination(ys_orig, ys_line): y_mean_line = [mean(ys_orig) for y in ys_orig] squared_error_regr = squared_error(ys_orig, ys_line) squared_error_y_mean = squared_error(ys_orig, y_mean_line) return 1 - (squared_error_regr / squared_error_y_mean) xs, ys = create_dataset(40, 40, 2, correlation='pos') m, b = best_fit_slope_and_intercept(xs, ys) regression_line = [(m * x) + b for x in xs] predict_x = 8 propert_y = (m * predict_x) + b r_squared = coefficient_of_determination(ys, regression_line) print(r_squared) plt.scatter(xs, ys, color='#003F72', label='data') plt.scatter(predict_x, propert_y, color='g', label='predict') plt.plot(xs, regression_line, label='regression line') plt.legend(loc=4) plt.show()
{ "content_hash": "c119b50d90b4dab346f5b50c25476eae", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 73, "avg_line_length": 30.42105263157895, "alnum_prop": 0.6349480968858131, "repo_name": "mtdx/ml-algorithms", "id": "7fdbce9a682654f27bd37389fb4dd23c0401e24f", "size": "1734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "regression/linear-regression-alg.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "48168" } ], "symlink_target": "" }
import gdspy import numpy as np from phidl.geometry import ( Device, DeviceReference, _merge_floating_point_errors, _parse_layer, Polygon, _offset_polygons_parallel, ) import pp def offset( elements, distance=0.1, join_first=True, precision=1e-4, num_divisions=[1, 1], join="miter", tolerance=2, max_points=4000, layer=0, ): """ returns an element containing all polygons with an offset from phidl geometry """ if type(elements) is not list: elements = [elements] polygons_to_offset = [] for e in elements: if isinstance(e, (Device, DeviceReference)): polygons_to_offset += e.get_polygons(by_spec=False) elif isinstance(e, (Polygon, gdspy.Polygon)): polygons_to_offset.append(e) if len(polygons_to_offset) == 0: return pp.Component("offset") polygons_to_offset = _merge_floating_point_errors( polygons_to_offset, tol=precision / 1000 ) gds_layer, gds_datatype = _parse_layer(layer) if all(np.array(num_divisions) == np.array([1, 1])): p = gdspy.offset( polygons_to_offset, distance=distance, join=join, tolerance=tolerance, precision=precision, join_first=join_first, max_points=max_points, layer=gds_layer, datatype=gds_datatype, ) else: p = _offset_polygons_parallel( polygons_to_offset, distance=distance, num_divisions=num_divisions, join_first=join_first, precision=precision, join=join, tolerance=tolerance, ) D = pp.Component("offset") polygons = D.add_polygon(p, layer=layer) [ polygon.fracture(max_points=max_points, precision=precision) for polygon in polygons ] return D if __name__ == "__main__": c = pp.c.ring() co = offset(c) pp.show(co)
{ "content_hash": "1dc6faaaedaa2021e1fda61c7a21065d", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 68, "avg_line_length": 25.666666666666668, "alnum_prop": 0.5774225774225774, "repo_name": "psiq/gdsfactory", "id": "37ff66a5c6ee054eaa4d7276922c936a3c70f727", "size": "2002", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pp/offset.py", "mode": "33188", "license": "mit", "language": [ { "name": "Jupyter Notebook", "bytes": "111940" }, { "name": "Makefile", "bytes": "3712" }, { "name": "Python", "bytes": "900889" }, { "name": "Shell", "bytes": "293" }, { "name": "XS", "bytes": "10068" } ], "symlink_target": "" }
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'DMUserProfile.klass' db.add_column('accounts_dmuserprofile', 'klass', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['classes.LogicalClass'], null=True), keep_default=False) def backwards(self, orm): # Deleting field 'DMUserProfile.klass' db.delete_column('accounts_dmuserprofile', 'klass_id') models = { 'accounts.dmuserprofile': { 'Meta': {'object_name': 'DMUserProfile'}, 'awards': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'english_band_score': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}), 'english_band_type': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}), 'ethnic': ('django.db.models.fields.IntegerField', [], {}), 'gender': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'health': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '64', 'blank': 'True'}), 'high_school': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '32', 'blank': 'True'}), 'hobby': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '128', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'id_number': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'join_date': ('django.db.models.fields.DateField', [], {}), 'klass': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['classes.LogicalClass']", 'null': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'default': "'zh'", 'max_length': '5'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'major': ('django.db.models.fields.CharField', [], {'max_length': '16', 'blank': 'True'}), 'mugshot': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'nickname': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '32', 'blank': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '24', 'blank': 'True'}), 'political': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'privacy': ('django.db.models.fields.CharField', [], {'default': "'registered'", 'max_length': '15'}), 'realname': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'role': ('django.db.models.fields.IntegerField', [], {}), 'sign_line': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '128', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'profile'", 'unique': 'True', 'to': "orm['auth.User']"}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'classes.logicalclass': { 'Meta': {'object_name': 'LogicalClass'}, 'date': ('django.db.models.fields.DateField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'major': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['classes.Major']"}), 'seq': ('django.db.models.fields.IntegerField', [], {}) }, 'classes.major': { 'Meta': {'object_name': 'Major'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '16'}), 'shortname': ('django.db.models.fields.CharField', [], {'max_length': '4'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['accounts']
{ "content_hash": "10b7ad7c98736b3fa642533335141189", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 182, "avg_line_length": 72.32323232323232, "alnum_prop": 0.5409217877094972, "repo_name": "team-xue/xue", "id": "c960d22719c1000d0690814f0419c020628fdf2a", "size": "7179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xue/accounts/migrations/0013_add_class_field.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "156439" }, { "name": "JavaScript", "bytes": "549974" }, { "name": "Python", "bytes": "2293457" }, { "name": "XSLT", "bytes": "5122" } ], "symlink_target": "" }
""" WSGI config for biolabs project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "biolabs.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
{ "content_hash": "7671787a3cfe89781d9ec7f469e92c10", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 78, "avg_line_length": 27.785714285714285, "alnum_prop": 0.7737789203084833, "repo_name": "romgar/django-biolabs", "id": "888a6242fdd03e96d5afeca86a61aea74eede2e7", "size": "389", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "biolabs/wsgi.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "16187" } ], "symlink_target": "" }
import re from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from horizon import tabs from horizon.utils import memoized from horizon import workflows from openstack_dashboard import api from openstack_dashboard.dashboards.project.firewalls \ import forms as fw_forms from openstack_dashboard.dashboards.project.firewalls \ import tabs as fw_tabs from openstack_dashboard.dashboards.project.firewalls \ import workflows as fw_workflows InsertRuleToPolicy = fw_forms.InsertRuleToPolicy RemoveRuleFromPolicy = fw_forms.RemoveRuleFromPolicy UpdateFirewall = fw_forms.UpdateFirewall UpdatePolicy = fw_forms.UpdatePolicy UpdateRule = fw_forms.UpdateRule FirewallDetailsTabs = fw_tabs.FirewallDetailsTabs FirewallTabs = fw_tabs.FirewallTabs PolicyDetailsTabs = fw_tabs.PolicyDetailsTabs RuleDetailsTabs = fw_tabs.RuleDetailsTabs AddFirewall = fw_workflows.AddFirewall AddPolicy = fw_workflows.AddPolicy AddRule = fw_workflows.AddRule class IndexView(tabs.TabView): tab_group_class = (FirewallTabs) template_name = 'project/firewalls/details_tabs.html' def post(self, request, *args, **kwargs): obj_ids = request.POST.getlist('object_ids') action = request.POST['action'] obj_type = re.search('.delete([a-z]+)', action).group(1) if not obj_ids: obj_ids.append(re.search('([0-9a-z-]+)$', action).group(1)) if obj_type == 'rule': for obj_id in obj_ids: try: api.fwaas.rule_delete(request, obj_id) messages.success(request, _('Deleted rule %s') % obj_id) except Exception as e: exceptions.handle(request, _('Unable to delete rule. %s') % e) if obj_type == 'policy': for obj_id in obj_ids: try: api.fwaas.policy_delete(request, obj_id) messages.success(request, _('Deleted policy %s') % obj_id) except Exception as e: exceptions.handle(request, _('Unable to delete policy. %s') % e) if obj_type == 'firewall': for obj_id in obj_ids: try: api.fwaas.firewall_delete(request, obj_id) messages.success(request, _('Deleted firewall %s') % obj_id) except Exception as e: exceptions.handle(request, _('Unable to delete firewall. %s') % e) return self.get(request, *args, **kwargs) class AddRuleView(workflows.WorkflowView): workflow_class = AddRule template_name = "project/firewalls/addrule.html" class AddPolicyView(workflows.WorkflowView): workflow_class = AddPolicy template_name = "project/firewalls/addpolicy.html" class AddFirewallView(workflows.WorkflowView): workflow_class = AddFirewall template_name = "project/firewalls/addfirewall.html" class RuleDetailsView(tabs.TabView): tab_group_class = (RuleDetailsTabs) template_name = 'project/firewalls/details_tabs.html' class PolicyDetailsView(tabs.TabView): tab_group_class = (PolicyDetailsTabs) template_name = 'project/firewalls/details_tabs.html' class FirewallDetailsView(tabs.TabView): tab_group_class = (FirewallDetailsTabs) template_name = 'project/firewalls/details_tabs.html' class UpdateRuleView(forms.ModalFormView): form_class = UpdateRule template_name = "project/firewalls/updaterule.html" context_object_name = 'rule' success_url = reverse_lazy("horizon:project:firewalls:index") def get_context_data(self, **kwargs): context = super(UpdateRuleView, self).get_context_data(**kwargs) context['rule_id'] = self.kwargs['rule_id'] obj = self._get_object() context['page_title'] = _("Edit Rule") if obj: context['name'] = obj.name_or_id context['page_title'] = _("Edit Rule " "%(rule_name)s") % {'rule_name': obj.name} return context @memoized.memoized_method def _get_object(self, *args, **kwargs): rule_id = self.kwargs['rule_id'] try: rule = api.fwaas.rule_get(self.request, rule_id) return rule except Exception: redirect = self.success_url msg = _('Unable to retrieve rule details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): rule = self._get_object() initial = rule.get_dict() protocol = initial['protocol'] initial['protocol'] = protocol.upper() if protocol else 'ANY' initial['action'] = initial['action'].upper() return initial class UpdatePolicyView(forms.ModalFormView): form_class = UpdatePolicy template_name = "project/firewalls/updatepolicy.html" context_object_name = 'policy' success_url = reverse_lazy("horizon:project:firewalls:index") def get_context_data(self, **kwargs): context = super(UpdatePolicyView, self).get_context_data(**kwargs) context["policy_id"] = self.kwargs['policy_id'] obj = self._get_object() context['page_title'] = _("Edit Policy") if obj: context['name'] = obj.name_or_id context['page_title'] = _("Edit Policy %s") % obj.name return context @memoized.memoized_method def _get_object(self, *args, **kwargs): policy_id = self.kwargs['policy_id'] try: policy = api.fwaas.policy_get(self.request, policy_id) return policy except Exception: redirect = self.success_url msg = _('Unable to retrieve policy details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): policy = self._get_object() initial = policy.get_dict() return initial class UpdateFirewallView(forms.ModalFormView): form_class = UpdateFirewall template_name = "project/firewalls/updatefirewall.html" context_object_name = 'firewall' success_url = reverse_lazy("horizon:project:firewalls:index") def get_context_data(self, **kwargs): context = super(UpdateFirewallView, self).get_context_data(**kwargs) context["firewall_id"] = self.kwargs['firewall_id'] obj = self._get_object() context['page_title'] = _("Edit Firewall") if obj: context['name'] = obj.name context['page_title'] = _("Edit Firewall %s") % obj.name return context @memoized.memoized_method def _get_object(self, *args, **kwargs): firewall_id = self.kwargs['firewall_id'] try: firewall = api.fwaas.firewall_get(self.request, firewall_id) return firewall except Exception: redirect = self.success_url msg = _('Unable to retrieve firewall details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): firewall = self._get_object() initial = firewall.get_dict() return initial class InsertRuleToPolicyView(forms.ModalFormView): form_class = InsertRuleToPolicy template_name = "project/firewalls/insert_rule_to_policy.html" context_object_name = 'policy' success_url = reverse_lazy("horizon:project:firewalls:index") def get_context_data(self, **kwargs): context = super(InsertRuleToPolicyView, self).get_context_data(**kwargs) context["policy_id"] = self.kwargs['policy_id'] obj = self._get_object() if obj: context['name'] = obj.name_or_id return context @memoized.memoized_method def _get_object(self, *args, **kwargs): policy_id = self.kwargs['policy_id'] try: policy = api.fwaas.policy_get(self.request, policy_id) return policy except Exception: redirect = self.success_url msg = _('Unable to retrieve policy details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): policy = self._get_object() initial = policy.get_dict() initial['policy_id'] = initial['id'] return initial class RemoveRuleFromPolicyView(forms.ModalFormView): form_class = RemoveRuleFromPolicy template_name = "project/firewalls/remove_rule_from_policy.html" context_object_name = 'policy' success_url = reverse_lazy("horizon:project:firewalls:index") def get_context_data(self, **kwargs): context = super(RemoveRuleFromPolicyView, self).get_context_data(**kwargs) context["policy_id"] = self.kwargs['policy_id'] obj = self._get_object() if obj: context['name'] = obj.name_or_id return context @memoized.memoized_method def _get_object(self, *args, **kwargs): policy_id = self.kwargs['policy_id'] try: policy = api.fwaas.policy_get(self.request, policy_id) return policy except Exception: redirect = self.success_url msg = _('Unable to retrieve policy details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): policy = self._get_object() initial = policy.get_dict() initial['policy_id'] = initial['id'] return initial
{ "content_hash": "e0d5d8cd2bcdef79bd184e7259c0150f", "timestamp": "", "source": "github", "line_count": 273, "max_line_length": 78, "avg_line_length": 35.94871794871795, "alnum_prop": 0.6136132056246179, "repo_name": "AlexOugh/horizon", "id": "947f619e4eb91d14b61c963c195c8d70a233581e", "size": "10436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "openstack_dashboard/dashboards/project/firewalls/views.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1000458" }, { "name": "JavaScript", "bytes": "244031" }, { "name": "Makefile", "bytes": "6165" }, { "name": "Python", "bytes": "4545176" }, { "name": "Shell", "bytes": "18285" } ], "symlink_target": "" }
__all__ = ['registry_status'] # http://blog.codepainters.com/2012/11/20/gevent-monkey-patching-versus- # sniffer-nose/ # if 'threading' in sys.modules: # raise Exception('threading module loaded before patching!') import gevent.monkey gevent.monkey.patch_all() import socket import sys from . import storage from . import toolkit from .app import app from .lib import cache from .lib import config _config = config.load() def redis_status(): message = '' if not cache.redis_conn: cache.init() if not cache.redis_conn: return {'redis': 'unconfigured'} key = toolkit.gen_random_string() value = toolkit.gen_random_string() try: cache.redis_conn.setex(key, 5, value) if value != cache.redis_conn.get(key): message = 'Set value is different from what was received' except Exception: message = str(sys.exc_info()[1]) return {'redis': message} def storage_status(): message = '' try: _storage = storage.load(_config.storage) key = toolkit.gen_random_string() value = toolkit.gen_random_string() _storage.put_content(key, value) stored_value = _storage.get_content(key) _storage.remove(key) if value != stored_value: message = 'Set value is different from what was received' except Exception as e: message = str(e) return {'storage': message} @app.route('/_status') @app.route('/v1/_status') def registry_status(): retval = {'services': ['redis', 'storage'], 'failures': {}} retval['host'] = socket.gethostname() code = 200 jobs = [gevent.spawn(job) for job in [redis_status, storage_status]] gevent.joinall(jobs, timeout=10) for job, service in zip(jobs, retval['services']): try: value = job.get() if value[service] != '': retval['failures'].update({service: value[service]}) code = 503 except Exception as e: retval['failures'].update({service: str(e)}) code = 503 return toolkit.response(retval, code=code)
{ "content_hash": "9d0a15a3dff809c7cc93137c6e3bafaa", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 72, "avg_line_length": 29.416666666666668, "alnum_prop": 0.615675165250236, "repo_name": "glenux/contrib-docker-registry", "id": "01268671ae7d92c86a681beece80aed77305305c", "size": "2143", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docker_registry/status.py", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import sys import os import pkg_resources # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'luigi-swf' copyright = u'2014 RUN, Inc.' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. release = pkg_resources.get_distribution('luigi-swf').version # The short X.Y version. version = '.'.join(release.split('.')[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'nature' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'luigi_swfdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'luigi_swf.tex', u'luigi\\_swf Documentation', u'Author', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'luigi_swf', u'luigi_swf Documentation', [u'Author'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'luigi_swf', u'luigi_swf Documentation', u'Author', 'luigi_swf', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'luigi-swf' epub_author = u'Author' epub_publisher = u'Author' epub_copyright = u'2014 RUN, Inc.' # The basename for the epub file. It defaults to the project name. #epub_basename = u'luigi_swf' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the PIL. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True # Intersphinx intersphinx_mapping = { 'boto': ('http://boto.readthedocs.org/en/latest/', None), 'python': ('http://docs.python.org/2.7', None), 'luigi': ('http://luigi.readthedocs.org/en/latest/', None), }
{ "content_hash": "d2b7ae2a25db6f77f038d2b614c7a6e9", "timestamp": "", "source": "github", "line_count": 327, "max_line_length": 80, "avg_line_length": 31.027522935779817, "alnum_prop": 0.7032328011038833, "repo_name": "RUNDSP/luigi-swf", "id": "83cf2569b0e7248eefb537d0b8b1e4dd47ab9b9e", "size": "10568", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "docs/conf.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "73402" }, { "name": "Ruby", "bytes": "1363" }, { "name": "Shell", "bytes": "239" } ], "symlink_target": "" }
from bs4 import BeautifulSoup class Reader: def __init__(self): self.file = open("qald_5.txt","r+") content_temp = self.file.read() self.content =content_temp.replace("\n"," ") self.soup = BeautifulSoup(self.content) self.file.close() def get_parsed_queries(self): triple = [] for question in self.soup.find_all("question"): temp = [] try: sparql = str(question.query.get_text()) for strings in question.find_all("string"): if strings["lang"] == "en": query_question = str(strings.get_text()) temp.append(query_question) temp.append(sparql) answers = question.answers count_answer = 0 for answer in answers.find_all("answer"): count_answer = count_answer + 1 temp.append(count_answer) triple.append(temp) except: continue return triple
{ "content_hash": "30773efe1fb83ebf13b6df697b399e0a", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 49, "avg_line_length": 25.8125, "alnum_prop": 0.648910411622276, "repo_name": "geraltofrivia/natural-language-queries-classification", "id": "39643e0491da4309f81b622e72f73aebb6eaf825", "size": "826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "reader.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "5688" } ], "symlink_target": "" }
from setuptools import setup, find_packages ''' Created on 2014/12/02 @author: user ''' setup( name='mona_gui_pool', version='draft', license='The MIT License (MIT)', description='', author="Muramasa. K. Fujiwara", author_email='', url='', packages=find_packages(), )
{ "content_hash": "e9745ed6e6ddfc2571d4729eccab4361", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 43, "avg_line_length": 17.764705882352942, "alnum_prop": 0.6192052980132451, "repo_name": "GitHub-of-Muramasa/mona-gui-pool", "id": "59f9d296c7af5b7728a2f1678ff5c5e09c93afe6", "size": "324", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "setup.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "251" }, { "name": "JavaScript", "bytes": "1468" }, { "name": "Python", "bytes": "8849" } ], "symlink_target": "" }
from collections import defaultdict import kevlar from kevlar.intervalforest import IntervalForest import sys def populate_index_from_bed(instream): index = IntervalForest() for line in instream: if line.startswith('#') or line.strip() == '': continue values = line.strip().split() chrom = values[0] start, end = [int(coord) for coord in values[1:3]] strrepr = '{:s}:{:d}-{:d}'.format(chrom, start, end) index.insert(chrom, start, end, strrepr) return index def compact(variants, index, delta=10): """Compact variants by call class Variant calls labeled with the same `CALLCLASS` attribute were predicted from the same partition (set of reads). While more than one of these may indeed be true variants with respect to the reference, we expect only one *de novo* variant per partition. This function assumes the variant calls are sorted by likelihood score (the `LIKESCORE` attribute in kevlar). Any call that does not pass filters is ignored. Then, for each CALLCLASS with multiple passing calls, all calls are discarded except for the one matching the true variant. If the CALLCLASS has no calls matching a true variant, all of the calls are discarded except for the highest scoring call. """ variants_by_class = defaultdict(list) calls = list() for varcall in variants: if varcall.filterstr != 'PASS': continue callclass = varcall.attribute('CALLCLASS') if callclass is None: calls.append(varcall) else: variants_by_class[callclass].append(varcall) for callclass, calllist in variants_by_class.items(): nmatches = 0 match = None for varcall in calllist: hits = index.query(varcall.seqid, varcall.position, delta=delta) if hits == set(): continue else: nmatches += 1 if match is None: match = varcall if nmatches == 0: calllist[0].annotate('EVAL', 'False') calls.append(calllist[0]) else: assert nmatches > 0, nmatches if nmatches > 1: print('WARNING: found', nmatches, 'matches for CALLCLASS', callclass, file=sys.stderr) match.annotate('EVAL', 'True') calls.append(match) calls.sort(key=lambda c: float(c.attribute('LIKESCORE')), reverse=True) calls = [c for c in calls if float(c.attribute('LIKESCORE')) > 0.0] return calls
{ "content_hash": "162409e0ac3cc0966fe0926ebc898f42", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 79, "avg_line_length": 37.22857142857143, "alnum_prop": 0.6193399846508059, "repo_name": "dib-lab/kevlar", "id": "1e25e9fe5e5a6d10fd19d9ca6f3d08ce0832a5f2", "size": "2972", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kevlar/evaluate.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3342" }, { "name": "C++", "bytes": "16738" }, { "name": "Dockerfile", "bytes": "1538" }, { "name": "Makefile", "bytes": "2648" }, { "name": "Python", "bytes": "488299" }, { "name": "Shell", "bytes": "4576" } ], "symlink_target": "" }
from __future__ import absolute_import, division, print_function from abc import ABCMeta, abstractproperty, abstractmethod import numpy as np from glue.external import six from glue.core.exceptions import IncompatibleAttribute from glue.core.layer_artist import MatplotlibLayerArtist, ChangedTrigger __all__ = ['HistogramLayerArtist'] @six.add_metaclass(ABCMeta) class HistogramLayerBase(object): lo = abstractproperty() # lo-cutoff for bin counting hi = abstractproperty() # hi-cutoff for bin counting nbins = abstractproperty() # number of bins xlog = abstractproperty() # whether to space bins logarithmically @abstractmethod def get_data(self): """ Return array of bin counts """ pass class HistogramLayerArtist(MatplotlibLayerArtist, HistogramLayerBase): _property_set = MatplotlibLayerArtist._property_set + 'lo hi nbins xlog'.split() lo = ChangedTrigger(0) hi = ChangedTrigger(1) nbins = ChangedTrigger(10) xlog = ChangedTrigger(False) att = ChangedTrigger() def __init__(self, layer, axes): super(HistogramLayerArtist, self).__init__(layer, axes) self.ylog = False self.cumulative = False self.normed = False self.y = np.array([]) self.x = np.array([]) self._y = np.array([]) self._scale_state = None def get_data(self): return self.x, self.y def clear(self): super(HistogramLayerArtist, self).clear() self.x = np.array([]) self.y = np.array([]) self._y = np.array([]) def _calculate_histogram(self): """Recalculate the histogram, creating new patches""" self.clear() try: data = self.layer[self.att].ravel() if not np.isfinite(data).any(): return False except IncompatibleAttribute as exc: self.disable_invalid_attributes(*exc.args) return False if data.size == 0: return if self.lo > np.nanmax(data) or self.hi < np.nanmin(data): return if self.xlog: data = np.log10(data) rng = [np.log10(self.lo), np.log10(self.hi)] else: rng = self.lo, self.hi nbinpatch = self._axes.hist(data, bins=int(self.nbins), range=rng) self._y, self.x, self.artists = nbinpatch return True def _scale_histogram(self): """Modify height of bins to match ylog, cumulative, and norm""" if self.x.size == 0: return y = self._y.astype(np.float) dx = self.x[1] - self.x[0] if self.normed: div = y.sum() * dx if div == 0: div = 1 y /= div if self.cumulative: y = y.cumsum() y /= y.max() self.y = y bottom = 0 if not self.ylog else 1e-100 for a, y in zip(self.artists, y): a.set_height(y) x, y = a.get_xy() a.set_xy((x, bottom)) def _check_scale_histogram(self): """ If needed, rescale histogram to match cumulative/log/normed state. """ state = (self.normed, self.ylog, self.cumulative) if state == self._scale_state: return self._scale_state = state self._scale_histogram() def update(self, view=None): """Sync plot. The _change flag tracks whether the histogram needs to be recalculated. If not, the properties of the existing artists are updated """ self._check_subset_state_changed() if self._changed: if not self._calculate_histogram(): return self._changed = False self._scale_state = None self._check_scale_histogram() self._sync_style() def _sync_style(self): """Update visual properties""" style = self.layer.style for artist in self.artists: artist.set_facecolor(style.color) artist.set_alpha(style.alpha) artist.set_zorder(self.zorder) artist.set_visible(self.visible and self.enabled)
{ "content_hash": "2a75a5cadb3c5d64445d4f201aebcc7e", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 84, "avg_line_length": 30.091549295774648, "alnum_prop": 0.5642405803884858, "repo_name": "saimn/glue", "id": "8b8231fea05d25661473edf27480de61f8522a2e", "size": "4273", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "glue/viewers/histogram/layer_artist.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "1609137" }, { "name": "Shell", "bytes": "1603" } ], "symlink_target": "" }
import unittest from Src.BioAnalyzer.GenePrioritization.Steps.DifferentialAnalysis.Measurers.LocalBetaValueMeasurer import \ LocalBetaValueMeasurer from Src.BioDataManagement.CrossCutting.DTOs.DnaMethylationLevelStatusDto import DnaMethylationLevelStatusDto class LocalBetaValueMeasurerTest(unittest.TestCase): def test_calculate(self): measurer = LocalBetaValueMeasurer() resp = measurer.calculate(1, 0.8715999999999999, 0.9187000000000001) self.assertEqual(resp.element_id, 1) self.assertFalse(resp.is_highly_significant) self.assertEqual(resp.status, DnaMethylationLevelStatusDto.Hypomethylation) self.assertEqual(resp.value, -0.04710000000000014) resp = measurer.calculate(1, 0.5508, 0.04830000000000001) self.assertEqual(resp.element_id, 1) self.assertTrue(resp.is_highly_significant) self.assertEqual(resp.status, DnaMethylationLevelStatusDto.Hypermethylated) self.assertEqual(resp.value, 0.5025) resp = measurer.calculate(1, 0.15105, 0.38334999999999997) self.assertEqual(resp.element_id, 1) self.assertTrue(resp.is_highly_significant) self.assertEqual(resp.status, DnaMethylationLevelStatusDto.Hypermethylated) self.assertEqual(resp.value, -0.23229999999999998) resp = measurer.calculate(1, 0.0000, 0.0000) self.assertEqual(resp.element_id, 1) self.assertFalse(resp.is_highly_significant) self.assertEqual(resp.status, DnaMethylationLevelStatusDto.Hypomethylation) self.assertEqual(resp.value, 0) if __name__ == '__main__': unittest.main()
{ "content_hash": "a69635234cbea2f56e303ba2347abc13", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 109, "avg_line_length": 42, "alnum_prop": 0.7387057387057387, "repo_name": "cemarchi/biosphere", "id": "03402433a5d38e19ea2fb166fc889a55de642348", "size": "1638", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tests/BioAnalyzer/Analysis/GenePrioritization/Steps/DifferentialAnalysis/Measurers/LocalBetaValueMeasurerTest.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "822707" } ], "symlink_target": "" }
#!/usr/bin/python # # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Does google-lint on c++ files. The goal of this script is to identify places in the code that *may* be in non-compliance with google style. It does not attempt to fix up these problems -- the point is to educate. It does also not attempt to find all problems, or to ensure that everything it does find is legitimately a problem. In particular, we can get very confused by ' # Matches multi-line C style comments. # This RE is a little bit more complicated than one might expect, because we # have to take care of space removals tools so we can handle comments inside # statements better. # The current rule is: We only clear spaces from both sides when we're at the # end of the line. Otherwise, we try to remove spaces from the right side, # if this doesn't work we try on left side but only if there's a non-character # on the right. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' + _RE_PATTERN_C_COMMENTS + r'\s+|' + r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' + _RE_PATTERN_C_COMMENTS + r')') def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 def CleanseRawStrings(raw_lines): """Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings. """ delimiter = None lines_without_raw_strings = [] for line in raw_lines: if delimiter: # Inside a raw string, look for the end end = line.find(delimiter) if end >= 0: # Found the end of the string, match leading space for this # line and resume copying the original lines, and also insert # a "" on the last line. leading_space = Match(r'^(\s*)\S', line) line = leading_space.group(1) + '""' + line[end + len(delimiter):] delimiter = None else: # Haven't found the end yet, append a blank line. line = '""' # Look for beginning of a raw string, and replace them with # empty strings. This is done in a loop to handle multiple raw # strings on the same line. while delimiter is None: # Look for beginning of a raw string. # See 2.14.15 [lex.string] for syntax. matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) if matched: delimiter = ')' + matched.group(2) + '"' end = matched.group(3).find(delimiter) if end >= 0: # Raw string ended on same line line = (matched.group(1) + '""' + matched.group(3)[end + len(delimiter):]) delimiter = None else: # Start of a multi-line raw string line = matched.group(1) + '""' else: break lines_without_raw_strings.append(line) # TODO(unknown): if delimiter is not None here, we might want to # emit a warning for unterminated string. return lines_without_raw_strings def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines) def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines) def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '// dummy' def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1 def CleanseComments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ commentpos = line.find('//') if commentpos != -1 and not IsCppString(line[:commentpos]): line = line[:commentpos].rstrip() # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) class CleansedLines(object): """Holds 3 copies of all lines with different preprocessing applied to them. 1) elided member contains lines without strings and comments, 2) lines member contains lines without comments, and 3) raw_lines member contains all the lines without processing. All these three members are of <type 'list'>, and of the same length. """ def __init__(self, lines): self.elided = [] self.lines = [] self.raw_lines = lines self.num_lines = len(lines) self.lines_without_raw_strings = CleanseRawStrings(lines) for linenum in range(len(self.lines_without_raw_strings)): self.lines.append(CleanseComments( self.lines_without_raw_strings[linenum])) elided = self._CollapseStrings(self.lines_without_raw_strings[linenum]) self.elided.append(CleanseComments(elided)) def NumLines(self): """Returns the number of lines represented.""" return self.num_lines @staticmethod def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if _RE_PATTERN_INCLUDE.match(elided): return elided # Remove escaped characters first to make quote/single quote collapsing # basic. Things that look like escaped characters shouldn't occur # outside of strings and chars. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) # Replace quoted strings and digit separators. Both single quotes # and double quotes are processed in the same loop, otherwise # nested quotes wouldn't work. collapsed = '' while True: # Find the first quote character match = Match(r'^([^\'"]*)([\'"])(.*)$', elided) if not match: collapsed += elided break head, quote, tail = match.groups() if quote == '"': # Collapse double quoted strings second_quote = tail.find('"') if second_quote >= 0: collapsed += head + '""' elided = tail[second_quote + 1:] else: # Unmatched double quote, don't bother processing the rest # of the line since this is probably a multiline string. collapsed += elided break else: # Found single quote, check nearby text to eliminate digit separators. # # There is no special handling for floating point here, because # the integer/fractional/exponent parts would all be parsed # correctly as long as there are digits on both sides of the # separator. So we are fine as long as we don't see something # like "0.'3" (gcc 4.9.0 will not allow this literal). if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head): match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail) collapsed += head + match_literal.group(1).replace("'", '') elided = match_literal.group(2) else: second_quote = tail.find('\'') if second_quote >= 0: collapsed += head + "''" elided = tail[second_quote + 1:] else: # Unmatched single quote collapsed += elided break return collapsed def FindEndOfExpressionInLine(line, startpos, stack): """Find the position just after the end of current parenthesized expression. Args: line: a CleansedLines line. startpos: start searching at this position. stack: nesting stack at startpos. Returns: On finding matching end: (index just after matching end, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at end of this line) """ for i in xrange(startpos, len(line)): char = line[i] if char in '([{': # Found start of parenthesized expression, push to expression stack stack.append(char) elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator if stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) elif i > 0 and Search(r'\boperator\s*$', line[0:i]): # operator<, don't add to stack continue else: # Tentative start of template argument list stack.append('<') elif char in ')]}': # Found end of parenthesized expression. # # If we are currently expecting a matching '>', the pending '<' # must have been an operator. Remove them from expression stack. while stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) if ((stack[-1] == '(' and char == ')') or (stack[-1] == '[' and char == ']') or (stack[-1] == '{' and char == '}')): stack.pop() if not stack: return (i + 1, None) else: # Mismatched parentheses return (-1, None) elif char == '>': # Found potential end of template argument list. # Ignore "->" and operator functions if (i > 0 and (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))): continue # Pop the stack if there is a matching '<'. Otherwise, ignore # this '>' since it must be an operator. if stack: if stack[-1] == '<': stack.pop() if not stack: return (i + 1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '>', the matching '<' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) # Did not find end of expression or unbalanced parentheses on this line return (-1, stack) def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): return (line, clean_lines.NumLines(), -1) # Check first line (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while stack and linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) if end_pos > -1: return (line, linenum, end_pos) # Did not find end of expression before end of file, give up return (line, clean_lines.NumLines(), -1) def FindStartOfExpressionInLine(line, endpos, stack): """Find position at the matching start of current expression. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. stack: nesting stack at endpos. Returns: On finding matching start: (index at matching start, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at beginning of this line) """ i = endpos while i >= 0: char = line[i] if char in ')]}': # Found end of expression, push to expression stack stack.append(char) elif char == '>': # Found potential end of template argument list. # # Ignore it if it's a "->" or ">=" or "operator>" if (i > 0 and (line[i - 1] == '-' or Match(r'\s>=\s', line[i - 1:]) or Search(r'\boperator\s*$', line[0:i]))): i -= 1 else: stack.append('>') elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator i -= 1 else: # If there is a matching '>', we can pop the expression stack. # Otherwise, ignore this '<' since it must be an operator. if stack and stack[-1] == '>': stack.pop() if not stack: return (i, None) elif char in '([{': # Found start of expression. # # If there are any unmatched '>' on the stack, they must be # operators. Remove those. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) if ((char == '(' and stack[-1] == ')') or (char == '[' and stack[-1] == ']') or (char == '{' and stack[-1] == '}')): stack.pop() if not stack: return (i, None) else: # Mismatched parentheses return (-1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '<', the matching '>' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) i -= 1 return (-1, stack) def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if line[pos] not in ')}]>': return (line, 0, -1) # Check last line (start_pos, stack) = FindStartOfExpressionInLine(line, pos, []) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while stack and linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack) if start_pos > -1: return (line, linenum, start_pos) # Did not find start of expression before beginning of file, give up return (line, 0, -1) def CheckForCopyright(filename, lines, error): """Logs an error if no Copyright message appears at the top of the file.""" # We'll say it should occur by line 10. Don't forget there's a # dummy line at the front. for line in xrange(1, min(len(lines), 11)): if re.search(r'Copyright', lines[line], re.I): break else: # means no copyright line was found error(filename, 0, 'legal/copyright', 5, 'No copyright message found. ' 'You should have a line: "Copyright [year] <Copyright Owner>"') def GetIndentLevel(line): """Return the number of leading spaces in line. Args: line: A string to check. Returns: An integer count of leading spaces, possibly zero. """ indent = Match(r'^( *)\S', line) if indent: return len(indent.group(1)) else: return 0 def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() if _root: file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' def CheckForHeaderGuard(filename, lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # Don't check for header guards if there are error suppression # comments somewhere in this file. # # Because this is silencing a warning for a nonexistent line, we # only support the very specific NOLINT(build/header_guard) syntax, # and not the general NOLINT or NOLINT(*) syntax. for i in lines: if Search(r'//\s*NOLINT\(build/header_guard\)', i): return cppvar = GetHeaderGuardCPPVariable(filename) ifndef = None ifndef_linenum = 0 define = None endif = None endif_linenum = 0 for linenum, line in enumerate(lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return if not define: error(filename, 0, 'build/header_guard', 5, 'No #define header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) if define != ifndef: error(filename, 0, 'build/header_guard', 5, '#ifndef and #define don\'t match, suggested CPP variable is: %s' % cppvar) return if endif != ('#endif // %s' % cppvar): error_level = 0 if endif != ('#endif // %s' % (cppvar + '_')): error_level = 5 ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum, error) error(filename, endif_linenum, 'build/header_guard', error_level, '#endif line should be "#endif // %s"' % cppvar) def CheckForBadCharacters(filename, lines, error): """Logs an error for each line containing bad characters. Two kinds of bad characters: 1. Unicode replacement characters: These indicate that either the file contained invalid UTF-8 (likely) or Unicode replacement characters (which it shouldn't). Note that it's possible for this to throw off line numbering if the invalid UTF-8 occurred adjacent to a newline. 2. NUL bytes. These are problematic for some tools. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ for linenum, line in enumerate(lines): if u'\ufffd' in line: error(filename, linenum, 'readability/utf8', 5, 'Line contains invalid UTF-8 (or Unicode replacement character).') if '\0' in line: error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.') def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.') # (non-threadsafe name, thread-safe alternative, validation pattern) # # The validation pattern is used to eliminate false positives such as: # _rand(); // false positive due to substring match. # ->rand(); // some member function rand(). # ACMRandom rand(seed); // some variable named rand. # ISAACRandom rand(); // another variable named rand. # # Basically we require the return value of these functions to be used # in some expression context on the same line by matching on some # operator before the function name. This eliminates constructors and # member function calls. _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)' _THREADING_LIST = ( ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'), ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'), ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'), ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'), ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'), ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'), ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'), ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'), ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'), ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'), ('strtok(', 'strtok_r(', _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'), ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'), ) def CheckPosixThreading(filename, clean_lines, linenum, error): """Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST: # Additional pattern matching check to confirm that this is the # function we are looking for if Search(pattern, line): error(filename, linenum, 'runtime/threadsafe_fn', 2, 'Consider using ' + multithread_safe_func + '...) instead of ' + single_thread_func + '...) for improved thread safety.') def CheckVlogArguments(filename, clean_lines, linenum, error): """Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): error(filename, linenum, 'runtime/vlog', 5, 'VLOG() should be used with numeric verbosity level. ' 'Use LOG() if you want symbolic severity levels.') # Matches invalid increment: *count++, which moves pointer instead of # incrementing a value. _RE_PATTERN_INVALID_INCREMENT = re.compile( r'^\s*\*\w+(\+\+|--);') def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).') def IsMacroDefinition(clean_lines, linenum): if Search(r'^#define', clean_lines[linenum]): return True if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]): return True return False def IsForwardClassDeclaration(clean_lines, linenum): return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum]) class _BlockInfo(object): """Stores information about a generic block of code.""" def __init__(self, seen_open_brace): self.seen_open_brace = seen_open_brace self.open_parentheses = 0 self.inline_asm = _NO_ASM self.check_namespace_indentation = False def CheckBegin(self, filename, clean_lines, linenum, error): """Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass def CheckEnd(self, filename, clean_lines, linenum, error): """Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass def IsBlockInfo(self): """Returns true if this block is a _BlockInfo. This is convenient for verifying that an object is an instance of a _BlockInfo, but not an instance of any of the derived classes. Returns: True for this class, False for derived classes. """ return self.__class__ == _BlockInfo class _ExternCInfo(_BlockInfo): """Stores information about an 'extern "C"' block.""" def __init__(self): _BlockInfo.__init__(self, True) class _ClassInfo(_BlockInfo): """Stores information about a class.""" def __init__(self, name, class_or_struct, clean_lines, linenum): _BlockInfo.__init__(self, False) self.name = name self.starting_linenum = linenum self.is_derived = False self.check_namespace_indentation = True if class_or_struct == 'struct': self.access = 'public' self.is_struct = True else: self.access = 'private' self.is_struct = False # Remember initial indentation level for this class. Using raw_lines here # instead of elided to account for leading comments. self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum]) # Try to find the end of the class. This will be confused by things like: # class A { # } *x = { ... # # But it's still good enough for CheckSectionSpacing. self.last_line = 0 depth = 0 for i in range(linenum, clean_lines.NumLines()): line = clean_lines.elided[i] depth += line.count('{') - line.count('}') if not depth: self.last_line = i break def CheckBegin(self, filename, clean_lines, linenum, error): # Look for a bare ':' if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): self.is_derived = True def CheckEnd(self, filename, clean_lines, linenum, error): # Check that closing brace is aligned with beginning of the class. # Only do this if the closing brace is indented by only whitespaces. # This means we will not check single-line class definitions. indent = Match(r'^( *)\}', clean_lines.elided[linenum]) if indent and len(indent.group(1)) != self.class_indent: if self.is_struct: parent = 'struct ' + self.name else: parent = 'class ' + self.name error(filename, linenum, 'whitespace/indent', 3, 'Closing brace should be aligned with beginning of %s' % parent) class _NamespaceInfo(_BlockInfo): """Stores information about a namespace.""" def __init__(self, name, linenum): _BlockInfo.__init__(self, False) self.name = name or '' self.starting_linenum = linenum self.check_namespace_indentation = True def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): # If "// namespace anonymous" or "// anonymous namespace (more text)", # mention "// anonymous namespace" as an acceptable form if Match(r'}.*\b(namespace anonymous|anonymous namespace)\b', line): error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"' ' or "// anonymous namespace"') else: error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"') class _PreprocessorInfo(object): """Stores checkpoints of nesting stacks when #if/#else is seen.""" def __init__(self, stack_before_if): # The entire nesting stack before #if self.stack_before_if = stack_before_if # The entire nesting stack up to #else self.stack_before_else = [] # Whether we have already seen #else or #elif self.seen_else = False class NestingState(object): """Holds states related to parsing braces.""" def __init__(self): # Stack for tracking all braces. An object is pushed whenever we # see a "{", and popped when we see a "}". Only 3 types of # objects are possible: # - _ClassInfo: a class or struct. # - _NamespaceInfo: a namespace. # - _BlockInfo: some other type of block. self.stack = [] # Top of the previous stack before each Update(). # # Because the nesting_stack is updated at the end of each line, we # had to do some convoluted checks to find out what is the current # scope at the beginning of the line. This check is simplified by # saving the previous top of nesting stack. # # We could save the full stack, but we only need the top. Copying # the full nesting stack would slow down cpplint by ~10%. self.previous_stack_top = [] # Stack of _PreprocessorInfo objects. self.pp_stack = [] def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo) def InExternC(self): """Check if we are currently one level inside an 'extern "C"' block. Returns: True if top of the stack is an extern block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _ExternCInfo) def InClassDeclaration(self): """Check if we are currently one level inside a class or struct declaration. Returns: True if top of the stack is a class/struct, False otherwise. """ return self.stack and isinstance(self.stack[-1], _ClassInfo) def InAsmBlock(self): """Check if we are currently one level inside an inline ASM block. Returns: True if the top of the stack is a block containing inline ASM. """ return self.stack and self.stack[-1].inline_asm != _NO_ASM def InTemplateArgumentList(self, clean_lines, linenum, pos): """Check if current position is inside template argument list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: position just after the suspected template argument. Returns: True if (linenum, pos) is inside template arguments. """ while linenum < clean_lines.NumLines(): # Find the earliest character that might indicate a template argument line = clean_lines.elided[linenum] match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) if not match: linenum += 1 pos = 0 continue token = match.group(1) pos += len(match.group(0)) # These things do not look like template argument list: # class Suspect { # class Suspect x; } if token in ('{', '}', ';'): return False # These things look like template argument list: # template <class Suspect> # template <class Suspect = default_value> # template <class Suspect[]> # template <class Suspect...> if token in ('>', '=', '[', ']', '.'): return True # Check if token is an unmatched '<'. # If not, move on to the next character. if token != '<': pos += 1 if pos >= len(line): linenum += 1 pos = 0 continue # We can't be sure if we just find a single '<', and need to # find the matching '>'. (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) if end_pos < 0: # Not sure if template argument list or syntax error in file return False linenum = end_line pos = end_pos return False def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass # TODO(unknown): Update() is too long, but we will refactor later. def Update(self, filename, clean_lines, linenum, error): """Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remember top of the previous nesting stack. # # The stack is always pushed/popped and not modified in place, so # we can just do a shallow copy instead of copy.deepcopy. Using # deepcopy would slow down cpplint by ~28%. if self.stack: self.previous_stack_top = self.stack[-1] else: self.previous_stack_top = None # Update pp_stack self.UpdatePreprocessor(line) # Count parentheses. This is to avoid adding struct arguments to # the nesting stack. if self.stack: inner_block = self.stack[-1] depth_change = line.count('(') - line.count(')') inner_block.open_parentheses += depth_change # Also check if we are starting or ending an inline assembly block. if inner_block.inline_asm in (_NO_ASM, _END_ASM): if (depth_change != 0 and inner_block.open_parentheses == 1 and _MATCH_ASM.match(line)): # Enter assembly block inner_block.inline_asm = _INSIDE_ASM else: # Not entering assembly block. If previous line was _END_ASM, # we will now shift to _NO_ASM state. inner_block.inline_asm = _NO_ASM elif (inner_block.inline_asm == _INSIDE_ASM and inner_block.open_parentheses == 0): # Exit assembly block inner_block.inline_asm = _END_ASM # Consume namespace declaration at the beginning of the line. Do # this in a loop so that we catch same line declarations like this: # namespace proto2 { namespace bridge { class MessageSet; } } while True: # Match start of namespace. The "\b\s*" below catches namespace # declarations even if it weren't followed by a whitespace, this # is so that we don't confuse our namespace checker. The # missing spaces will be flagged by CheckSpacing. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) if not namespace_decl_match: break new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) self.stack.append(new_namespace) line = namespace_decl_match.group(2) if line.find('{') != -1: new_namespace.seen_open_brace = True line = line[line.find('{') + 1:] # Look for a class declaration in whatever is left of the line # after parsing namespaces. The regexp accounts for decorated classes # such as in: # class LOCKABLE API Object { # }; class_decl_match = Match( r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?' r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))' r'(.*)$', line) if (class_decl_match and (not self.stack or self.stack[-1].open_parentheses == 0)): # We do not want to accept classes that are actually template arguments: # template <class Ignore1, # class Ignore2 = Default<Args>, # template <Args> class Ignore3> # void Function() {}; # # To avoid template argument cases, we scan forward and look for # an unmatched '>'. If we see one, assume we are inside a # template argument list. end_declaration = len(class_decl_match.group(1)) if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): self.stack.append(_ClassInfo( class_decl_match.group(3), class_decl_match.group(2), clean_lines, linenum)) line = class_decl_match.group(4) # If we have not yet seen the opening brace for the innermost block, # run checks here. if not self.SeenOpenBrace(): self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) # Update access control if we are inside a class/struct if self.stack and isinstance(self.stack[-1], _ClassInfo): classinfo = self.stack[-1] access_match = Match( r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' r':(?:[^:]|$)', line) if access_match: classinfo.access = access_match.group(2) # Check that access keywords are indented +1 space. Skip this # check if the keywords are not preceded by whitespaces. indent = access_match.group(1) if (len(indent) != classinfo.class_indent + 1 and Match(r'^\s*$', indent)): if classinfo.is_struct: parent = 'struct ' + classinfo.name else: parent = 'class ' + classinfo.name slots = '' if access_match.group(3): slots = access_match.group(3) error(filename, linenum, 'whitespace/indent', 3, '%s%s: should be indented +1 space inside %s' % ( access_match.group(2), slots, parent)) # Consume braces or semicolons from what's left of the line while True: # Match first brace, semicolon, or closed parenthesis. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) if not matched: break token = matched.group(1) if token == '{': # If namespace or class hasn't seen a opening brace yet, mark # namespace/class head as complete. Push a new block onto the # stack otherwise. if not self.SeenOpenBrace(): self.stack[-1].seen_open_brace = True elif Match(r'^extern\s*"[^"]*"\s*\{', line): self.stack.append(_ExternCInfo()) else: self.stack.append(_BlockInfo(True)) if _MATCH_ASM.match(line): self.stack[-1].inline_asm = _BLOCK_ASM elif token == ';' or token == ')': # If we haven't seen an opening brace yet, but we already saw # a semicolon, this is probably a forward declaration. Pop # the stack for these. # # Similarly, if we haven't seen an opening brace yet, but we # already saw a closing parenthesis, then these are probably # function arguments with extra "class" or "struct" keywords. # Also pop these stack for these. if not self.SeenOpenBrace(): self.stack.pop() else: # token == '}' # Perform end of block checks and pop the stack. if self.stack: self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) self.stack.pop() line = matched.group(2) def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None def CheckCompletedBlocks(self, filename, error): """Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, 'Failed to find complete declaration of namespace %s' % obj.name) def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage class (static, extern, typedef, etc) should be first.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. Also look for # non-single-argument constructors which are also technically valid, but # strongly suggest something is wrong. explicit_constructor_match = Match( r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*' r'\(((?:[^()]|\([^()]*\))*)\)' % re.escape(base_classname), line) if explicit_constructor_match: is_marked_explicit = explicit_constructor_match.group(1) if not explicit_constructor_match.group(2): constructor_args = [] else: constructor_args = explicit_constructor_match.group(2).split(',') # collapse arguments so that commas in template parameter lists and function # argument parameter lists don't split arguments in two i = 0 while i < len(constructor_args): constructor_arg = constructor_args[i] while (constructor_arg.count('<') > constructor_arg.count('>') or constructor_arg.count('(') > constructor_arg.count(')')): constructor_arg += ',' + constructor_args[i + 1] del constructor_args[i + 1] constructor_args[i] = constructor_arg i += 1 defaulted_args = [arg for arg in constructor_args if '=' in arg] noarg_constructor = (not constructor_args or # empty arg list # 'void' arg specifier (len(constructor_args) == 1 and constructor_args[0].strip() == 'void')) onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg not noarg_constructor) or # all but at most one arg defaulted (len(constructor_args) >= 1 and not noarg_constructor and len(defaulted_args) >= len(constructor_args) - 1)) initializer_list_constructor = bool( onearg_constructor and Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0])) copy_constructor = bool( onearg_constructor and Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&' % re.escape(base_classname), constructor_args[0].strip())) if (not is_marked_explicit and onearg_constructor and not initializer_list_constructor and not copy_constructor): if defaulted_args: error(filename, linenum, 'runtime/explicit', 5, 'Constructors callable with one argument ' 'should be marked explicit.') else: error(filename, linenum, 'runtime/explicit', 5, 'Single-parameter constructors should be marked explicit.') elif is_marked_explicit and not onearg_constructor: if noarg_constructor: error(filename, linenum, 'runtime/explicit', 5, 'Zero-parameter constructors should not be marked explicit.') else: error(filename, linenum, 'runtime/explicit', 0, 'Constructors that require multiple arguments ' 'should not be marked explicit.') def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)): # TODO(unknown): Space after an operator function seem to be a common # error, silence those for now by restricting them to highest verbosity. if Search(r'\boperator_*\b', line): error(filename, linenum, 'whitespace/parens', 0, 'Extra space before ( in function call') else: error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )') def IsBlankLine(line): """Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank. """ return not line or line.isspace() def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error): is_namespace_indent_item = ( len(nesting_state.stack) > 1 and nesting_state.stack[-1].check_namespace_indentation and isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and nesting_state.previous_stack_top == nesting_state.stack[-2]) if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, clean_lines.elided, line): CheckItemIndentationInNamespace(filename, clean_lines.elided, line, error) def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in xrange(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count() # Count non-blank/non-comment lines. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') def CheckComment(line, filename, linenum, next_line_start, error): """Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. error: The function to call with any errors found. """ commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if (line.count('"', 0, commentpos) - line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes # Allow one space for new scopes, two spaces otherwise: if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # Checks for common mistakes in TODO comments. comment = line[commentpos:] match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space') # If the comment contains an alphanumeric character, there # should be a space somewhere between it and the //. if Match(r'//[^ ]*\w', comment): error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != 'private': error(filename, linenum, 'readability/constructors', 3, '%s must be in the private: section' % matched.group(1)) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw = clean_lines.lines_without_raw_strings line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' # # Skip all the blank line checks if we are immediately inside a # namespace body. In other words, don't issue blank line warnings # for this block: # namespace { # # } # # A warning about missing end of namespace comments will be issued instead. # # Also skip blank line checks for 'extern "C"' blocks, which are formatted # like namespaces. if (IsBlankLine(line) and not nesting_state.InNamespaceBody() and not nesting_state.InExternC()): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Redundant blank line at the start of a code block ' 'should be deleted.') # Ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Redundant blank line at the end of a code block ' 'should be deleted.') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, check comments next_line_start = 0 if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] next_line_start = len(next_line) - len(next_line.lstrip()) CheckComment(line, filename, linenum, next_line_start, error) # get rid of comments and strings line = clean_lines.elided[linenum] # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'return []() {};' if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # In range-based for, we wanted spaces before and after the colon, but # not around "::" tokens that might appear. if (Search(r'for *\(.*[^:]:[^: ]', line) or Search(r'for *\(.*[^: ]:[^:]', line)): error(filename, linenum, 'whitespace/forcolon', 2, 'Missing space around colon in range-based for loop') def CheckOperatorSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing around operators. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Don't try to do spacing checks for operator methods. Do this by # replacing the troublesome characters with something else, # preserving column position for all other characters. # # The replacement is done repeatedly to avoid false positives from # operators that call operators. while True: match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line) if match: line = match.group(1) + ('_' * len(match.group(2))) + match.group(3) else: break # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # # Check <= and >= first to avoid false positives with < and >, then # check non-include lines for spacing around < and >. # # If the operator is followed by a comma, assume it's be used in a # macro context and don't do any checks. This avoids false # positives. # # Note that && is not included here. Those are checked separately # in CheckRValueReference match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) elif not Match(r'#.*include', line): # Look for < that is not surrounded by spaces. This is only # triggered if both sides are missing spaces, even though # technically should should flag if at least one side is missing a # space. This is done to avoid some false positives with shifts. match = Match(r'^(.*[^\s<])<[^\s=<,]', line) if match: (_, _, end_pos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if end_pos <= -1: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <') # Look for > that is not surrounded by spaces. Similar to the # above, we only trigger if both sides are missing spaces to avoid # false positives with shifts. match = Match(r'^(.*[^-\s>])>[^\s=>,]', line) if match: (_, _, start_pos) = ReverseCloseExpression( clean_lines, linenum, len(match.group(1))) if start_pos <= -1: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >') # We allow no-spaces around << when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) # # We also allow operators following an opening parenthesis, since # those tend to be macros that deal with operators. match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<([^\s,=])', line) if (match and match.group(1) != '(' and not (match.group(1).isdigit() and match.group(2).isdigit()) and not (match.group(1) == 'operator' and match.group(2) == ';')): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <<') # We allow no-spaces around >> for almost anything. This is because # C++11 allows ">>" to close nested templates, which accounts for # most cases when ">>" is not followed by a space. # # We still warn on ">>" followed by alpha character, because that is # likely due to ">>" being used for right shifts, e.g.: # value >> alpha # # When ">>" is used to close templates, the alphanumeric letter that # follows would be part of an identifier, and there should still be # a space separating the template type and the identifier. # type<type<type>> alpha match = Search(r'>>[a-zA-Z_]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >>') # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) def CheckParenthesisSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing around parentheses. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # No spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if len(match.group(2)) not in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) def CheckCommaSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing near commas and semicolons. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ raw = clean_lines.lines_without_raw_strings line = clean_lines.elided[linenum] # You should always have a space after a comma (either as fn arg or operator) # # This does not apply when the non-space character following the # comma is another comma, since the only time when that happens is # for empty macro arguments. # # We run this check in two passes: first pass on elided lines to # verify that lines contain missing whitespaces, second pass on raw # lines to confirm that those missing whitespaces are not due to # elided comments. if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and Search(r',[^,\s]', raw[linenum])): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') def CheckBracesSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing near commas. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces. And since you should never have braces at the beginning of a line, # this is an easy test. match = Match(r'^(.*[^ ({]){', line) if match: # Try a bit harder to check for brace initialization. This # happens in one of the following forms: # Constructor() : initializer_list_{} { ... } # Constructor{}.MemberFunction() # Type variable{}; # FunctionCall(type{}, ...); # LastArgument(..., type{}); # LOG(INFO) << type{} << " ..."; # map_of_type[{...}] = ...; # ternary = expr ? new type{} : nullptr; # OuterTemplate<InnerTemplateConstructor<Type>{}> # # We check for the character following the closing brace, and # silence the warning if it's one of those listed above, i.e. # "{.;,)<>]:". # # To account for nested initializer list, we allow any number of # closing braces up to "{;,)<". We can't simply silence the # warning on first sight of closing brace, because that would # cause false negatives for things that are not initializer lists. # Silence this: But not this: # Outer{ if (...) { # Inner{...} if (...){ // Missing space before { # }; } # # There is a false negative with this approach if people inserted # spurious semicolons, e.g. "if (cond){};", but we will catch the # spurious semicolon with a separate check. (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) trailing_text = '' if endpos > -1: trailing_text = endline[endpos:] for offset in xrange(endlinenum + 1, min(endlinenum + 3, clean_lines.NumLines() - 1)): trailing_text += clean_lines.elided[offset] if not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.') def IsDecltype(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is decltype(). Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is decltype() expression, False otherwise. """ (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column) if start_col < 0: return False if Search(r'\bdecltype\s*$', text[0:start_col]): return True return False def IsTemplateParameterList(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is the end of template<>. Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is end of a template parameter list, False otherwise. """ (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, column) if (startpos > -1 and Search(r'\btemplate\s*$', clean_lines.elided[startline][0:startpos])): return True return False def IsRValueType(clean_lines, nesting_state, linenum, column): """Check if the token ending on (linenum, column) is a type. Assumes that text to the right of the column is "&&" or a function name. Args: clean_lines: A CleansedLines instance containing the file. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is a type, False if we are not sure. """ prefix = clean_lines.elided[linenum][0:column] # Get one word to the left. If we failed to do so, this is most # likely not a type, since it's unlikely that the type name and "&&" # would be split across multiple lines. match = Match(r'^(.*)(\b\w+|[>*)&])\s*$', prefix) if not match: return False # Check text following the token. If it's "&&>" or "&&," or "&&...", it's # most likely a rvalue reference used inside a template. suffix = clean_lines.elided[linenum][column:] if Match(r'&&\s*(?:[>,]|\.\.\.)', suffix): return True # Check for simple type and end of templates: # int&& variable # vector<int>&& variable # # Because this function is called recursively, we also need to # recognize pointer and reference types: # int* Function() # int& Function() if match.group(2) in ['char', 'char16_t', 'char32_t', 'wchar_t', 'bool', 'short', 'int', 'long', 'signed', 'unsigned', 'float', 'double', 'void', 'auto', '>', '*', '&']: return True # If we see a close parenthesis, look for decltype on the other side. # decltype would unambiguously identify a type, anything else is # probably a parenthesized expression and not a type. if match.group(2) == ')': return IsDecltype( clean_lines, linenum, len(match.group(1)) + len(match.group(2)) - 1) # Check for casts and cv-qualifiers. # match.group(1) remainder # -------------- --------- # const_cast< type&& # const type&& # type const&& if Search(r'\b(?:const_cast\s*<|static_cast\s*<|dynamic_cast\s*<|' r'reinterpret_cast\s*<|\w+\s)\s*$', match.group(1)): return True # Look for a preceding symbol that might help differentiate the context. # These are the cases that would be ambiguous: # match.group(1) remainder # -------------- --------- # Call ( expression && # Declaration ( type&& # sizeof ( type&& # if ( expression && # while ( expression && # for ( type&& # for( ; expression && # statement ; type&& # block { type&& # constructor { expression && start = linenum line = match.group(1) match_symbol = None while start >= 0: # We want to skip over identifiers and commas to get to a symbol. # Commas are skipped so that we can find the opening parenthesis # for function parameter lists. match_symbol = Match(r'^(.*)([^\w\s,])[\w\s,]*$', line) if match_symbol: break start -= 1 line = clean_lines.elided[start] if not match_symbol: # Probably the first statement in the file is an rvalue reference return True if match_symbol.group(2) == '}': # Found closing brace, probably an indicate of this: # block{} type&& return True if match_symbol.group(2) == ';': # Found semicolon, probably one of these: # for(; expression && # statement; type&& # Look for the previous 'for(' in the previous lines. before_text = match_symbol.group(1) for i in xrange(start - 1, max(start - 6, 0), -1): before_text = clean_lines.elided[i] + before_text if Search(r'for\s*\([^{};]*$', before_text): # This is the condition inside a for-loop return False # Did not find a for-init-statement before this semicolon, so this # is probably a new statement and not a condition. return True if match_symbol.group(2) == '{': # Found opening brace, probably one of these: # block{ type&& = ... ; } # constructor{ expression && expression } # Look for a closing brace or a semicolon. If we see a semicolon # first, this is probably a rvalue reference. line = clean_lines.elided[start][0:len(match_symbol.group(1)) + 1] end = start depth = 1 while True: for ch in line: if ch == ';': return True elif ch == '{': depth += 1 elif ch == '}': depth -= 1 if depth == 0: return False end += 1 if end >= clean_lines.NumLines(): break line = clean_lines.elided[end] # Incomplete program? return False if match_symbol.group(2) == '(': # Opening parenthesis. Need to check what's to the left of the # parenthesis. Look back one extra line for additional context. before_text = match_symbol.group(1) if linenum > 1: before_text = clean_lines.elided[linenum - 1] + before_text before_text = match_symbol.group(1) # Patterns that are likely to be types: # [](type&& # for (type&& # sizeof(type&& # operator=(type&& # if Search(r'(?:\]|\bfor|\bsizeof|\boperator\s*\S+\s*)\s*$', before_text): return True # Patterns that are likely to be expressions: # if (expression && # while (expression && # : initializer(expression && # , initializer(expression && # ( FunctionCall(expression && # + FunctionCall(expression && # + (expression && # # The last '+' represents operators such as '+' and '-'. if Search(r'(?:\bif|\bwhile|[-+=%^(<!?:,&*]\s*)$', before_text): return False # Something else. Check that tokens to the left look like # return_type function_name match_func = Match(r'^(.*)\s+\w(?:\w|::)*(?:<[^<>]*>)?\s*$', match_symbol.group(1)) if match_func: # Check for constructors, which don't have return types. if Search(r'\b(?:explicit|inline)$', match_func.group(1)): return True implicit_constructor = Match(r'\s*(\w+)\((?:const\s+)?(\w+)', prefix) if (implicit_constructor and implicit_constructor.group(1) == implicit_constructor.group(2)): return True return IsRValueType(clean_lines, nesting_state, linenum, len(match_func.group(1))) # Nothing before the function name. If this is inside a block scope, # this is probably a function call. return not (nesting_state.previous_stack_top and nesting_state.previous_stack_top.IsBlockInfo()) if match_symbol.group(2) == '>': # Possibly a closing bracket, check that what's on the other side # looks like the start of a template. return IsTemplateParameterList( clean_lines, start, len(match_symbol.group(1))) # Some other symbol, usually something like "a=b&&c". This is most # likely not a type. return False def IsDeletedOrDefault(clean_lines, linenum): """Check if current constructor or operator is deleted or default. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if this is a deleted or default constructor. """ open_paren = clean_lines.elided[linenum].find('(') if open_paren < 0: return False (close_line, _, close_paren) = CloseExpression( clean_lines, linenum, open_paren) if close_paren < 0: return False return Match(r'\s*=\s*(?:delete|default)\b', close_line[close_paren:]) def IsRValueAllowed(clean_lines, linenum): """Check if RValue reference is allowed on a particular line. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if line is within the region where RValue references are allowed. """ # Allow region marked by PUSH/POP macros for i in xrange(linenum, 0, -1): line = clean_lines.elided[i] if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line): if not line.endswith('PUSH'): return False for j in xrange(linenum, clean_lines.NumLines(), 1): line = clean_lines.elided[j] if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line): return line.endswith('POP') # Allow operator= line = clean_lines.elided[linenum] if Search(r'\boperator\s*=\s*\(', line): return IsDeletedOrDefault(clean_lines, linenum) # Allow constructors match = Match(r'\s*([\w<>]+)\s*::\s*([\w<>]+)\s*\(', line) if match and match.group(1) == match.group(2): return IsDeletedOrDefault(clean_lines, linenum) if Search(r'\b(?:explicit|inline)\s+[\w<>]+\s*\(', line): return IsDeletedOrDefault(clean_lines, linenum) if Match(r'\s*[\w<>]+\s*\(', line): previous_line = 'ReturnType' if linenum > 0: previous_line = clean_lines.elided[linenum - 1] if Match(r'^\s*$', previous_line) or Search(r'[{}:;]\s*$', previous_line): return IsDeletedOrDefault(clean_lines, linenum) return False def CheckRValueReference(filename, clean_lines, linenum, nesting_state, error): """Check for rvalue references. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Find lines missing spaces around &&. # TODO(unknown): currently we don't check for rvalue references # with spaces surrounding the && to avoid false positives with # boolean expressions. line = clean_lines.elided[linenum] match = Match(r'^(.*\S)&&', line) if not match: match = Match(r'(.*)&&\S', line) if (not match) or '(&&)' in line or Search(r'\boperator\s*$', match.group(1)): return # Either poorly formed && or an rvalue reference, check the context # to get a more accurate error message. Mostly we want to determine # if what's to the left of "&&" is a type or not. and_pos = len(match.group(1)) if IsRValueType(clean_lines, nesting_state, linenum, and_pos): if not IsRValueAllowed(clean_lines, linenum): error(filename, linenum, 'build/c++11', 3, 'RValue references are an unapproved C++ feature.') else: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around &&') def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. # Also ignores cases where the previous line ends with a backslash as can be # common when defining classes in C macros. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line) and not Search(r'\\$', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.starting_linenum for i in range(class_info.starting_linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1)) def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line. """ prevlinenum = linenum - 1 while prevlinenum >= 0: prevline = clean_lines.elided[prevlinenum] if not IsBlankLine(prevline): # if not a blank line... return (prevline, prevlinenum) prevlinenum -= 1 return ('', -1) def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone is using # braces in a block to explicitly create a new scope, which is commonly used # to control the lifetime of stack-allocated variables. Braces are also # used for brace initializers inside function calls. We don't detect this # perfectly: we just don't complain if the last non-whitespace character on # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the # previous line starts a preprocessor block. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[,;:}{(]\s*$', prevline) and not Match(r'\s*#', prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\b\s*(?:if\b|\{|$)', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'else if\s*\(', line): # could be multi-line if brace_on_left = bool(Search(r'}\s*else if\s*\(', line)) # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) brace_on_right = endline[endpos:].find('{') != -1 if brace_on_left != brace_on_right: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Check single-line if/else bodies. The style guide says 'curly braces are not # required for single-line statements'. We additionally allow multi-line, # single statements, but we reject anything with more than one semicolon in # it. This means that the first semicolon after the if should be at the end of # its line, and the line after that should have an indent level equal to or # lower than the if. We also check for ambiguous if/else nesting without # braces. if_else_match = Search(r'\b(if\s*\(|else\b)', line) if if_else_match and not Match(r'\s*#', line): if_indent = GetIndentLevel(line) endline, endlinenum, endpos = line, linenum, if_else_match.end() if_match = Search(r'\bif\s*\(', line) if if_match: # This could be a multiline if condition, so find the end first. pos = if_match.end() - 1 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos) # Check for an opening brace, either directly after the if or on the next # line. If found, this isn't a single-statement conditional. if (not Match(r'\s*{', endline[endpos:]) and not (Match(r'\s*$', endline[endpos:]) and endlinenum < (len(clean_lines.elided) - 1) and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))): while (endlinenum < len(clean_lines.elided) and ';' not in clean_lines.elided[endlinenum][endpos:]): endlinenum += 1 endpos = 0 if endlinenum < len(clean_lines.elided): endline = clean_lines.elided[endlinenum] # We allow a mix of whitespace and closing braces (e.g. for one-liner # methods) and a single \ after the semicolon (for macros) endpos = endline.find(';') if not Match(r';[\s}]*(\\?)$', endline[endpos:]): # Semicolon isn't the last character, there's something trailing. # Output a warning if the semicolon is not contained inside # a lambda expression. if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$', endline): error(filename, linenum, 'readability/braces', 4, 'If/else bodies with multiple statements require braces') elif endlinenum < len(clean_lines.elided) - 1: # Make sure the next line is dedented next_line = clean_lines.elided[endlinenum + 1] next_indent = GetIndentLevel(next_line) # With ambiguous nested if statements, this will error out on the # if that *doesn't* match the else, regardless of whether it's the # inner one or outer one. if (if_match and Match(r'\s*else\b', next_line) and next_indent != if_indent): error(filename, linenum, 'readability/braces', 4, 'Else clause should be indented at the same level as if. ' 'Ambiguous nested if/else chains require braces.') elif next_indent > if_indent: error(filename, linenum, 'readability/braces', 4, 'If/else bodies with multiple statements require braces') def CheckTrailingSemicolon(filename, clean_lines, linenum, error): """Looks for redundant trailing semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Block bodies should not be followed by a semicolon. Due to C++11 # brace initialization, there are more places where semicolons are # required than not, so we use a whitelist approach to check these # rather than a blacklist. These are the places where "};" should # be replaced by just "}": # 1. Some flavor of block following closing parenthesis: # for (;;) {}; # while (...) {}; # switch (...) {}; # Function(...) {}; # if (...) {}; # if (...) else if (...) {}; # # 2. else block: # if (...) else {}; # # 3. const member function: # Function(...) const {}; # # 4. Block following some statement: # x = 42; # {}; # # 5. Block at the beginning of a function: # Function(...) { # {}; # } # # Note that naively checking for the preceding "{" will also match # braces inside multi-dimensional arrays, but this is fine since # that expression will not contain semicolons. # # 6. Block following another block: # while (true) {} # {}; # # 7. End of namespaces: # namespace {}; # # These semicolons seems far more common than other kinds of # redundant semicolons, possibly due to people converting classes # to namespaces. For now we do not warn for this case. # # Try matching case 1 first. match = Match(r'^(.*\)\s*)\{', line) if match: # Matched closing parenthesis (case 1). Check the token before the # matching opening parenthesis, and don't warn if it looks like a # macro. This avoids these false positives: # - macro that defines a base class # - multi-line macro that defines a base class # - macro that defines the whole class-head # # But we still issue warnings for macros that we know are safe to # warn, specifically: # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P # - TYPED_TEST # - INTERFACE_DEF # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: # # We implement a whitelist of safe macros instead of a blacklist of # unsafe macros, even though the latter appears less frequently in # google code and would have been easier to implement. This is because # the downside for getting the whitelist wrong means some extra # semicolons, while the downside for getting the blacklist wrong # would result in compile errors. # # In addition to macros, we also don't want to warn on compound # literals and lambdas. closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression( clean_lines, linenum, closing_brace_pos) if opening_parenthesis[2] > -1: line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search(r'\b([A-Z_]+)\s*$', line_prefix) func = Match(r'^(.*\])\s*$', line_prefix) if ((macro and macro.group(1) not in ( 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or Search(r'\s+=\s*$', line_prefix)): match = None if (match and opening_parenthesis[1] > 1 and Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])): # Multi-line lambda-expression match = None else: # Try matching cases 2-3. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) if not match: # Try matching cases 4-6. These are always matched on separate lines. # # Note that we can't simply concatenate the previous line to the # current line and do a single match, otherwise we may output # duplicate warnings for the blank line case: # if (cond) { # // blank line # } prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if prevline and Search(r'[;{}]\s*$', prevline): match = Match(r'^(\s*)\{', line) # Check matching closing brace if match: (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if endpos > -1 and Match(r'^\s*;', endline[endpos:]): # Current {} pair is eligible for semicolon check, and we have found # the redundant semicolon, output warning here. # # Note: because we are scanning forward for opening braces, and # outputting warnings for the matching closing brace, if there are # nested blocks with trailing semicolons, we will get the error # messages in reversed order. error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }") def CheckEmptyBlockBody(filename, clean_lines, linenum, error): """Look for empty loop/conditional body with only a single semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Search for loop keywords at the beginning of the line. Because only # whitespaces are allowed before the keywords, this will also ignore most # do-while-loops, since those lines should start with closing brace. # # We also check "if" blocks here, since an empty conditional block # is likely an error. line = clean_lines.elided[linenum] matched = Match(r'\s*(for|while|if)\s*\(', line) if matched: # Find the end of the conditional expression (end_line, end_linenum, end_pos) = CloseExpression( clean_lines, linenum, line.find('(')) # Output warning if what follows the condition expression is a semicolon. # No warning for all other cases, including whitespace or newline, since we # have a separate check for semicolons preceded by whitespace. if end_pos >= 0 and Match(r';', end_line[end_pos:]): if matched.group(1) == 'if': error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, 'Empty conditional bodies should use {}') else: error(filename, end_linenum, 'whitespace/empty_loop_body', 5, 'Empty loop bodies should use {} or continue') def FindCheckMacro(line): """Find a replaceable CHECK-like macro. Args: line: line to search on. Returns: (macro name, start position), or (None, -1) if no replaceable macro is found. """ for macro in _CHECK_MACROS: i = line.find(macro) if i >= 0: # Find opening parenthesis. Do a regular expression match here # to make sure that we are matching the expected CHECK macro, as # opposed to some other macro that happens to contain the CHECK # substring. matched = Match(r'^(.*\b' + macro + r'\s*)\(', line) if not matched: continue return (macro, len(matched.group(1))) return (None, -1) def CheckCheck(filename, clean_lines, linenum, error): """Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested lines = clean_lines.elided (check_macro, start_pos) = FindCheckMacro(lines[linenum]) if not check_macro: return # Find end of the boolean expression by matching parentheses (last_line, end_line, end_pos) = CloseExpression( clean_lines, linenum, start_pos) if end_pos < 0: return # If the check macro is followed by something other than a # semicolon, assume users will log their own custom error messages # and don't suggest any replacements. if not Match(r'\s*;', last_line[end_pos:]): return if linenum == end_line: expression = lines[linenum][start_pos + 1:end_pos - 1] else: expression = lines[linenum][start_pos + 1:] for i in xrange(linenum + 1, end_line): expression += lines[i] expression += last_line[0:end_pos - 1] # Parse expression so that we can take parentheses into account. # This avoids false positives for inputs like "CHECK((a < 4) == b)", # which is not replaceable by CHECK_LE. lhs = '' rhs = '' operator = None while expression: matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' r'==|!=|>=|>|<=|<|\()(.*)$', expression) if matched: token = matched.group(1) if token == '(': # Parenthesized operand expression = matched.group(2) (end, _) = FindEndOfExpressionInLine(expression, 0, ['(']) if end < 0: return # Unmatched parenthesis lhs += '(' + expression[0:end] expression = expression[end:] elif token in ('&&', '||'): # Logical and/or operators. This means the expression # contains more than one term, for example: # CHECK(42 < a && a < b); # # These are not replaceable with CHECK_LE, so bail out early. return elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): # Non-relational operator lhs += token expression = matched.group(2) else: # Relational operator operator = token rhs = matched.group(2) break else: # Unparenthesized operand. Instead of appending to lhs one character # at a time, we do another regular expression match to consume several # characters at once if possible. Trivial benchmark shows that this # is more efficient when the operands are longer than a single # character, which is generally the case. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) if not matched: matched = Match(r'^(\s*\S)(.*)$', expression) if not matched: break lhs += matched.group(1) expression = matched.group(2) # Only apply checks if we got all parts of the boolean expression if not (lhs and operator and rhs): return # Check that rhs do not contain logical operators. We already know # that lhs is fine since the loop above parses out && and ||. if rhs.find('&&') > -1 or rhs.find('||') > -1: return # At least one of the operands must be a constant literal. This is # to avoid suggesting replacements for unprintable things like # CHECK(variable != iterator) # # The following pattern matches decimal, hex integers, strings, and # characters (in that order). lhs = lhs.strip() rhs = rhs.strip() match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' if Match(match_constant, lhs) or Match(match_constant, rhs): # Note: since we know both lhs and rhs, we can provide a more # descriptive error message like: # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) # Instead of: # Consider using CHECK_EQ instead of CHECK(a == b) # # We are still keeping the less descriptive message because if lhs # or rhs gets long, the error message might become unreadable. error(filename, linenum, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[check_macro][operator], check_macro, operator)) def CheckAltTokens(filename, clean_lines, linenum, error): """Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort to avoid multi-line comments. This will not help # if the comment started before the current line or ended after the # current line, but it catches most of the false positives. At least, # it provides a way to workaround this warning for people who use # multi-line comments in preprocessor macros. # # TODO(unknown): remove this once cpplint has better support for # multi-line comments. if line.find('/*') >= 0 or line.find('*/') >= 0: return for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): error(filename, linenum, 'readability/alt_tokens', 2, 'Use operator %s instead of %s' % ( _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line) def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, error): """Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we do what we can. In particular we check for 2-space indents, line lengths, tab usage, spaces inside code, etc. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw_lines = clean_lines.lines_without_raw_strings line = raw_lines[linenum] if line.find('\t') != -1: error(filename, linenum, 'whitespace/tab', 1, 'Tab found; better to use spaces') # One or three blank spaces at the beginning of the line is weird; it's # hard to reconcile that with 2-space indents. # NOTE: here are the conditions rob pike used for his tests. Mine aren't # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces # if(RLENGTH > 20) complain = 0; # if(match($0, " +(error|private|public|protected):")) complain = 0; # if(match(prev, "&& *$")) complain = 0; # if(match(prev, "\\|\\| *$")) complain = 0; # if(match(prev, "[\",=><] *$")) complain = 0; # if(match($0, " <<")) complain = 0; # if(match(prev, " +for \\(")) complain = 0; # if(prevodd && match(prevprev, " +for \\(")) complain = 0; scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$' classinfo = nesting_state.InnermostClass() initial_spaces = 0 cleansed_line = clean_lines.elided[linenum] while initial_spaces < len(line) and line[initial_spaces] == ' ': initial_spaces += 1 if line and line[-1].isspace(): error(filename, linenum, 'whitespace/end_of_line', 4, 'Line ends in whitespace. Consider deleting these extra spaces.') # There are certain situations we allow one space, notably for # section labels, and also lines containing multi-line raw strings. elif ((initial_spaces == 1 or initial_spaces == 3) and not Match(scope_or_label_pattern, cleansed_line) and not (clean_lines.raw_lines[linenum] != line and Match(r'^\s*""', line))): error(filename, linenum, 'whitespace/indent', 3, 'Weird number of spaces at line-start. ' 'Are you using a 2-space indent?') # Check if the line is a header guard. is_header_guard = False if file_extension == 'h': cppvar = GetHeaderGuardCPPVariable(filename) if (line.startswith('#ifndef %s' % cppvar) or line.startswith('#define %s' % cppvar) or line.startswith('#endif // %s' % cppvar)): is_header_guard = True # #include lines and header guards can be long, since there's no clean way to # split them. # # URLs can be long too. It's possible to split these, but it makes them # harder to cut&paste. # # The "$Id:...$" comment may also get very long without it being the # developers fault. if (not line.startswith('#include') and not is_header_guard and not Match(r'^\s*//.*http(s?)://\S*$', line) and not Match(r'^// \$Id:.*#[0-9]+ \$$', line)): line_width = GetLineWidth(line) extended_length = int((_line_length * 1.25)) if line_width > extended_length: error(filename, linenum, 'whitespace/line_length', 4, 'Lines should very rarely be longer than %i characters' % extended_length) elif line_width > _line_length: error(filename, linenum, 'whitespace/line_length', 2, 'Lines should be <= %i characters long' % _line_length) if (cleansed_line.count(';') > 1 and # for loops are allowed two ;'s (and may run over two lines). cleansed_line.find('for') == -1 and (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and # It's ok to have many commands in a switch case that fits in 1 line not ((cleansed_line.find('case ') != -1 or cleansed_line.find('default:') != -1) and cleansed_line.find('break;') != -1)): error(filename, linenum, 'whitespace/newline', 0, 'More than one command on the same line') # Some more style checks CheckBraces(filename, clean_lines, linenum, error) CheckTrailingSemicolon(filename, clean_lines, linenum, error) CheckEmptyBlockBody(filename, clean_lines, linenum, error) CheckAccess(filename, clean_lines, linenum, nesting_state, error) CheckSpacing(filename, clean_lines, linenum, nesting_state, error) CheckOperatorSpacing(filename, clean_lines, linenum, error) CheckParenthesisSpacing(filename, clean_lines, linenum, error) CheckCommaSpacing(filename, clean_lines, linenum, error) CheckBracesSpacing(filename, clean_lines, linenum, error) CheckSpacingForFunctionCall(filename, clean_lines, linenum, error) CheckRValueReference(filename, clean_lines, linenum, nesting_state, error) CheckCheck(filename, clean_lines, linenum, error) CheckAltTokens(filename, clean_lines, linenum, error) classinfo = nesting_state.InnermostClass() if classinfo: CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') # Matches the first component of a filename delimited by -s and _s. That is: # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', 'inl.h', 'impl.h', 'internal.h'): if (filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ('-', '_')): return filename[:-len(suffix) - 1] return os.path.splitext(filename)[0] def _IsTestFilename(filename): """Determines if the given filename has a suffix that identifies it as a test. Args: filename: The input filename. Returns: True if 'filename' looks like a test, False otherwise. """ if (filename.endswith('_test.cc') or filename.endswith('_unittest.cc') or filename.endswith('_regtest.cc')): return True else: return False def _ClassifyInclude(fileinfo, include, is_system): """Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER """ # This is a list of all standard c++ header files, except # those already checked for above. is_cpp_h = include in _CPP_HEADERS if is_system: if is_cpp_h: return _CPP_SYS_HEADER else: return _C_SYS_HEADER # If the target file and the include we're checking share a # basename when we drop common extensions, and the include # lives in . , then it's likely to be owned by the target file. target_dir, target_base = ( os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) if target_base == include_base and ( include_dir == target_dir or include_dir == os.path.normpath(target_dir + '/../public')): return _LIKELY_MY_HEADER # If the target and include share some initial basename # component, it's possible the target is implementing the # include, so it's allowed to be first, but we'll never # complain if it's not there. target_first_component = _RE_FIRST_COMPONENT.match(target_base) include_first_component = _RE_FIRST_COMPONENT.match(include_base) if (target_first_component and include_first_component and target_first_component.group(0) == include_first_component.group(0)): return _POSSIBLE_MY_HEADER return _OTHER_HEADER def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): """Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] # "include" should use the new style "foo/bar.h" instead of just "bar.h" # Only do this check if the included header follows google naming # conventions. If not, assume that it's a 3rd party API that # requires special include conventions. # # We also make an exception for Lua headers, which follow google # naming convention but not the include convention. match = Match(r'#include\s*"([^/]+\.h)"', line) if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)): error(filename, linenum, 'build/include', 4, 'Include the directory when naming .h files') # we shouldn't include a file more than once. actually, there are a # handful of instances where doing so is okay, but in general it's # not. match = _RE_PATTERN_INCLUDE.search(line) if match: include = match.group(2) is_system = (match.group(1) == '<') duplicate_line = include_state.FindHeader(include) if duplicate_line >= 0: error(filename, linenum, 'build/include', 4, '"%s" already included at %s:%s' % (include, filename, duplicate_line)) elif not _THIRD_PARTY_HEADERS_PATTERN.match(include): include_state.include_list[-1].append((include, linenum)) # We want to ensure that headers appear in the right order: # 1) for foo.cc, foo.h (preferred location) # 2) c system files # 3) cpp system files # 4) for foo.cc, foo.h (deprecated location) # 5) other google headers # # We classify each include statement as one of those 5 types # using a number of techniques. The include_state object keeps # track of the highest type seen, and complains if we see a # lower type after that. error_message = include_state.CheckNextIncludeOrder( _ClassifyInclude(fileinfo, include, is_system)) if error_message: error(filename, linenum, 'build/include_order', 4, '%s. Should be: %s.h, c system, c++ system, other.' % (error_message, fileinfo.BaseName())) canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) if not include_state.IsInAlphabeticalOrder( clean_lines, linenum, canonical_include): error(filename, linenum, 'build/include_alpha', 4, 'Include "%s" not in alphabetical order' % include) include_state.SetLastHeader(canonical_include) # Look for any of the stream classes that are part of standard C++. match = _RE_PATTERN_INCLUDE.match(line) if match: include = match.group(2) if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include): # Many unit tests use cout, so we exempt them. if not _IsTestFilename(filename): # Suggest a different header for ostream if include == 'ostream': error(filename, linenum, 'readability/streams', 3, 'For logging, include "base/logging.h" instead of <ostream>.') else: error(filename, linenum, 'readability/streams', 3, 'Streams are highly discouraged.') def _GetTextInside(text, start_pattern): r"""Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found. """ # TODO(unknown): Audit cpplint.py to see what places could be profitably # rewritten to use _GetTextInside (and use inferior regexp matching today). # Give opening punctuations to get the matching close-punctuations. matching_punctuation = {'(': ')', '{': '}', '[': ']'} closing_punctuation = set(matching_punctuation.itervalues()) # Find the position to start extracting text. match = re.search(start_pattern, text, re.M) if not match: # start_pattern not found in text. return None start_position = match.end(0) assert start_position > 0, ( 'start_pattern must ends with an opening punctuation.') assert text[start_position - 1] in matching_punctuation, ( 'start_pattern must ends with an opening punctuation.') # Stack of closing punctuations we expect to have in text after position. punctuation_stack = [matching_punctuation[text[start_position - 1]]] position = start_position while punctuation_stack and position < len(text): if text[position] == punctuation_stack[-1]: punctuation_stack.pop() elif text[position] in closing_punctuation: # A closing punctuation without matching opening punctuations. return None elif text[position] in matching_punctuation: punctuation_stack.append(matching_punctuation[text[position]]) position += 1 if punctuation_stack: # Opening punctuations left without matching close-punctuations. return None # punctuations match. return text[start_position:position - 1] # Patterns for matching call-by-reference parameters. # # Supports nested templates up to 2 levels deep using this messy pattern: # < (?: < (?: < [^<>]* # > # | [^<>] )* # > # | [^<>] )* # > _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]* _RE_PATTERN_TYPE = ( r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?' r'(?:\w|' r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|' r'::)+') # A call-by-reference parameter ends with '& identifier'. _RE_PATTERN_REF_PARAM = re.compile( r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*' r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]') # A call-by-const-reference parameter either ends with 'const& identifier' # or looks like 'const type& identifier' when 'type' is atomic. _RE_PATTERN_CONST_REF_PARAM = ( r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT + r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')') def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state, nesting_state, error): """Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # If the line is empty or consists of entirely a comment, no need to # check it. line = clean_lines.elided[linenum] if not line: return match = _RE_PATTERN_INCLUDE.search(line) if match: CheckIncludeLine(filename, clean_lines, linenum, include_state, error) return # Reset include state across preprocessor directives. This is meant # to silence warnings for conditional includes. match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line) if match: include_state.ResetSection(match.group(1)) # Make Windows paths like Unix. fullname = os.path.abspath(filename).replace('\\', '/') # Perform other checks now that we are sure that this is not an include line CheckCasts(filename, clean_lines, linenum, error) CheckGlobalStatic(filename, clean_lines, linenum, error) CheckPrintf(filename, clean_lines, linenum, error) if file_extension == 'h': # TODO(unknown): check that 1-arg constructors are explicit. # How to tell it's a constructor? # (handled in CheckForNonStandardConstructs for now) # TODO(unknown): check that classes declare or disable copy/assign # (level 1 error) pass # Check if people are using the verboten C basic types. The only exception # we regularly allow is "unsigned short port" for port. if Search(r'\bshort port\b', line): if not Search(r'\bunsigned short port\b', line): error(filename, linenum, 'runtime/int', 4, 'Use "unsigned short" for ports, not "short"') else: match = Search(r'\b(short|long(?! +double)|long long)\b', line) if match: error(filename, linenum, 'runtime/int', 4, 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) # Check if some verboten operator overloading is going on # TODO(unknown): catch out-of-line unary operator&: # class X {}; # int operator&(const X& x) { return 42; } // unary operator& # The trick is it's hard to tell apart from binary operator&: # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& if Search(r'\boperator\s*&\s*\(\s*\)', line): error(filename, linenum, 'runtime/operator', 4, 'Unary operator& is dangerous. Do not use it.') # Check for suspicious usage of "if" like # } if (a == b) { if Search(r'\}\s*if\s*\(', line): error(filename, linenum, 'readability/braces', 4, 'Did you mean "else if"? If not, start a new line for "if".') # Check for potential format string bugs like printf(foo). # We constrain the pattern not to pick things like DocidForPrintf(foo). # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) # TODO(unknown): Catch the following case. Need to change the calling # convention of the whole function to process multiple line to handle it. # printf( # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') if printf_args: match = Match(r'([\w.\->()]+)$', printf_args) if match and match.group(1) != '__VA_ARGS__': function_name = re.search(r'\b((?:string)?printf)\s*\(', line, re.I).group(1) error(filename, linenum, 'runtime/printf', 4, 'Potential format string bug. Do %s("%%s", %s) instead.' % (function_name, match.group(1))) # Check for potential memset bugs like memset(buf, sizeof(buf), 0). match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): error(filename, linenum, 'runtime/memset', 4, 'Did you mean "memset(%s, 0, %s)"?' % (match.group(1), match.group(2))) if Search(r'\busing namespace\b', line): error(filename, linenum, 'build/namespaces', 5, 'Do not use namespace using-directives. ' 'Use using-declarations instead.') # Detect variable-length arrays. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) if (match and match.group(2) != 'return' and match.group(2) != 'delete' and match.group(3).find(']') == -1): # Split the size using space and arithmetic operators as delimiters. # If any of the resulting tokens are not compile time constants then # report the error. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) is_const = True skip_next = False for tok in tokens: if skip_next: skip_next = False continue if Search(r'sizeof\(.+\)', tok): continue if Search(r'arraysize\(\w+\)', tok): continue tok = tok.lstrip('(') tok = tok.rstrip(')') if not tok: continue if Match(r'\d+', tok): continue if Match(r'0[xX][0-9a-fA-F]+', tok): continue if Match(r'k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue # A catch all for tricky sizeof cases, including 'sizeof expression', # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' # requires skipping the next token because we split on ' ' and '*'. if tok.startswith('sizeof'): skip_next = True continue is_const = False break if not is_const: error(filename, linenum, 'runtime/arrays', 1, 'Do not use variable-length arrays. Use an appropriately named ' "('k' followed by CamelCase) compile-time constant for the size.") # If DISALLOW_COPY_AND_ASSIGN DISALLOW_IMPLICIT_CONSTRUCTORS is present, # then it should be the last thing in the class declaration. match = Match( (r'\s*' r'(DISALLOW_(COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))' r'\(.*\);$'), line) if match and linenum + 1 < clean_lines.NumLines(): next_line = clean_lines.elided[linenum + 1] # We allow some, but not all, declarations of variables to be present # in the statement that defines the class. The [\w\*,\s]* fragment of # the regular expression below allows users to declare instances of # the class or pointers to instances, but not less common types such # as function pointers or arrays. It's a tradeoff between allowing # reasonable code and avoiding trying to parse more C++ using regexps. if not Search(r'^\s*}[\w\*,\s]*;', next_line): error(filename, linenum, 'readability/constructors', 3, match.group(1) + ' should be the last thing in the class') # Check for use of unnamed namespaces in header files. Registration # macros are typically OK, so we allow use of "namespace {" on lines # that end with backslashes. if (file_extension == 'h' and Search(r'\bnamespace\s*{', line) and line[-1] != '\\'): error(filename, linenum, 'build/namespaces', 4, 'Do not use unnamed namespaces in header files. See ' 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' ' for more information.') def CheckGlobalStatic(filename, clean_lines, linenum, error): """Check for unsafe global or static objects. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Match two lines at a time to support multiline declarations if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line): line += clean_lines.elided[linenum + 1].strip() # Check for people declaring static/global STL strings at the top level. # This is dangerous because the C++ language does not guarantee that # globals with constructors are initialized before the first access. match = Match( r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)', line) # Remove false positives: # - String pointers (as opposed to values). # string *pointer # const string *pointer # string const *pointer # string *const pointer # # - Functions and template specializations. # string Function<Type>(... # string Class<Type>::Method(... # # - Operators. These are matched separately because operator names # cross non-word boundaries, and trying to match both operators # and functions at the same time would decrease accuracy of # matching identifiers. # string Class::operator*() if (match and not Search(r'\bstring\b(\s+const)?\s*\*\s*(const\s+)?\w', line) and not Search(r'\boperator\W', line) and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(3))): error(filename, linenum, 'runtime/string', 4, 'For a static/global string constant, use a C style string instead: ' '"%schar %s[]".' % (match.group(1), match.group(2))) if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line): error(filename, linenum, 'runtime/init', 4, 'You seem to be initializing a member variable with itself.') def CheckPrintf(filename, clean_lines, linenum, error): """Check for printf related issues. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # When snprintf is used, the second argument shouldn't be a literal. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) if match and match.group(2) != '0': # If 2nd arg is zero, snprintf is used to calculate size. error(filename, linenum, 'runtime/printf', 3, 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' 'to snprintf.' % (match.group(1), match.group(2))) # Check if some verboten C functions are being used. if Search(r'\bsprintf\s*\(', line): error(filename, linenum, 'runtime/printf', 5, 'Never use sprintf. Use snprintf instead.') match = Search(r'\b(strcpy|strcat)\s*\(', line) if match: error(filename, linenum, 'runtime/printf', 4, 'Almost always, snprintf is better than %s' % match.group(1)) def IsDerivedFunction(clean_lines, linenum): """Check if current line contains an inherited function. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line contains a function with "override" virt-specifier. """ # Scan back a few lines for start of current function for i in xrange(linenum, max(-1, linenum - 10), -1): match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i]) if match: # Look for "override" after the matching closing parenthesis line, _, closing_paren = CloseExpression( clean_lines, i, len(match.group(1))) return (closing_paren >= 0 and Search(r'\boverride\b', line[closing_paren:])) return False def IsInitializerList(clean_lines, linenum): """Check if current line is inside constructor initializer list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line appears to be inside constructor initializer list, False otherwise. """ for i in xrange(linenum, 1, -1): line = clean_lines.elided[i] if i == linenum: remove_function_body = Match(r'^(.*)\{\s*$', line) if remove_function_body: line = remove_function_body.group(1) if Search(r'\s:\s*\w+[({]', line): # A lone colon tend to indicate the start of a constructor # initializer list. It could also be a ternary operator, which # also tend to appear in constructor initializer lists as # opposed to parameter lists. return True if Search(r'\}\s*,\s*$', line): # A closing brace followed by a comma is probably the end of a # brace-initialized member in constructor initializer list. return True if Search(r'[{};]\s*$', line): # Found one of the following: # - A closing brace or semicolon, probably the end of the previous # function. # - An opening brace, probably the start of current class or namespace. # # Current line is probably not inside an initializer list since # we saw one of those things without seeing the starting colon. return False # Got to the beginning of the file without seeing the start of # constructor initializer list. return False def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error): """Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Do nothing if there is no '&' on current line. line = clean_lines.elided[linenum] if '&' not in line: return # If a function is inherited, current function doesn't have much of # a choice, so any non-const references should not be blamed on # derived function. if IsDerivedFunction(clean_lines, linenum): return # Long type names may be broken across multiple lines, usually in one # of these forms: # LongType # ::LongTypeContinued &identifier # LongType:: # LongTypeContinued &identifier # LongType< # ...>::LongTypeContinued &identifier # # If we detected a type split across two lines, join the previous # line to current line so that we can match const references # accordingly. # # Note that this only scans back one line, since scanning back # arbitrary number of lines would be expensive. If you have a type # that spans more than 2 lines, please use a typedef. if linenum > 1: previous = None if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): # previous_line\n + ::current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', clean_lines.elided[linenum - 1]) elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): # previous_line::\n + current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', clean_lines.elided[linenum - 1]) if previous: line = previous.group(1) + line.lstrip() else: # Check for templated parameter that is split across multiple lines endpos = line.rfind('>') if endpos > -1: (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, endpos) if startpos > -1 and startline < linenum: # Found the matching < on an earlier line, collect all # pieces up to current line. line = '' for i in xrange(startline, linenum + 1): line += clean_lines.elided[i].strip() # Check for non-const references in function parameters. A single '&' may # found in the following places: # inside expression: binary & for bitwise AND # inside expression: unary & for taking the address of something # inside declarators: reference parameter # We will exclude the first two cases by checking that we are not inside a # function body, including one that was just introduced by a trailing '{'. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. if (nesting_state.previous_stack_top and not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or isinstance(nesting_state.previous_stack_top, _NamespaceInfo))): # Not at toplevel, not within a class, and not within a namespace return # Avoid initializer lists. We only need to scan back from the # current line for something that starts with ':'. # # We don't need to check the current line, since the '&' would # appear inside the second set of parentheses on the current line as # opposed to the first set. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 10), -1): previous_line = clean_lines.elided[i] if not Search(r'[),]\s*$', previous_line): break if Match(r'^\s*:\s+\S', previous_line): return # Avoid preprocessors if Search(r'\\\s*$', line): return # Avoid constructor initializer lists if IsInitializerList(clean_lines, linenum): return # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". Do not check # those function parameters. # # We also accept & in static_assert, which looks like a function but # it's actually a declaration expression. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' r'operator\s*[<>][<>]|' r'static_assert|COMPILE_ASSERT' r')\s*\(') if Search(whitelisted_functions, line): return elif not Search(r'\S+\([^)]*$', line): # Don't see a whitelisted function on this line. Actually we # didn't see any function name on this line, so this is likely a # multi-line parameter list. Try a bit harder to catch this case. for i in xrange(2): if (linenum > i and Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): return decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer: ' + ReplaceAll(' *<', '<', parameter)) def CheckCasts(filename, clean_lines, linenum, error): """Various cast related checks. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Check to see if they're using an conversion function cast. # I just try to capture the most common basic types, though there are more. # Parameterless conversion functions, such as bool(), are allowed as they are # probably a member operator declaration or default constructor. match = Search( r'(\bnew\s+|\S<\s*(?:const\s+)?)?\b' r'(int|float|double|bool|char|int32|uint32|int64|uint64)' r'(\([^)].*)', line) expecting_function = ExpectingFunctionArgs(clean_lines, linenum) if match and not expecting_function: matched_type = match.group(2) # matched_new_or_template is used to silence two false positives: # - New operators # - Template arguments with function types # # For template arguments, we match on types immediately following # an opening bracket without any spaces. This is a fast way to # silence the common case where the function type is the first # template argument. False negative with less-than comparison is # avoided because those operators are usually followed by a space. # # function<double(double)> // bracket + no space = false positive # value < double(42) // bracket + space = true positive matched_new_or_template = match.group(1) # Avoid arrays by looking for brackets that come after the closing # parenthesis. if Match(r'\([^()]+\)\s*\[', match.group(3)): return # Other things to ignore: # - Function pointers # - Casts to pointer types # - Placement new # - Alias declarations matched_funcptr = match.group(3) if (matched_new_or_template is None and not (matched_funcptr and (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', matched_funcptr) or matched_funcptr.startswith('(*)'))) and not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and not Search(r'new\(\S+\)\s*' + matched_type, line)): error(filename, linenum, 'readability/casting', 4, 'Using deprecated casting style. ' 'Use static_cast<%s>(...) instead' % matched_type) if not expecting_function: CheckCStyleCast(filename, clean_lines, linenum, 'static_cast', r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) # This doesn't catch all cases. Consider (const char * const)"hello". # # (char *) "foo" should always be a const_cast (reinterpret_cast won't # compile). if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error): pass else: # Check pointer casts for other than string constants CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) # In addition, we look for people taking the address of a cast. This # is dangerous -- casts can assign to temporaries, so the pointer doesn't # point where you think. # # Some non-identifier character is required before the '&' for the # expression to be recognized as a cast. These are casts: # expression = &static_cast<int*>(temporary()); # function(&(int*)(temporary())); # # This is not a cast: # reference_type&(int* function_param); match = Search( r'(?:[^\w]&\(([^)]+)\)[\w(])|' r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line) if match and match.group(1) != '*': # Try a better error message when the & is bound to something # dereferenced by the casted pointer, as opposed to the casted # pointer itself. parenthesis_error = False match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line) if match: _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1))) if x1 >= 0 and clean_lines.elided[y1][x1] == '(': _, y2, x2 = CloseExpression(clean_lines, y1, x1) if x2 >= 0: extended_line = clean_lines.elided[y2][x2:] if y2 < clean_lines.NumLines() - 1: extended_line += clean_lines.elided[y2 + 1] if Match(r'\s*(?:->|\[)', extended_line): parenthesis_error = True if parenthesis_error: error(filename, linenum, 'readability/casting', 4, ('Are you taking an address of something dereferenced ' 'from a cast? Wrapping the dereferenced expression in ' 'parentheses will make the binding more obvious')) else: error(filename, linenum, 'runtime/casting', 4, ('Are you taking an address of a cast? ' 'This is dangerous: could be a temp var. ' 'Take the address before doing the cast, rather than after')) def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ line = clean_lines.elided[linenum] match = Search(pattern, line) if not match: return False # Exclude lines with keywords that tend to look like casts context = line[0:match.start(1) - 1] if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): return False # Try expanding current context to see if we one level of # parentheses inside a macro. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 5), -1): context = clean_lines.elided[i] + context if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): return False # operator++(int) and operator--(int) if context.endswith(' operator++') or context.endswith(' operator--'): return False # A single unnamed argument for a function tends to look like old # style cast. If we see those, don't issue warnings for deprecated # casts, instead issue warnings for unnamed arguments where # appropriate. # # These are things that we want warnings for, since the style guide # explicitly require all parameters to be named: # Function(int); # Function(int) { # ConstMember(int) const; # ConstMember(int) const { # ExceptionMember(int) throw (...); # ExceptionMember(int) throw (...) { # PureVirtual(int) = 0; # # These are functions of some sort, where the compiler would be fine # if they had named parameters, but people often omit those # identifiers to reduce clutter: # (FunctionPointer)(int); # (FunctionPointer)(int) = value; # Function((function_pointer_arg)(int)) # Function((function_pointer_arg)(int), int param) # <TemplateArgument(int)>; # <(FunctionPointerTemplateArgument)(int)>; remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),])', remainder): # Looks like an unnamed parameter. # Don't warn on any kind of template arguments. if Match(r'^\s*>', remainder): return False # Don't warn on assignments to function pointers, but keep warnings for # unnamed parameters to pure virtual functions. Note that this pattern # will also pass on assignments of "0" to function pointers, but the # preferred values for those would be "nullptr" or "NULL". matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder) if matched_zero and matched_zero.group(1) != '0': return False # Don't warn on function pointer declarations. For this we need # to check what came before the "(type)" string. if Match(r'.*\)\s*$', line[0:match.start(0)]): return False # Don't warn if the parameter is named with block comments, e.g.: # Function(int /*unused_param*/); raw_line = clean_lines.raw_lines[linenum] if '/*' in raw_line: return False # Passed all filters, issue warning here. error(filename, linenum, 'readability/function', 3, 'All parameters should be named in a function') return True # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True def ExpectingFunctionArgs(clean_lines, linenum): """Checks whether where function type arguments are expected. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if the line at 'linenum' is inside something that expects arguments of function types. """ line = clean_lines.elided[linenum] return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or (linenum >= 2 and (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', clean_lines.elided[linenum - 1]) or Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', clean_lines.elided[linenum - 2]) or Search(r'\bstd::m?function\s*\<\s*$', clean_lines.elided[linenum - 1])))) _HEADERS_CONTAINING_TEMPLATES = ( ('<deque>', ('deque',)), ('<functional>', ('unary_function', 'binary_function', 'plus', 'minus', 'multiplies', 'divides', 'modulus', 'negate', 'equal_to', 'not_equal_to', 'greater', 'less', 'greater_equal', 'less_equal', 'logical_and', 'logical_or', 'logical_not', 'unary_negate', 'not1', 'binary_negate', 'not2', 'bind1st', 'bind2nd', 'pointer_to_unary_function', 'pointer_to_binary_function', 'ptr_fun', 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', 'mem_fun_ref_t', 'const_mem_fun_t', 'const_mem_fun1_t', 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', 'mem_fun_ref', )), ('<limits>', ('numeric_limits',)), ('<list>', ('list',)), ('<map>', ('map', 'multimap',)), ('<memory>', ('allocator',)), ('<queue>', ('queue', 'priority_queue',)), ('<set>', ('set', 'multiset',)), ('<stack>', ('stack',)), ('<string>', ('char_traits', 'basic_string',)), ('<utility>', ('pair',)), ('<vector>', ('vector',)), # gcc extensions. # Note: std::hash is their hash, ::hash is our hash ('<hash_map>', ('hash_map', 'hash_multimap',)), ('<hash_set>', ('hash_set', 'hash_multiset',)), ('<slist>', ('slist',)), ) _RE_PATTERN_STRING = re.compile(r'\bstring\b') _re_pattern_algorithm_header = [] for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap', 'transform'): # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or # type::max(). _re_pattern_algorithm_header.append( (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), _template, '<algorithm>')) _re_pattern_templates = [] for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: for _template in _templates: _re_pattern_templates.append( (re.compile(r'(\<|\b)' + _template + r'\s*\<'), _template + '<>', _header)) def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ if not filename_cc.endswith('.cc'): return (False, '') filename_cc = filename_cc[:-len('.cc')] if filename_cc.endswith('_unittest'): filename_cc = filename_cc[:-len('_unittest')] elif filename_cc.endswith('_test'): filename_cc = filename_cc[:-len('_test')] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') if not filename_h.endswith('.h'): return (False, '') filename_h = filename_h[:-len('.h')] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path def UpdateIncludeState(filename, include_dict, io=codecs): """Fill up the include_dict with new includes found from the file. Args: filename: the name of the header to read. include_dict: a dictionary in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was successfully added. False otherwise. """ headerfile = None try: headerfile = io.open(filename, 'r', 'utf8', 'replace') except IOError: return False linenum = 0 for line in headerfile: linenum += 1 clean_line = CleanseComments(line) match = _RE_PATTERN_INCLUDE.search(clean_line) if match: include = match.group(2) include_dict.setdefault(include, linenum) return True def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in xrange(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_algorithm_header: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: if pattern.search(line): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's flatten the include_state include_list and copy it into a dictionary. include_dict = dict([item for sublist in include_state.include_list for item in sublist]) # Did we find the header for this file (if any) and successfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_dict is modified during iteration, so we iterate over a copy of # the keys. header_keys = include_dict.keys() for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_dict, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if filename.endswith('.cc') and not header_found: return # All the lines have been processed, report the errors found. for required_header_unstripped in required: template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_dict: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template) _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<') def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): """Check that make_pair's template arguments are deduced. G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) if match: error(filename, linenum, 'build/explicit_make_pair', 4, # 4 = high confidence 'For C++11-compatibility, omit template arguments from make_pair' ' OR use pair directly OR if appropriate, construct a pair directly') def CheckDefaultLambdaCaptures(filename, clean_lines, linenum, error): """Check that default lambda captures are not used. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # A lambda introducer specifies a default capture if it starts with "[=" # or if it starts with "[&" _not_ followed by an identifier. match = Match(r'^(.*)\[\s*(?:=|&[^\w])', line) if match: # Found a potential error, check what comes after the lambda-introducer. # If it's not open parenthesis (for lambda-declarator) or open brace # (for compound-statement), it's not a lambda. line, _, pos = CloseExpression(clean_lines, linenum, len(match.group(1))) if pos >= 0 and Match(r'^\s*[{(]', line[pos:]): error(filename, linenum, 'build/c++11', 4, # 4 = high confidence 'Default lambda captures are an unapproved C++ feature.') def CheckRedundantVirtual(filename, clean_lines, linenum, error): """Check if line contains a redundant "virtual" function-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Look for "virtual" on current line. line = clean_lines.elided[linenum] virtual = Match(r'^(.*\bvirtual\b)', line) if not virtual: return # Look for the next opening parenthesis. This is the start of the # parameter list (possibly on the next line shortly after virtual). # TODO(unknown): doesn't work if there are virtual functions with # decltype() or other things that use parentheses, but csearch suggests # that this is rare. end_col = -1 end_line = -1 start_col = len(virtual.group(1)) for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())): line = clean_lines.elided[start_line][start_col:] parameter_list = Match(r'^([^(]*)\(', line) if parameter_list: # Match parentheses to find the end of the parameter list (_, end_line, end_col) = CloseExpression( clean_lines, start_line, start_col + len(parameter_list.group(1))) break start_col = 0 if end_col < 0: return # Couldn't find end of parameter list, give up # Look for "override" or "final" after the parameter list # (possibly on the next few lines). for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())): line = clean_lines.elided[i][end_col:] match = Search(r'\b(override|final)\b', line) if match: error(filename, linenum, 'readability/inheritance', 4, ('"virtual" is redundant since function is ' 'already declared as "%s"' % match.group(1))) # Set end_col to check whole lines after we are done with the # first line. end_col = 0 if Search(r'[^\w]\s*$', line): break def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): """Check if line contains a redundant "override" or "final" virt-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Check that at most one of "override" or "final" is present, not both line = clean_lines.elided[linenum] if Search(r'\boverride\b', line) and Search(r'\bfinal\b', line): error(filename, linenum, 'readability/inheritance', 4, ('"override" is redundant since function is ' 'already declared as "final"')) # Returns true if we are at a new block, and it is directly # inside of a namespace. def IsBlockInNameSpace(nesting_state, is_forward_declaration): """Checks that the new block is directly in a namespace. Args: nesting_state: The _NestingState object that contains info about our state. is_forward_declaration: If the class is a forward declared class. Returns: Whether or not the new block is directly in a namespace. """ if is_forward_declaration: if len(nesting_state.stack) >= 1 and ( isinstance(nesting_state.stack[-1], _NamespaceInfo)): return True else: return False return (len(nesting_state.stack) > 1 and nesting_state.stack[-1].check_namespace_indentation and isinstance(nesting_state.stack[-2], _NamespaceInfo)) def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, raw_lines_no_comments, linenum): """This method determines if we should apply our namespace indentation check. Args: nesting_state: The current nesting state. is_namespace_indent_item: If we just put a new class on the stack, True. If the top of the stack is not a class, or we did not recently add the class, False. raw_lines_no_comments: The lines without the comments. linenum: The current line number we are processing. Returns: True if we should apply our namespace indentation check. Currently, it only works for classes and namespaces inside of a namespace. """ is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments, linenum) if not (is_namespace_indent_item or is_forward_declaration): return False # If we are in a macro, we do not want to check the namespace indentation. if IsMacroDefinition(raw_lines_no_comments, linenum): return False return IsBlockInNameSpace(nesting_state, is_forward_declaration) # Call this method if the line is directly inside of a namespace. # If the line above is blank (excluding comments) or the start of # an inner namespace, it cannot be indented. def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum, error): line = raw_lines_no_comments[linenum] if Match(r'^\s+', line): error(filename, linenum, 'runtime/indentation_namespace', 4, 'Do not indent within a namespace') def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error) if nesting_state.InAsmBlock(): return CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, nesting_state, error) CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error) CheckVlogArguments(filename, clean_lines, line, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) CheckDefaultLambdaCaptures(filename, clean_lines, line, error) CheckRedundantVirtual(filename, clean_lines, line, error) CheckRedundantOverrideOrFinal(filename, clean_lines, line, error) for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error) def FlagCxx11Features(filename, clean_lines, linenum, error): """Flag those c++11 features that we only allow in certain places. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Flag unapproved C++11 headers. include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) if include and include.group(1) in ('cfenv', 'condition_variable', 'fenv.h', 'future', 'mutex', 'thread', 'chrono', 'ratio', 'regex', 'system_error', ): error(filename, linenum, 'build/c++11', 5, ('<%s> is an unapproved C++11 header.') % include.group(1)) # The only place where we need to worry about C++11 keywords and library # features in preprocessor directives is in macro definitions. if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return # These are classes and free functions. The classes are always # mentioned as std::*, but we only catch the free functions if # they're not found by ADL. They're alphabetical by header. for top_name in ( # type_traits 'alignment_of', 'aligned_union', # utility 'forward', ): if Search(r'\bstd::%s\b' % top_name, line): error(filename, linenum, 'build/c++11', 5, ('std::%s is an unapproved C++11 class or function. Send c-style ' 'an example of where it would make your code more readable, and ' 'they may let you use it.') % top_name) def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=[]): """Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ lines = (['// marker so line numbers and indices both start at 1'] + lines + ['// marker so line numbers end in a known way']) include_state = _IncludeState() function_state = _FunctionState() nesting_state = NestingState() ResetNolintSuppressions() CheckForCopyright(filename, lines, error) if file_extension == 'h': CheckForHeaderGuard(filename, lines, error) RemoveMultiLineComments(filename, lines, error) clean_lines = CleansedLines(lines) for line in xrange(clean_lines.NumLines()): ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions) FlagCxx11Features(filename, clean_lines, line, error) nesting_state.CheckCompletedBlocks(filename, error) CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) # We check here rather than inside ProcessLine so that we see raw # lines rather than "cleaned" lines. CheckForBadCharacters(filename, lines, error) CheckForNewlineAtEOF(filename, lines, error) def ProcessConfigOverrides(filename): """ Loads the configuration files and processes the config overrides. Args: filename: The name of the file being processed by the linter. Returns: False if the current |filename| should not be processed further. """ abs_filename = os.path.abspath(filename) cfg_filters = [] keep_looking = True while keep_looking: abs_path, base_name = os.path.split(abs_filename) if not base_name: break # Reached the root directory. cfg_file = os.path.join(abs_path, "CPPLINT.cfg") abs_filename = abs_path if not os.path.isfile(cfg_file): continue try: with open(cfg_file) as file_handle: for line in file_handle: line, _, _ = line.partition('#') # Remove comments. if not line.strip(): continue name, _, val = line.partition('=') name = name.strip() val = val.strip() if name == 'set noparent': keep_looking = False elif name == 'filter': cfg_filters.append(val) elif name == 'exclude_files': # When matching exclude_files pattern, use the base_name of # the current file name or the directory name we are processing. # For example, if we are checking for lint errors in /foo/bar/baz.cc # and we found the .cfg file at /foo/CPPLINT.cfg, then the config # file's "exclude_files" filter is meant to be checked against "bar" # and not "baz" nor "bar/baz.cc". if base_name: pattern = re.compile(val) if pattern.match(base_name): sys.stderr.write('Ignoring "%s": file excluded by "%s". ' 'File path component "%s" matches ' 'pattern "%s"\n' % (filename, cfg_file, base_name, val)) return False else: sys.stderr.write( 'Invalid configuration option (%s) in file %s\n' % (name, cfg_file)) except IOError: sys.stderr.write( "Skipping config file '%s': Can't open for reading\n" % cfg_file) keep_looking = False # Apply all the accumulated filters in reverse order (top-level directory # config options having the least priority). for filter in reversed(cfg_filters): _AddFilters(filter) return True def ProcessFile(filename, vlevel, extra_check_functions=[]): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) _BackupFilters() if not ProcessConfigOverrides(filename): _RestoreFilters() return lf_lines = [] crlf_lines = [] try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') # Remove trailing '\r'. # The -1 accounts for the extra trailing blank line we get from split() for linenum in range(len(lines) - 1): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') crlf_lines.append(linenum + 1) else: lf_lines.append(linenum + 1) except IOError: sys.stderr.write( "Skipping input '%s': Can't open for reading\n" % filename) _RestoreFilters() return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if filename != '-' and file_extension not in _valid_extensions: sys.stderr.write('Ignoring %s; not a valid file name ' '(%s)\n' % (filename, ', '.join(_valid_extensions))) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) # If end-of-line sequences are a mix of LF and CR-LF, issue # warnings on the lines with CR. # # Don't issue any warnings if all lines are uniformly LF or CR-LF, # since critique can handle these just fine, and the style guide # doesn't dictate a particular end of line sequence. # # We can't depend on os.linesep to determine what the desired # end-of-line sequence should be, since that will return the # server-side end-of-line sequence. if lf_lines and crlf_lines: # Warn on every line with CR. An alternative approach might be to # check whether the file is mostly CRLF or just LF, and warn on the # minority, we bias toward LF here since most tools prefer LF. for linenum in crlf_lines: Error(filename, linenum, 'whitespace/newline', 1, 'Unexpected \\r (^M) found; better to use only \\n') sys.stderr.write('Done processing %s\n' % filename) _RestoreFilters() def PrintUsage(message): """Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message. """ sys.stderr.write(_USAGE) if message: sys.exit('\nFATAL ERROR: ' + message) else: sys.exit(1) def PrintCategories(): """Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter. """ sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) sys.exit(0) def ParseArguments(args): """Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint. """ try: (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', 'counting=', 'filter=', 'root=', 'linelength=', 'extensions=']) except getopt.GetoptError: PrintUsage('Invalid arguments.') verbosity = _VerboseLevel() output_format = _OutputFormat() filters = '' counting_style = '' for (opt, val) in opts: if opt == '--help': PrintUsage(None) elif opt == '--output': if val not in ('emacs', 'vs7', 'eclipse'): PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.') output_format = val elif opt == '--verbose': verbosity = int(val) elif opt == '--filter': filters = val if not filters: PrintCategories() elif opt == '--counting': if val not in ('total', 'toplevel', 'detailed'): PrintUsage('Valid counting options are total, toplevel, and detailed') counting_style = val elif opt == '--root': global _root _root = val elif opt == '--linelength': global _line_length try: _line_length = int(val) except ValueError: PrintUsage('Line length must be digits.') elif opt == '--extensions': global _valid_extensions try: _valid_extensions = set(val.split(',')) except ValueError: PrintUsage('Extensions must be comma seperated list.') if not filenames: PrintUsage('No files were specified.') _SetOutputFormat(output_format) _SetVerboseLevel(verbosity) _SetFilters(filters) _SetCountingStyle(counting_style) return filenames def main(): filenames = ParseArguments(sys.argv[1:]) # Change stderr to write with replacement characters so we don't die # if we try to print something containing non-ASCII characters. sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') _cpplint_state.ResetErrorCounts() for filename in filenames: ProcessFile(filename, _cpplint_state.verbose_level) _cpplint_state.PrintErrorCounts() sys.exit(_cpplint_state.error_count > 0) if __name__ == '__main__': main()
{ "content_hash": "f4adf8c608483988da4c81d43dfe6023", "timestamp": "", "source": "github", "line_count": 5052, "max_line_length": 97, "avg_line_length": 39.54117181314331, "alnum_prop": 0.6374886114476227, "repo_name": "vianuevm/cppStyle", "id": "99403b8480a9ebdb72b00f87dcc5676b2df4c331", "size": "234785", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cpplint.py", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "8409" }, { "name": "CSS", "bytes": "5034" }, { "name": "HTML", "bytes": "17883" }, { "name": "JavaScript", "bytes": "11136" }, { "name": "Python", "bytes": "309693" } ], "symlink_target": "" }
"""Tests for `tanh.py`.""" from absl.testing import absltest from absl.testing import parameterized import chex from distrax._src.bijectors import sigmoid from distrax._src.bijectors import tanh import jax import jax.numpy as jnp import numpy as np from tensorflow_probability.substrates import jax as tfp tfb = tfp.bijectors RTOL = 1e-5 class TanhTest(parameterized.TestCase): def setUp(self): super().setUp() self.seed = jax.random.PRNGKey(1234) def test_properties(self): bijector = tanh.Tanh() self.assertEqual(bijector.event_ndims_in, 0) self.assertEqual(bijector.event_ndims_out, 0) self.assertFalse(bijector.is_constant_jacobian) self.assertFalse(bijector.is_constant_log_det) @chex.all_variants @parameterized.parameters( {'x_shape': (2,)}, {'x_shape': (2, 3)}, {'x_shape': (2, 3, 4)}) def test_forward_shapes(self, x_shape): x = jnp.zeros(x_shape) bijector = tanh.Tanh() y1 = self.variant(bijector.forward)(x) logdet1 = self.variant(bijector.forward_log_det_jacobian)(x) y2, logdet2 = self.variant(bijector.forward_and_log_det)(x) self.assertEqual(y1.shape, x_shape) self.assertEqual(y2.shape, x_shape) self.assertEqual(logdet1.shape, x_shape) self.assertEqual(logdet2.shape, x_shape) @chex.all_variants @parameterized.parameters( {'y_shape': (2,)}, {'y_shape': (2, 3)}, {'y_shape': (2, 3, 4)}) def test_inverse_shapes(self, y_shape): y = jnp.zeros(y_shape) bijector = tanh.Tanh() x1 = self.variant(bijector.inverse)(y) logdet1 = self.variant(bijector.inverse_log_det_jacobian)(y) x2, logdet2 = self.variant(bijector.inverse_and_log_det)(y) self.assertEqual(x1.shape, y_shape) self.assertEqual(x2.shape, y_shape) self.assertEqual(logdet1.shape, y_shape) self.assertEqual(logdet2.shape, y_shape) @chex.all_variants def test_forward(self): x = jax.random.normal(self.seed, (100,)) bijector = tanh.Tanh() y = self.variant(bijector.forward)(x) np.testing.assert_allclose(y, jnp.tanh(x), rtol=RTOL) @chex.all_variants def test_forward_log_det_jacobian(self): x = jax.random.normal(self.seed, (100,)) bijector = tanh.Tanh() fwd_logdet = self.variant(bijector.forward_log_det_jacobian)(x) actual = jnp.log(jax.vmap(jax.grad(bijector.forward))(x)) np.testing.assert_allclose(fwd_logdet, actual, rtol=1e-2) @chex.all_variants def test_forward_and_log_det(self): x = jax.random.normal(self.seed, (100,)) bijector = tanh.Tanh() y1 = self.variant(bijector.forward)(x) logdet1 = self.variant(bijector.forward_log_det_jacobian)(x) y2, logdet2 = self.variant(bijector.forward_and_log_det)(x) np.testing.assert_allclose(y1, y2, rtol=RTOL) np.testing.assert_allclose(logdet1, logdet2, rtol=RTOL) @chex.all_variants def test_inverse(self): x = jax.random.normal(self.seed, (100,)) bijector = tanh.Tanh() y = self.variant(bijector.forward)(x) x_rec = self.variant(bijector.inverse)(y) np.testing.assert_allclose(x_rec, x, rtol=1e-3) @chex.all_variants def test_inverse_log_det_jacobian(self): x = jax.random.normal(self.seed, (100,)) bijector = tanh.Tanh() y = self.variant(bijector.forward)(x) fwd_logdet = self.variant(bijector.forward_log_det_jacobian)(x) inv_logdet = self.variant(bijector.inverse_log_det_jacobian)(y) np.testing.assert_allclose(inv_logdet, -fwd_logdet, rtol=1e-3) @chex.all_variants def test_inverse_and_log_det(self): y = jax.random.normal(self.seed, (100,)) bijector = tanh.Tanh() x1 = self.variant(bijector.inverse)(y) logdet1 = self.variant(bijector.inverse_log_det_jacobian)(y) x2, logdet2 = self.variant(bijector.inverse_and_log_det)(y) np.testing.assert_allclose(x1, x2, rtol=RTOL) np.testing.assert_allclose(logdet1, logdet2, rtol=RTOL) @chex.all_variants def test_stability(self): bijector = tanh.Tanh() tfp_bijector = tfb.Tanh() x = np.array([-10.0, -3.3, 0.0, 3.3, 10.0], dtype=np.float32) fldj = tfp_bijector.forward_log_det_jacobian(x, event_ndims=0) fldj_ = self.variant(bijector.forward_log_det_jacobian)(x) np.testing.assert_allclose(fldj_, fldj, rtol=RTOL) y = bijector.forward(x) ildj = tfp_bijector.inverse_log_det_jacobian(y, event_ndims=0) ildj_ = self.variant(bijector.inverse_log_det_jacobian)(y) np.testing.assert_allclose(ildj_, ildj, rtol=RTOL) @chex.all_variants @parameterized.named_parameters( ('int16', np.array([0, 0], dtype=np.int16)), ('int32', np.array([0, 0], dtype=np.int32)), ('int64', np.array([0, 0], dtype=np.int64)), ) def test_integer_inputs(self, inputs): bijector = tanh.Tanh() output, log_det = self.variant(bijector.forward_and_log_det)(inputs) expected_out = jnp.tanh(inputs).astype(jnp.float32) expected_log_det = jnp.zeros_like(inputs, dtype=jnp.float32) np.testing.assert_array_equal(output, expected_out) np.testing.assert_array_equal(log_det, expected_log_det) def test_jittable(self): @jax.jit def f(x, b): return b.forward(x) bijector = tanh.Tanh() x = np.zeros(()) f(x, bijector) def test_same_as(self): bijector = tanh.Tanh() self.assertTrue(bijector.same_as(bijector)) self.assertTrue(bijector.same_as(tanh.Tanh())) self.assertFalse(bijector.same_as(sigmoid.Sigmoid())) if __name__ == '__main__': absltest.main()
{ "content_hash": "0dd7f8d0166cbd442a2dde319a047776", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 72, "avg_line_length": 33.3109756097561, "alnum_prop": 0.6749038989566173, "repo_name": "deepmind/distrax", "id": "2c049541284fa4332e77880cd717ed0563322aee", "size": "6159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "distrax/_src/bijectors/tanh_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "1044417" }, { "name": "Shell", "bytes": "3000" } ], "symlink_target": "" }
''' Non-relativistic Unrestricted Kohn-Sham ''' import numpy from pyscf import lib from pyscf.lib import logger from pyscf.scf import uhf from pyscf.dft import rks def get_veff(ks, mol=None, dm=None, dm_last=0, vhf_last=0, hermi=1): '''Coulomb + XC functional for UKS. See pyscf/dft/rks.py :func:`get_veff` fore more details. ''' if mol is None: mol = ks.mol if dm is None: dm = ks.make_rdm1() if not isinstance(dm, numpy.ndarray): dm = numpy.asarray(dm) if dm.ndim == 2: # RHF DM dm = numpy.asarray((dm*.5,dm*.5)) ks.initialize_grids(mol, dm) t0 = (logger.process_clock(), logger.perf_counter()) ground_state = (dm.ndim == 3 and dm.shape[0] == 2) ni = ks._numint if hermi == 2: # because rho = 0 n, exc, vxc = (0,0), 0, 0 else: max_memory = ks.max_memory - lib.current_memory()[0] n, exc, vxc = ni.nr_uks(mol, ks.grids, ks.xc, dm, max_memory=max_memory) if ks.nlc: assert 'VV10' in ks.nlc.upper() _, enlc, vnlc = ni.nr_rks(mol, ks.nlcgrids, ks.xc+'__'+ks.nlc, dm[0]+dm[1], max_memory=max_memory) exc += enlc vxc += vnlc logger.debug(ks, 'nelec by numeric integration = %s', n) t0 = logger.timer(ks, 'vxc', *t0) #enabling range-separated hybrids omega, alpha, hyb = ni.rsh_and_hybrid_coeff(ks.xc, spin=mol.spin) if abs(hyb) < 1e-10 and abs(alpha) < 1e-10: vk = None if (ks._eri is None and ks.direct_scf and getattr(vhf_last, 'vj', None) is not None): ddm = numpy.asarray(dm) - numpy.asarray(dm_last) vj = ks.get_j(mol, ddm[0]+ddm[1], hermi) vj += vhf_last.vj else: vj = ks.get_j(mol, dm[0]+dm[1], hermi) vxc += vj else: if (ks._eri is None and ks.direct_scf and getattr(vhf_last, 'vk', None) is not None): ddm = numpy.asarray(dm) - numpy.asarray(dm_last) vj, vk = ks.get_jk(mol, ddm, hermi) vk *= hyb if abs(omega) > 1e-10: vklr = ks.get_k(mol, ddm, hermi, omega) vklr *= (alpha - hyb) vk += vklr vj = vj[0] + vj[1] + vhf_last.vj vk += vhf_last.vk else: vj, vk = ks.get_jk(mol, dm, hermi) vj = vj[0] + vj[1] vk *= hyb if abs(omega) > 1e-10: vklr = ks.get_k(mol, dm, hermi, omega) vklr *= (alpha - hyb) vk += vklr vxc += vj - vk if ground_state: exc -=(numpy.einsum('ij,ji', dm[0], vk[0]).real + numpy.einsum('ij,ji', dm[1], vk[1]).real) * .5 if ground_state: ecoul = numpy.einsum('ij,ji', dm[0]+dm[1], vj).real * .5 else: ecoul = None vxc = lib.tag_array(vxc, ecoul=ecoul, exc=exc, vj=vj, vk=vk) return vxc def get_vsap(ks, mol=None): '''Superposition of atomic potentials S. Lehtola, Assessment of initial guesses for self-consistent field calculations. Superposition of Atomic Potentials: simple yet efficient, J. Chem. Theory Comput. 15, 1593 (2019). DOI: 10.1021/acs.jctc.8b01089. arXiv:1810.11659. This function evaluates the effective charge of a neutral atom, given by exchange-only LDA on top of spherically symmetric unrestricted Hartree-Fock calculations as described in S. Lehtola, L. Visscher, E. Engel, Efficient implementation of the superposition of atomic potentials initial guess for electronic structure calculations in Gaussian basis sets, J. Chem. Phys., in press (2020). The potentials have been calculated for the ground-states of spherically symmetric atoms at the non-relativistic level of theory as described in S. Lehtola, "Fully numerical calculations on atoms with fractional occupations and range-separated exchange functionals", Phys. Rev. A 101, 012516 (2020). DOI: 10.1103/PhysRevA.101.012516 using accurate finite-element calculations as described in S. Lehtola, "Fully numerical Hartree-Fock and density functional calculations. I. Atoms", Int. J. Quantum Chem. e25945 (2019). DOI: 10.1002/qua.25945 .. note:: This function will modify the input ks object. Args: ks : an instance of :class:`RKS` XC functional are controlled by ks.xc attribute. Attribute ks.grids might be initialized. Returns: matrix Vsap = Vnuc + J + Vxc. ''' Vsap = rks.get_vsap(ks, mol) return numpy.asarray([Vsap, Vsap]) def energy_elec(ks, dm=None, h1e=None, vhf=None): if dm is None: dm = ks.make_rdm1() if h1e is None: h1e = ks.get_hcore() if vhf is None or getattr(vhf, 'ecoul', None) is None: vhf = ks.get_veff(ks.mol, dm) if not (isinstance(dm, numpy.ndarray) and dm.ndim == 2): dm = dm[0] + dm[1] return rks.energy_elec(ks, dm, h1e, vhf) class UKS(rks.KohnShamDFT, uhf.UHF): '''Unrestricted Kohn-Sham See pyscf/dft/rks.py RKS class for document of the attributes''' def __init__(self, mol, xc='LDA,VWN'): uhf.UHF.__init__(self, mol) rks.KohnShamDFT.__init__(self, xc) def dump_flags(self, verbose=None): uhf.UHF.dump_flags(self, verbose) rks.KohnShamDFT.dump_flags(self, verbose) return self def initialize_grids(self, mol=None, dm=None): ground_state = (isinstance(dm, numpy.ndarray) and dm.ndim == 3 and dm.shape[0] == 2) if ground_state: super().initialize_grids(mol, dm[0]+dm[1]) else: super().initialize_grids(mol) return self get_veff = get_veff get_vsap = get_vsap energy_elec = energy_elec init_guess_by_vsap = rks.init_guess_by_vsap def nuc_grad_method(self): from pyscf.grad import uks return uks.Gradients(self)
{ "content_hash": "8c40878d6387372360e8c4a3d86d71e0", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 87, "avg_line_length": 34.53757225433526, "alnum_prop": 0.5834309623430962, "repo_name": "sunqm/pyscf", "id": "49fdf0c54feb18e447c16dce4e84202d6bc8d916", "size": "6657", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pyscf/dft/uks.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2805171" }, { "name": "CMake", "bytes": "19597" }, { "name": "Common Lisp", "bytes": "40515" }, { "name": "Dockerfile", "bytes": "447" }, { "name": "Makefile", "bytes": "6797" }, { "name": "Python", "bytes": "19630497" }, { "name": "Roff", "bytes": "429" }, { "name": "Shell", "bytes": "6564" } ], "symlink_target": "" }
import os.path import argparse import subprocess import json from spinalcordtoolbox.utils.sys import printv from spinalcordtoolbox.utils.fs import extract_fname required_minc_cmdline_tools = ['mincinfo', 'minctoraw'] def console_log(message): printv(message) def cmd(command): return subprocess.check_output(command.split(), universal_newlines=True).strip() def get_space(mincfile, space): header = { "start": float(cmd("mincinfo -attval {}:start {}".format(space, mincfile))), "space_length": float(cmd("mincinfo -dimlength {} {}".format(space, mincfile))), "step": float(cmd("mincinfo -attval {}:step {}".format(space, mincfile))), } cosines = cmd("mincinfo -attval {}:direction_cosines {}".format(space, mincfile)) cosines = cosines.strip().split() if len(cosines) > 1: header["direction_cosines"] = list(map(float, cosines)) return header def make_header(mincfile, headerfile): header = {} # find dimension order order = cmd("mincinfo -attval image:dimorder {}".format(mincfile)) order = order.split(",") if len(order) < 3 or len(order) > 4: order = cmd("mincinfo -dimnames {}".format(mincfile)) order = order.split(" ") header["order"] = order if len(order) == 4: time_start = cmd("mincinfo -attval time:start {}".format(mincfile)) time_length = cmd("mincinfo -dimlength time {}".format(mincfile)) header["time"] = {"start": float(time_start), "space_length": float(time_length)} # find space header["xspace"] = get_space(mincfile, "xspace") header["yspace"] = get_space(mincfile, "yspace") header["zspace"] = get_space(mincfile, "zspace") if len(order) > 3: header["time"] = get_space(mincfile, "time") # write out the header open(headerfile, "w").write(json.dumps(header)) def make_raw(mincfile, rawfile): raw = open(rawfile, "wb") raw.write( subprocess.check_output(["minctoraw", "-byte", "-unsigned", "-normalize", mincfile])) def main(filename, fname_out=''): if not os.path.isfile(filename): console_log("File {} does not exist.".format(filename)) if fname_out != '': path_out, file_out, ext_out = extract_fname(fname_out) basename = path_out + file_out else: basename = os.path.basename(filename) headername = "{}.header".format(basename) rawname = "{}.raw".format(basename) console_log("Processing file: {}".format(filename)) console_log("Creating header file: {}".format(headername)) make_header(filename, headername) console_log("Creating raw data file: {}".format(rawname)) make_raw(filename, rawname) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("filename", help="absolute path of input image") parser.add_argument("-o", "--fname_out", action="store", default="", help="absolute path of output image (without image format)") args = parser.parse_args() main(args.filename, args.fname_out)
{ "content_hash": "5f157f771a7f979d1f98fc639734cab6", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 133, "avg_line_length": 30.455445544554454, "alnum_prop": 0.6375162548764629, "repo_name": "neuropoly/spinalcordtoolbox", "id": "7cede09423b1435c3cc1fd7479f01bdabf2c7a05", "size": "4084", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spinalcordtoolbox/scripts/isct_minc2volume-viewer.py", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "5931" }, { "name": "C++", "bytes": "629016" }, { "name": "CMake", "bytes": "7000" }, { "name": "CSS", "bytes": "1237" }, { "name": "Dockerfile", "bytes": "293" }, { "name": "HTML", "bytes": "11480" }, { "name": "JavaScript", "bytes": "3171" }, { "name": "MATLAB", "bytes": "120557" }, { "name": "Python", "bytes": "2052822" }, { "name": "Rich Text Format", "bytes": "1619" }, { "name": "Shell", "bytes": "61227" } ], "symlink_target": "" }
import argparse from dirbalak import describe from dirbalak import discover from dirbalak import cleanbuild from dirbalak import setoperation from dirbalak import repomirrorcache from dirbalak import unreferencedlabels from dirbalak import traverse from dirbalak import scriptolog from upseto import gitwrapper import logging import yaml logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest="cmd") describeCmd = subparsers.add_parser( "describe", help="Describe the exact hashes of a single project/hash") describeCmd.add_argument("--gitURL", required=True) describeCmd.add_argument("--hash", required=True) describeCmd.add_argument( "--noFetch", action="store_true", help="dont git fetch anything, use already fetched data only") describeCmd.add_argument( "--noDirbalakBuildRootFSArcs", action="store_true", help="do not show solvent dependencies in the project dirbalak uses for clean build rootfs") describeCmd.add_argument( "--noSolventRootFSArcs", action="store_true", help="do not show solvent dependencies in projects that starts with 'rootfs-'") describeCmd.add_argument("--graphicOutput", help="use dot to plot the output") describeCmd.add_argument("--dotOutput", help="save dot file") discoverCmd = subparsers.add_parser( "discover", help="Discover the inter-repository dependencies") discoverCmd.add_argument( "--currentProject", action='store_true', help="Add the current git project origin url to the project list to start discovery from") discoverCmd.add_argument( "--gitURL", nargs="*", default=[], help="Add this url to the discovery project list") discoverCmd.add_argument( "--multiverseFile", help="read multiverse file, will be used only for clustering, unless " "--projectsFromMultiverse is specified") discoverCmd.add_argument( "--projectsFromMultiverse", action='store_true', help="use the project list in the multiverse file") discoverCmd.add_argument("--graphicOutput", help="use dot to plot the output") discoverCmd.add_argument("--dotOutput", help="save dot file") discoverCmd.add_argument( "--noFetch", action="store_true", help="dont git fetch anything, use already fetched data only") discoverCmd.add_argument( "--officialObjectStore", help="object store to test existance of labels in, to determine if built") discoverCmd.add_argument( "--noDirbalakBuildRootFSArcs", action="store_true", help="do not show solvent dependencies in the project dirbalak uses for clean build rootfs") discoverCmd.add_argument( "--noSolventRootFSArcs", action="store_true", help="do not show solvent dependencies in projects that starts with 'rootfs-'") cleanbuildCmd = subparsers.add_parser( "cleanbuild", help="cleanly build a project") whatGroup = cleanbuildCmd.add_mutually_exclusive_group(required=True) whatGroup.add_argument("--gitURL") whatGroup.add_argument("--currentProject", action='store_true') cleanbuildCmd.add_argument("--hash", default="origin/master") cleanbuildCmd.add_argument("--nosubmit", action="store_true") cleanbuildCmd.add_argument( "--rootfs", help="label to build in. a dirbalak manifest should not exist " "to use this option") setCmd = subparsers.add_parser( "set", help="set dirbalak parameters") setCmd.add_argument( "key", help="one of: " "'buildRootFSRepositoryBasename' " "(==solvent requirement basename for rootfs product to build cleanly inside) " "'buildRootFSLabel' " "(==solvent label for to use as a rootfs to build cleanly inside. " "mutually exclusive with buildRootFSRepositoryBasename. Please do not use this but for " "bootstrapping rootfs projects)") setCmd.add_argument("value") unreferencedLabelsCmd = subparsers.add_parser( "unreferencedLabels", help="Find which labels are not referenced") unreferencedLabelsCmd.add_argument("--multiverseFile", required=True) unreferencedLabelsCmd.add_argument("--objectStore", required=True) unreferencedLabelsCmd.add_argument( "--noFetch", action="store_true", help="dont git fetch anything, use already fetched data only") scriptologCmd = subparsers.add_parser( "scriptolog", help="render a script") scriptSubparser = scriptologCmd.add_subparsers(dest="script") updateAllDependenciesScript = scriptSubparser.add_parser("updateAllDependencies") updateAllDependenciesScript.add_argument("--gitURL") args = parser.parse_args() if getattr(args, 'noFetch', False): repomirrorcache.fetch = False if args.cmd == 'describe': describeInstance = describe.Describe( gitURL=args.gitURL, hash=args.hash, dirbalakBuildRootFSArcs=not args.noDirbalakBuildRootFSArcs, solventRootFSArcs=not args.noSolventRootFSArcs) print describeInstance.renderText() if args.graphicOutput: graph = describeInstance.makeGraph() graph.saveSvg(args.graphicOutput) logging.info("Saved '%(graphicOutput)s'", dict(graphicOutput=args.graphicOutput)) if args.dotOutput: graph = describeInstance.makeGraph() graph.saveDot(args.dotOutput) elif args.cmd == "discover": projects = list(args.gitURL) if args.currentProject: projects.append(gitwrapper.GitWrapper('.').originURL()) clusterMap = dict() if args.multiverseFile: with open(args.multiverseFile) as f: multiverse = yaml.load(f.read()) if not args.noFetch: repomirrorcache.prepopulate(p['gitURL'] for p in multiverse['PROJECTS']) clusterMap = { gitwrapper.originURLBasename(p['gitURL']): p['group'] for p in multiverse['PROJECTS']} if args.projectsFromMultiverse: projects += [p['gitURL'] for p in multiverse['PROJECTS']] if len(projects) == 0: raise Exception("No projects specified in command line") discoverInstance = discover.Discover( projects=projects, objectStore=args.officialObjectStore, clusterMap=clusterMap, dirbalakBuildRootFSArcs=not args.noDirbalakBuildRootFSArcs, solventRootFSArcs=not args.noSolventRootFSArcs) print discoverInstance.renderText() if args.graphicOutput: graph = discoverInstance.makeGraph() graph.saveSvg(args.graphicOutput) logging.info("Saved '%(graphicOutput)s'", dict(graphicOutput=args.graphicOutput)) if args.dotOutput: graph = discoverInstance.makeGraph() graph.saveDot(args.dotOutput) elif args.cmd == "cleanbuild": gitURL = gitwrapper.GitWrapper(".").originURL() if args.currentProject else args.gitURL cleanbuild.CleanBuild( gitURL=gitURL, hash=args.hash, submit=not args.nosubmit, buildRootFS=args.rootfs).go() elif args.cmd == "set": setoperation.SetOperation(key=args.key, value=args.value).go() elif args.cmd == "unreferencedLabels": with open(args.multiverseFile) as f: multiverse = yaml.load(f.read()) instance = unreferencedlabels.UnreferencedLabels( projects=[p['gitURL'] for p in multiverse['PROJECTS']], objectStore=args.objectStore) for label in instance.unreferencedLabels(): print label elif args.cmd == "scriptolog": logging.getLogger().setLevel(logging.ERROR) if args.script == "updateAllDependencies": traverseInstance = traverse.Traverse() traverseInstance.traverse(args.gitURL, 'origin/master') print scriptolog.Scriptolog(traverseInstance).updateAllDependencies(args.gitURL) else: raise AssertionError("Unknown script") else: assert False, "command mismatch"
{ "content_hash": "129b0785c2b337081fb135758fc0a694", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 98, "avg_line_length": 43.5632183908046, "alnum_prop": 0.7295514511873351, "repo_name": "Stratoscale/dirbalak", "id": "749f82bcc692687850d892324100dcddf181ebf4", "size": "7580", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "py/dirbalak/main.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "340" }, { "name": "HTML", "bytes": "21593" }, { "name": "JavaScript", "bytes": "4477" }, { "name": "Makefile", "bytes": "2024" }, { "name": "Python", "bytes": "120641" }, { "name": "Shell", "bytes": "42" } ], "symlink_target": "" }
""" Indexer.py Calls tools.helpers.build_index() """ from tools import * if __name__ == "__main__": build_index()
{ "content_hash": "5e1841d9dc608ee900a7c44d40967ee7", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 33, "avg_line_length": 12.1, "alnum_prop": 0.5867768595041323, "repo_name": "visualdensity/nltk-tools", "id": "7db3ced192820977fd8134c598c2d2dcd8118617", "size": "162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "indexer.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "162" } ], "symlink_target": "" }
from YSeq import YSeq from YRules import YRules from YConstants import YConstants class YDNA(YSeq): """ En: This class represents a DNA sequence Ru: Данный класс инкапсулирует последовательность ДНК """ __list_of_nucleotides = ['A', 'T', 'C', 'G', '_'] def __init__(self, dna_sequence): self.__check_dna_mistakes(dna_sequence) super.__init__(dna_sequence) def append(self, symbol): self.__check_dna_mistakes(symbol) super.append(symbol) @staticmethod def nucleotides_count(): """ En: This method returns count of nucleotides as tuple Ru: Данный метод возвращает количество нуклеотидов A C G и T в виде кортежа :return: Tuple that contains the count of A C G and T: (A, C, G, T) """ a_count = super.count('A') c_count = super.count('C') g_count = super.count('G') t_count = super.count('T') return a_count, c_count, g_count, t_count def __check_dna_mistakes(self, dna_sequence): """ En: This method checks the DNA sequence errors :param dna_sequence: custom DNA sequence """ for nucleotide in dna_sequence: if nucleotide not in self.__list_of_nucleotides: raise ValueError(nucleotide) def complement(self): """ :return: """ complement = [] [complement.append(YRules.complement_dna[x]) for x in self._sequence] return complement def reverse_complement(self): """ :return: """ return self.Complement()[::-1] def entries_indexes(self, sub_sequence, indexing='zero_based'): """ :param sub_sequence: :param indexing: :return: """ indexes = [] dna_sequence = ''.join(self._sequence) start = 0 while True: current_position = dna_sequence.find(str(sub_sequence), start) if current_position != -1: start = current_position + 1 indexes.append(current_position + YConstants.indexing[indexing]) else: break return indexes
{ "content_hash": "0dee2da3902d25302e0f013e5b2b0bff", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 83, "avg_line_length": 28.907894736842106, "alnum_prop": 0.5653163404642695, "repo_name": "YuriShporhun/YBio", "id": "7066a1413162500a584a9d10fbb122e89eb7dffa", "size": "2345", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/YDNA.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "15162" } ], "symlink_target": "" }
import py.path from _pytest.config import Config, PytestPluginManager, default_plugins try: # pytest >= 3.4 from _pytest.nodes import FSCollector except ImportError: # pytest < 3.4 from _pytest.main import FSCollector class GraftedSubSession(FSCollector): """ Collects test files from outside of the file tree of the current pytest session. By default, pytest will only collect files from the directories with which it was invoked (or the current working directory, if none). With this, a "sub-session" may be collected from outside of the scope of the pytest session, e.g., in a third-party package. Args: name (str): The name of this grafted session. parent (Collector): The parent pytest collector. fspath (str): The directory from which files should be collected. """ def __init__(self, name, parent, fspath): fspath = py.path.local(fspath) # Get a new configuration for our path, which may be outside of the # scope of the parent pytest session. config = _build_config_for_path(fspath) super(GraftedSubSession, self).__init__(fspath, parent=parent, config=config) # Use our given name, rather than the path-based name set by :class:`FSCollector`. self.name = name @property def gethookproxy(self): return self.session.gethookproxy @property def _fixturemanager(self): return self.session._fixturemanager def reportinfo(self): return self.fspath, None, "" def collect(self): self._fixturemanager.parsefactories(self) for path in self.fspath.visit(fil=lambda x: x.check(file=1), rec=self._recurse, bf=True, sort=True): for f in self._collectfile(path): yield f def _collectfile(self, path): ihook = self.gethookproxy(path) if ihook.pytest_ignore_collect(path=path, config=self.config): return () return ihook.pytest_collect_file(path=path, parent=self) def _recurse(self, path): ihook = self.gethookproxy(path.dirpath()) if ihook.pytest_ignore_collect(path=path, config=self.config): return ihook = self.gethookproxy(path) ihook.pytest_collect_directory(path=path, parent=self) return True def _build_config_for_path(path): """ Builds and returns a basic test configuration rooted at the given path. Args: path (LocalPath): The path to the files under test. Returns: Config: The generated test configuration. """ # Find the root directory of the package containing our files. for rootdir in path.parts(reverse=True): if rootdir.join("setup.py").exists(): break else: rootdir = path # Initialize a base configuration as pytest would. pluginmanager = PytestPluginManager() for spec in default_plugins: pluginmanager.import_plugin(spec) config = Config(pluginmanager) # Ensure that pytest sets its root directory (``config.rootdir``) to the # given path. If we don't, then using this configuration from outside of # this path will confuse pytest. args = [rootdir] config.parse(args) return config
{ "content_hash": "ff72c8243843901539c2626113172dc2", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 90, "avg_line_length": 31.18867924528302, "alnum_prop": 0.6530550514216575, "repo_name": "elliterate/capybara.py", "id": "7383250699e1eb24ab87b2c4be7626eb97e8c7f9", "size": "3306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "capybara/tests/collector.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "38254" }, { "name": "JavaScript", "bytes": "5225" }, { "name": "Python", "bytes": "573480" } ], "symlink_target": "" }
def extractTurtleandHareTranslations(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if 'Time (对的时间对的人)' in item['title'] or 'Time (对的时间对的人)' in item['tags']: return buildReleaseMessageWithType(item, 'Time', vol, chp, frag=frag, postfix=postfix) return False
{ "content_hash": "896a10f52c458081f3feb051d923d556", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 88, "avg_line_length": 39, "alnum_prop": 0.7128205128205128, "repo_name": "fake-name/ReadableWebProxy", "id": "bd12e98c410c563abd7e8f5a4791149fbba66a9a", "size": "418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebMirror/management/rss_parser_funcs/feed_parse_extractTurtleandHareTranslations.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "105811" }, { "name": "Dockerfile", "bytes": "1178" }, { "name": "HTML", "bytes": "119737" }, { "name": "JavaScript", "bytes": "3006524" }, { "name": "Jupyter Notebook", "bytes": "148075" }, { "name": "Mako", "bytes": "1454" }, { "name": "Python", "bytes": "5264346" }, { "name": "Shell", "bytes": "1059" } ], "symlink_target": "" }
"""Python Stub implementation of tiger""" from concurrent import futures import time from subprocess import Popen, PIPE import grpc from tiger import cart_pb2, cart_pb2_grpc from tiger import search_pb2, search_pb2_grpc _ONE_DAY_IN_SECONDS = 60 * 60 * 24 class CartManager(cart_pb2_grpc.CartManagerServicer): def GetCart(self, request, context): return cart_pb2.GetCartResponse() class DocumentSearch(search_pb2_grpc.DocumentSearchServicer): def FindDocument(self, request, context): return search_pb2.FindDocumentResponse() def serve(port, with_proxy_server=False): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) cart_pb2_grpc.add_CartManagerServicer_to_server(CartManager(), server) search_pb2_grpc.add_DocumentSearchServicer_to_server(DocumentSearch(), server) server.add_insecure_port('[::]:{}'.format(port)) server.start() proxy_process = None try: if with_proxy_server: proxy_process = Popen(['tiger-rest-proxy']) while True: time.sleep(_ONE_DAY_IN_SECONDS) except KeyboardInterrupt: if proxy_process is not None: proxy_process.terminate() server.stop(0) def main(): import argparse parser = argparse.ArgumentParser( description='Run tiger, optionally with the REST Proxy Server', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-p', '--port', type=str, action='store', default=8081, help='server port') parser.add_argument('--with-proxy-server', action='store_true', default=False, help='Start the rest proxy server') args = parser.parse_args() serve(args.port, args.with_proxy_server) if __name__ == '__main__': main()
{ "content_hash": "48236b578e245da95fef3b1c737c1357", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 82, "avg_line_length": 23.974025974025974, "alnum_prop": 0.6598049837486457, "repo_name": "dillonhicks/gotham", "id": "3157dab3b9e594ac3bce3c5f3286a6ee7008420f", "size": "1846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server-stubs.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "1423" }, { "name": "Makefile", "bytes": "4823" }, { "name": "Protocol Buffer", "bytes": "2398" }, { "name": "Python", "bytes": "22525" }, { "name": "Shell", "bytes": "1560" } ], "symlink_target": "" }
import amsoil.core.pluginmanager as pm import amsoil.core.log logger=amsoil.core.log.getLogger('dhcpgeniv3delegate') GENIv3DelegateBase = pm.getService('geniv3delegatebase') geni_ex = pm.getService('geniv3exceptions') dhcp_ex = pm.getService('dhcpexceptions') class DHCPGENI3Delegate(GENIv3DelegateBase): """ """ URN_PREFIX = 'urn:DHCP_AM' # TODO should also include a changing component, identified by a config key def __init__(self): super(DHCPGENI3Delegate, self).__init__() self._resource_manager = pm.getService("dhcpresourcemanager") def get_request_extensions_mapping(self): """Documentation see [geniv3rpc] GENIv3DelegateBase.""" return {'dhcp' : 'http://example.com/dhcp'} # /request.xsd def get_manifest_extensions_mapping(self): """Documentation see [geniv3rpc] GENIv3DelegateBase.""" return {'dhcp' : 'http://example.com/dhcp'} # /manifest.xsd def get_ad_extensions_mapping(self): """Documentation see [geniv3rpc] GENIv3DelegateBase.""" return {'dhcp' : 'http://example.com/dhcp'} # /ad.xsd def is_single_allocation(self): """Documentation see [geniv3rpc] GENIv3DelegateBase. We allow to address single slivers (IPs) rather than the whole slice at once.""" return False def get_allocation_mode(self): """Documentation see [geniv3rpc] GENIv3DelegateBase. We allow to incrementally add new slivers (IPs).""" return 'geni_many' def list_resources(self, client_cert, credentials, geni_available): """Documentation see [geniv3rpc] GENIv3DelegateBase.""" client_urn, client_uuid, client_email = self.auth(client_cert, credentials, None, ('listslices',)) root_node = self.lxml_ad_root() E = self.lxml_ad_element_maker('dhcp') for lease in self._resource_manager.get_all_leases(): if (not lease["available"]) and geni_available: continue # taking care of geni_available r = E.resource() r.append(E.available("True" if lease["available"] else "False")) # possible to list other properties r.append(E.ip(lease["ip_str"])) root_node.append(r) return self.lxml_to_string(root_node) def describe(self, urns, client_cert, credentials): """Documentation see [geniv3rpc] GENIv3DelegateBase.""" rspec, sliver_list = self.status(urns, client_cert, credentials) return rspec def allocate(self, slice_urn, client_cert, credentials, rspec, end_time=None): """Documentation see [geniv3rpc] GENIv3DelegateBase.""" client_urn, client_uuid, client_email = self.auth(client_cert, credentials, slice_urn, ('createsliver',)) requested_ips = [] # parse RSpec -> requested_ips rspec_root = self.lxml_parse_rspec(rspec) for elm in rspec_root.getchildren(): if not self.lxml_elm_has_request_prefix(elm, 'dhcp'): raise geni_ex.GENIv3BadArgsError("RSpec contains elements/namespaces I dont understand (%s)." % (elm,)) if (self.lxml_elm_equals_request_tag(elm, 'dhcp', 'ip')): requested_ips.append(elm.text.strip()) elif (self.lxml_elm_equals_request_tag(elm, 'dhcp', 'iprange')): pass # raise geni_ex.GENIv3GeneralError('IP ranges in RSpecs are not supported yet.') # TODO else: raise geni_ex.GENIv3BadArgsError("RSpec contains an element I dont understand (%s)." % (elm,)) reserved_leases = [] for rip in requested_ips: try: reserved_leases.append(self._resource_manager.reserve_lease(rip, slice_urn, client_uuid, client_email, end_time)) except dhcp_ex.DHCPLeaseNotFound as e: # translate the resource manager exceptions to GENI exceptions raise geni_ex.GENIv3SearchFailedError("The desired IP(s) could no be found (%s)." % (rip,)) except dhcp_ex.DHCPLeaseAlreadyTaken as e: raise geni_ex.GENIv3AlreadyExistsError("The desired IP(s) is already taken (%s)." % (rip,)) # assemble sliver list sliver_list = [self._get_sliver_status_hash(lease, True, True, "") for lease in reserved_leases] return self.lxml_to_string(self._get_manifest_rspec(reserved_leases)), sliver_list def renew(self, urns, client_cert, credentials, expiration_time, best_effort): """Documentation see [geniv3rpc] GENIv3DelegateBase.""" # this code is similar to the provision call # TODO honor best effort leases = [] for urn in urns: if (self.urn_type(urn) == 'slice'): client_urn, client_uuid, client_email = self.auth(client_cert, credentials, urn, ('renewsliver',)) # authenticate for each given slice slice_leases = self._resource_manager.leases_in_slice(urn) for lease in slice_leases: # extend the lease, so we have a longer timeout. try: self._resource_manager.extend_lease(lease["ip_str"], expiration_time) except dhcp_ex.DHCPMaxLeaseDurationExceeded as e: raise geni_ex.GENIv3BadArgsError("Lease can not be extended that long (%s)" % (str(e),)) leases.extend(slice_leases) else: raise geni_ex.GENIv3OperationUnsupportedError('Only slice URNs can be renewed in this aggregate') # we could use _urn_to_ip helper method for mapping sliver URNs to IPs if len(leases) == 0: raise geni_ex.GENIv3SearchFailedError("There are no resources in the given slice(s)") return [self._get_sliver_status_hash(lease, True, True, "") for lease in leases] def provision(self, urns, client_cert, credentials, best_effort, end_time, geni_users): """Documentation see [geniv3rpc] GENIv3DelegateBase. {geni_users} is not relevant here.""" # TODO honor best_effort option provisioned_leases = [] for urn in urns: if (self.urn_type(urn) == 'slice'): client_urn, client_uuid, client_email = self.auth(client_cert, credentials, urn, ('createsliver',)) # authenticate for each given slice leases = self._resource_manager.leases_in_slice(urn) for lease in leases: # extend the lease, so we have a longer timeout. try: self._resource_manager.extend_lease(lease["ip_str"], end_time) except dhcp_ex.DHCPMaxLeaseDurationExceeded as e: raise geni_ex.GENIv3BadArgsError("Lease can not be extended that long (%s)" % (str(e),)) # usually you would really instanciate resources here (not necessary for IP-resources) provisioned_leases.extend(leases) else: raise geni_ex.GENIv3OperationUnsupportedError('Only slice URNs can be provisioned by this aggregate') # we could use _urn_to_ip helper method for mapping sliver URNs to IPs if len(provisioned_leases) == 0: raise geni_ex.GENIv3SearchFailedError("There are no resources in the given slice(s); perform allocate first") # assemble return values sliver_list = [self._get_sliver_status_hash(lease, True, True, "") for lease in provisioned_leases] return self.lxml_to_string(self._get_manifest_rspec(provisioned_leases)), sliver_list def status(self, urns, client_cert, credentials): """Documentation see [geniv3rpc] GENIv3DelegateBase.""" # This code is similar to the provision call. leases = [] for urn in urns: if (self.urn_type(urn) == 'slice'): client_urn, client_uuid, client_email = self.auth(client_cert, credentials, urn, ('sliverstatus',)) # authenticate for each given slice slice_leases = self._resource_manager.leases_in_slice(urn) leases.extend(slice_leases) else: raise geni_ex.GENIv3OperationUnsupportedError('Only slice URNs can be given to status in this aggregate') # we could use _urn_to_ip helper method for mapping sliver URNs to IPs if len(leases) == 0: raise geni_ex.GENIv3SearchFailedError("There are no resources in the given slice(s)") # assemble return values # logger.info(str(leases)) sliver_list = [self._get_sliver_status_hash(lease, True, True, "") for lease in leases] return self.lxml_to_string(self._get_manifest_rspec(leases)), sliver_list def perform_operational_action(self, urns, client_cert, credentials, action, best_effort): # could have similar structure like the provision call # You should check for the GENI-default actions like GENIv3DelegateBase.OPERATIONAL_ACTION_xxx raise geni_ex.GENIv3OperationUnsupportedError("DHCP leases do not have operational state.") def delete(self, urns, client_cert, credentials, best_effort): """Documentation see [geniv3rpc] GENIv3DelegateBase.""" # This code is similar to the provision call. leases = [] for urn in urns: if (self.urn_type(urn) == 'slice'): client_urn, client_uuid, client_email = self.auth(client_cert, credentials, urn, ('deletesliver',)) # authenticate for each given slice slice_leases = self._resource_manager.leases_in_slice(urn) for lease in slice_leases: self._resource_manager.free_lease(lease["ip_str"]) leases.extend(slice_leases) else: raise geni_ex.GENIv3OperationUnsupportedError('Only slice URNs can be deleted in this aggregate') # we could use _urn_to_ip helper method for mapping sliver URNs to IPs if len(leases) == 0: raise geni_ex.GENIv3SearchFailedError("There are no resources in the given slice(s)") # assemble return values return [self._get_sliver_status_hash(lease, True, True, "") for lease in leases] def shutdown(self, slice_urn, client_cert, credentials): """Documentation see [geniv3rpc] GENIv3DelegateBase.""" # client_urn, client_uuid, client_email = self.auth(client_cert, credentials, slice_urn, ('shutdown',)) raise geni_ex.GENIv3GeneralError("Method not implemented") return True # Helper methods def _ip_to_urn(self, ip_str): """Helper method to map IPs to URNs.""" return ("%s:%s" % (self.URN_PREFIX, ip_str.replace('.', '-'))) def _urn_to_ip_str(self, urn): """Helper method to map URNs to IPs.""" if (urn.startswith(self.URN_PREFIX)): return urn[len(self.URN_PREFIX)+1:].replace('-', '.') else: raise geni_ex.GENIv3BadArgsError("The given URN is not valid for this AM (%s)" %(urn,)) def _get_sliver_status_hash(self, lease, include_allocation_status=False, include_operational_status=False, error_message=None): """Helper method to create the sliver_status return values of allocate and other calls.""" result = {'geni_sliver_urn' : self._ip_to_urn(str(lease["ip_str"])), 'geni_expires' : lease["end_time"], 'geni_allocation_status' : self.ALLOCATION_STATE_ALLOCATED} result['geni_allocation_status'] = self.ALLOCATION_STATE_UNALLOCATED if lease["available"] else self.ALLOCATION_STATE_PROVISIONED if (include_operational_status): # there is no state to an ip, so we always return ready result['geni_operational_status'] = self.OPERATIONAL_STATE_READY if (error_message): result['geni_error'] = error_message return result def _get_manifest_rspec(self, leases): E = self.lxml_manifest_element_maker('dhcp') manifest = self.lxml_manifest_root() sliver_list = [] for lease in leases: # assemble manifest r = E.resource() r.append(E.ip(lease["ip_str"])) # TODO add more info here manifest.append(r) return manifest
{ "content_hash": "c656c626f18fbd4d414b66735a7a4ab7", "timestamp": "", "source": "github", "line_count": 233, "max_line_length": 151, "avg_line_length": 53.02575107296137, "alnum_prop": 0.6246054229057062, "repo_name": "motine/Ohouse", "id": "2f0a46db075b59a0058566161f2cbdb453030916", "size": "12356", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "src/vendor/dhcpgeni3/dhcpgenithreedelegate.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "265931" }, { "name": "Shell", "bytes": "520" } ], "symlink_target": "" }
"""Tests for field serialization.""" from collections import namedtuple, OrderedDict import datetime as dt import itertools import decimal import uuid import ipaddress import math import pytest from marshmallow import Schema, fields, missing as missing_ from tests.base import User, ALL_FIELDS, central, GenderEnum, HairColorEnum, DateEnum class DateTimeList: def __init__(self, dtimes): self.dtimes = dtimes class IntegerList: def __init__(self, ints): self.ints = ints class DateTimeIntegerTuple: def __init__(self, dtime_int): self.dtime_int = dtime_int class TestFieldSerialization: @pytest.fixture def user(self): return User("Foo", email="foo@bar.com", age=42) @pytest.mark.parametrize( ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] ) def test_number(self, value, expected, user): field = fields.Number() user.age = value assert field.serialize("age", user) == expected def test_number_as_string(self, user): user.age = 42 field = fields.Number(as_string=True) assert field.serialize("age", user) == str(float(user.age)) def test_number_as_string_passed_none(self, user): user.age = None field = fields.Number(as_string=True, allow_none=True) assert field.serialize("age", user) is None def test_function_field_passed_func(self, user): field = fields.Function(lambda obj: obj.name.upper()) assert "FOO" == field.serialize("key", user) def test_function_field_passed_serialize_only_is_dump_only(self, user): field = fields.Function(serialize=lambda obj: obj.name.upper()) assert field.dump_only is True def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): field = fields.Function( serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() ) assert field.dump_only is False def test_function_field_passed_serialize(self, user): field = fields.Function(serialize=lambda obj: obj.name.upper()) assert "FOO" == field.serialize("key", user) # https://github.com/marshmallow-code/marshmallow/issues/395 def test_function_field_does_not_swallow_attribute_error(self, user): def raise_error(obj): raise AttributeError() field = fields.Function(serialize=raise_error) with pytest.raises(AttributeError): field.serialize("key", user) def test_serialize_with_load_only_param(self): class AliasingUserSerializer(Schema): name = fields.String() years = fields.Integer(load_only=True) size = fields.Integer(dump_only=True, load_only=True) nicknames = fields.List(fields.Str(), load_only=True) data = { "name": "Mick", "years": "42", "size": "12", "nicknames": ["Your Majesty", "Brenda"], } result = AliasingUserSerializer().dump(data) assert result["name"] == "Mick" assert "years" not in result assert "size" not in result assert "nicknames" not in result def test_function_field_load_only(self): field = fields.Function(deserialize=lambda obj: None) assert field.load_only def test_function_field_passed_serialize_with_context(self, user, monkeypatch): class Parent(Schema): pass field = fields.Function( serialize=lambda obj, context: obj.name.upper() + context["key"] ) field.parent = Parent(context={"key": "BAR"}) assert "FOOBAR" == field.serialize("key", user) def test_function_field_passed_uncallable_object(self): with pytest.raises(TypeError): fields.Function("uncallable") def test_integer_field(self, user): field = fields.Integer() assert field.serialize("age", user) == 42 def test_integer_as_string_field(self, user): field = fields.Integer(as_string=True) assert field.serialize("age", user) == "42" def test_integer_field_default(self, user): user.age = None field = fields.Integer(dump_default=0) assert field.serialize("age", user) is None # missing assert field.serialize("age", {}) == 0 def test_integer_field_default_set_to_none(self, user): user.age = None field = fields.Integer(dump_default=None) assert field.serialize("age", user) is None def test_uuid_field(self, user): user.uuid1 = uuid.UUID("12345678123456781234567812345678") user.uuid2 = None field = fields.UUID() assert isinstance(field.serialize("uuid1", user), str) assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" assert field.serialize("uuid2", user) is None def test_ip_address_field(self, user): ipv4_string = "192.168.0.1" ipv6_string = "ffff::ffff" ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded user.ipv4 = ipaddress.ip_address(ipv4_string) user.ipv6 = ipaddress.ip_address(ipv6_string) user.empty_ip = None field_compressed = fields.IP() assert isinstance(field_compressed.serialize("ipv4", user), str) assert field_compressed.serialize("ipv4", user) == ipv4_string assert isinstance(field_compressed.serialize("ipv6", user), str) assert field_compressed.serialize("ipv6", user) == ipv6_string assert field_compressed.serialize("empty_ip", user) is None field_exploded = fields.IP(exploded=True) assert isinstance(field_exploded.serialize("ipv6", user), str) assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string def test_ipv4_address_field(self, user): ipv4_string = "192.168.0.1" user.ipv4 = ipaddress.ip_address(ipv4_string) user.empty_ip = None field = fields.IPv4() assert isinstance(field.serialize("ipv4", user), str) assert field.serialize("ipv4", user) == ipv4_string assert field.serialize("empty_ip", user) is None def test_ipv6_address_field(self, user): ipv6_string = "ffff::ffff" ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded user.ipv6 = ipaddress.ip_address(ipv6_string) user.empty_ip = None field_compressed = fields.IPv6() assert isinstance(field_compressed.serialize("ipv6", user), str) assert field_compressed.serialize("ipv6", user) == ipv6_string assert field_compressed.serialize("empty_ip", user) is None field_exploded = fields.IPv6(exploded=True) assert isinstance(field_exploded.serialize("ipv6", user), str) assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string def test_ip_interface_field(self, user): ipv4interface_string = "192.168.0.1/24" ipv6interface_string = "ffff::ffff/128" ipv6interface_exploded_string = ipaddress.ip_interface( "ffff::ffff/128" ).exploded user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) user.empty_ipinterface = None field_compressed = fields.IPInterface() assert isinstance(field_compressed.serialize("ipv4interface", user), str) assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string assert isinstance(field_compressed.serialize("ipv6interface", user), str) assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string assert field_compressed.serialize("empty_ipinterface", user) is None field_exploded = fields.IPInterface(exploded=True) assert isinstance(field_exploded.serialize("ipv6interface", user), str) assert ( field_exploded.serialize("ipv6interface", user) == ipv6interface_exploded_string ) def test_ipv4_interface_field(self, user): ipv4interface_string = "192.168.0.1/24" user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) user.empty_ipinterface = None field = fields.IPv4Interface() assert isinstance(field.serialize("ipv4interface", user), str) assert field.serialize("ipv4interface", user) == ipv4interface_string assert field.serialize("empty_ipinterface", user) is None def test_ipv6_interface_field(self, user): ipv6interface_string = "ffff::ffff/128" ipv6interface_exploded_string = ipaddress.ip_interface( "ffff::ffff/128" ).exploded user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) user.empty_ipinterface = None field_compressed = fields.IPv6Interface() assert isinstance(field_compressed.serialize("ipv6interface", user), str) assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string assert field_compressed.serialize("empty_ipinterface", user) is None field_exploded = fields.IPv6Interface(exploded=True) assert isinstance(field_exploded.serialize("ipv6interface", user), str) assert ( field_exploded.serialize("ipv6interface", user) == ipv6interface_exploded_string ) def test_enum_field_by_symbol_serialization(self, user): user.sex = GenderEnum.male field = fields.Enum(GenderEnum) assert field.serialize("sex", user) == "male" def test_enum_field_by_value_true_serialization(self, user): user.hair_color = HairColorEnum.black field = fields.Enum(HairColorEnum, by_value=True) assert field.serialize("hair_color", user) == "black hair" user.sex = GenderEnum.male field = fields.Enum(GenderEnum, by_value=True) assert field.serialize("sex", user) == 1 user.some_date = DateEnum.date_1 def test_enum_field_by_value_field_serialization(self, user): user.hair_color = HairColorEnum.black field = fields.Enum(HairColorEnum, by_value=fields.String) assert field.serialize("hair_color", user) == "black hair" user.sex = GenderEnum.male field = fields.Enum(GenderEnum, by_value=fields.Integer) assert field.serialize("sex", user) == 1 user.some_date = DateEnum.date_1 field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) assert field.serialize("some_date", user) == "29/02/2004" def test_decimal_field(self, user): user.m1 = 12 user.m2 = "12.355" user.m3 = decimal.Decimal(1) user.m4 = None field = fields.Decimal() assert isinstance(field.serialize("m1", user), decimal.Decimal) assert field.serialize("m1", user) == decimal.Decimal(12) assert isinstance(field.serialize("m2", user), decimal.Decimal) assert field.serialize("m2", user) == decimal.Decimal("12.355") assert isinstance(field.serialize("m3", user), decimal.Decimal) assert field.serialize("m3", user) == decimal.Decimal(1) assert field.serialize("m4", user) is None field = fields.Decimal(1) assert isinstance(field.serialize("m1", user), decimal.Decimal) assert field.serialize("m1", user) == decimal.Decimal(12) assert isinstance(field.serialize("m2", user), decimal.Decimal) assert field.serialize("m2", user) == decimal.Decimal("12.4") assert isinstance(field.serialize("m3", user), decimal.Decimal) assert field.serialize("m3", user) == decimal.Decimal(1) assert field.serialize("m4", user) is None field = fields.Decimal(1, decimal.ROUND_DOWN) assert isinstance(field.serialize("m1", user), decimal.Decimal) assert field.serialize("m1", user) == decimal.Decimal(12) assert isinstance(field.serialize("m2", user), decimal.Decimal) assert field.serialize("m2", user) == decimal.Decimal("12.3") assert isinstance(field.serialize("m3", user), decimal.Decimal) assert field.serialize("m3", user) == decimal.Decimal(1) assert field.serialize("m4", user) is None def test_decimal_field_string(self, user): user.m1 = 12 user.m2 = "12.355" user.m3 = decimal.Decimal(1) user.m4 = None field = fields.Decimal(as_string=True) assert isinstance(field.serialize("m1", user), str) assert field.serialize("m1", user) == "12" assert isinstance(field.serialize("m2", user), str) assert field.serialize("m2", user) == "12.355" assert isinstance(field.serialize("m3", user), str) assert field.serialize("m3", user) == "1" assert field.serialize("m4", user) is None field = fields.Decimal(1, as_string=True) assert isinstance(field.serialize("m1", user), str) assert field.serialize("m1", user) == "12.0" assert isinstance(field.serialize("m2", user), str) assert field.serialize("m2", user) == "12.4" assert isinstance(field.serialize("m3", user), str) assert field.serialize("m3", user) == "1.0" assert field.serialize("m4", user) is None field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) assert isinstance(field.serialize("m1", user), str) assert field.serialize("m1", user) == "12.0" assert isinstance(field.serialize("m2", user), str) assert field.serialize("m2", user) == "12.3" assert isinstance(field.serialize("m3", user), str) assert field.serialize("m3", user) == "1.0" assert field.serialize("m4", user) is None def test_decimal_field_special_values(self, user): user.m1 = "-NaN" user.m2 = "NaN" user.m3 = "-sNaN" user.m4 = "sNaN" user.m5 = "-Infinity" user.m6 = "Infinity" user.m7 = "-0" field = fields.Decimal(places=2, allow_nan=True) m1s = field.serialize("m1", user) assert isinstance(m1s, decimal.Decimal) assert m1s.is_qnan() and not m1s.is_signed() m2s = field.serialize("m2", user) assert isinstance(m2s, decimal.Decimal) assert m2s.is_qnan() and not m2s.is_signed() m3s = field.serialize("m3", user) assert isinstance(m3s, decimal.Decimal) assert m3s.is_qnan() and not m3s.is_signed() m4s = field.serialize("m4", user) assert isinstance(m4s, decimal.Decimal) assert m4s.is_qnan() and not m4s.is_signed() m5s = field.serialize("m5", user) assert isinstance(m5s, decimal.Decimal) assert m5s.is_infinite() and m5s.is_signed() m6s = field.serialize("m6", user) assert isinstance(m6s, decimal.Decimal) assert m6s.is_infinite() and not m6s.is_signed() m7s = field.serialize("m7", user) assert isinstance(m7s, decimal.Decimal) assert m7s.is_zero() and m7s.is_signed() field = fields.Decimal(as_string=True, allow_nan=True) m2s = field.serialize("m2", user) assert isinstance(m2s, str) assert m2s == user.m2 m5s = field.serialize("m5", user) assert isinstance(m5s, str) assert m5s == user.m5 m6s = field.serialize("m6", user) assert isinstance(m6s, str) assert m6s == user.m6 def test_decimal_field_special_values_not_permitted(self, user): user.m7 = "-0" field = fields.Decimal(places=2) m7s = field.serialize("m7", user) assert isinstance(m7s, decimal.Decimal) assert m7s.is_zero() and m7s.is_signed() def test_decimal_field_fixed_point_representation(self, user): """ Test we get fixed-point string representation for a Decimal number that would normally output in engineering notation. """ user.m1 = "0.00000000100000000" field = fields.Decimal() s = field.serialize("m1", user) assert isinstance(s, decimal.Decimal) assert s == decimal.Decimal("1.00000000E-9") field = fields.Decimal(as_string=True) s = field.serialize("m1", user) assert isinstance(s, str) assert s == user.m1 field = fields.Decimal(as_string=True, places=2) s = field.serialize("m1", user) assert isinstance(s, str) assert s == "0.00" def test_boolean_field_serialization(self, user): field = fields.Boolean() user.truthy = "non-falsy-ish" user.falsy = "false" user.none = None assert field.serialize("truthy", user) is True assert field.serialize("falsy", user) is False assert field.serialize("none", user) is None def test_email_field_serialize_none(self, user): user.email = None field = fields.Email() assert field.serialize("email", user) is None def test_dict_field_serialize_none(self, user): user.various_data = None field = fields.Dict() assert field.serialize("various_data", user) is None def test_dict_field_serialize(self, user): user.various_data = {"foo": "bar"} field = fields.Dict() dump = field.serialize("various_data", user) assert dump == {"foo": "bar"} # Check dump is a distinct object dump["foo"] = "baz" assert user.various_data["foo"] == "bar" def test_dict_field_serialize_ordereddict(self, user): user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) field = fields.Dict() assert field.serialize("various_data", user) == OrderedDict( [("foo", "bar"), ("bar", "baz")] ) def test_structured_dict_value_serialize(self, user): user.various_data = {"foo": decimal.Decimal("1")} field = fields.Dict(values=fields.Decimal) assert field.serialize("various_data", user) == {"foo": 1} def test_structured_dict_key_serialize(self, user): user.various_data = {1: "bar"} field = fields.Dict(keys=fields.Str) assert field.serialize("various_data", user) == {"1": "bar"} def test_structured_dict_key_value_serialize(self, user): user.various_data = {1: decimal.Decimal("1")} field = fields.Dict(keys=fields.Str, values=fields.Decimal) assert field.serialize("various_data", user) == {"1": 1} def test_url_field_serialize_none(self, user): user.homepage = None field = fields.Url() assert field.serialize("homepage", user) is None def test_method_field_with_method_missing(self): class BadSerializer(Schema): bad_field = fields.Method("invalid") with pytest.raises(AttributeError): BadSerializer() def test_method_field_passed_serialize_only_is_dump_only(self, user): field = fields.Method(serialize="method") assert field.dump_only is True assert field.load_only is False def test_method_field_passed_deserialize_only_is_load_only(self): field = fields.Method(deserialize="somemethod") assert field.load_only is True assert field.dump_only is False def test_method_field_with_uncallable_attribute(self): class BadSerializer(Schema): foo = "not callable" bad_field = fields.Method("foo") with pytest.raises(TypeError): BadSerializer() # https://github.com/marshmallow-code/marshmallow/issues/395 def test_method_field_does_not_swallow_attribute_error(self): class MySchema(Schema): mfield = fields.Method("raise_error") def raise_error(self, obj): raise AttributeError() with pytest.raises(AttributeError): MySchema().dump({}) def test_method_with_no_serialize_is_missing(self): m = fields.Method() m.parent = Schema() assert m.serialize("", "", "") is missing_ def test_serialize_with_data_key_param(self): class DumpToSchema(Schema): name = fields.String(data_key="NamE") years = fields.Integer(data_key="YearS") data = {"name": "Richard", "years": 11} result = DumpToSchema().dump(data) assert result == {"NamE": "Richard", "YearS": 11} def test_serialize_with_data_key_as_empty_string(self): class MySchema(Schema): name = fields.Field(data_key="") schema = MySchema() assert schema.dump({"name": "Grace"}) == {"": "Grace"} def test_serialize_with_attribute_and_data_key_uses_data_key(self): class ConfusedDumpToAndAttributeSerializer(Schema): name = fields.String(data_key="FullName") username = fields.String(attribute="uname", data_key="UserName") years = fields.Integer(attribute="le_wild_age", data_key="Years") data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} result = ConfusedDumpToAndAttributeSerializer().dump(data) assert result == { "FullName": "Mick", "UserName": "mick_the_awesome", "Years": 999, } @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) @pytest.mark.parametrize( ("value", "expected"), [ (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), ( dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), "Sun, 10 Nov 2013 01:23:45 +0000", ), ( central.localize(dt.datetime(2013, 11, 10, 1, 23, 45), is_dst=False), "Sun, 10 Nov 2013 01:23:45 -0600", ), ], ) def test_datetime_field_rfc822(self, fmt, value, expected): field = fields.DateTime(format=fmt) assert field.serialize("d", {"d": value}) == expected @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) @pytest.mark.parametrize( ("value", "expected"), [ (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), ( dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), "2013-11-10T01:23:45.123456+00:00", ), ( dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), "2013-11-10T01:23:45+00:00", ), ( central.localize(dt.datetime(2013, 11, 10, 1, 23, 45), is_dst=False), "2013-11-10T01:23:45-06:00", ), ], ) def test_datetime_field_iso8601(self, fmt, value, expected): if fmt is None: # Test default is ISO field = fields.DateTime() else: field = fields.DateTime(format=fmt) assert field.serialize("d", {"d": value}) == expected def test_datetime_field_format(self, user): format = "%Y-%m-%d" field = fields.DateTime(format=format) assert field.serialize("created", user) == user.created.strftime(format) def test_string_field(self): field = fields.String() user = User(name=b"foo") assert field.serialize("name", user) == "foo" field = fields.String(allow_none=True) user.name = None assert field.serialize("name", user) is None def test_string_field_default_to_empty_string(self, user): field = fields.String(dump_default="") assert field.serialize("notfound", {}) == "" def test_time_field(self, user): field = fields.Time() expected = user.time_registered.isoformat()[:15] assert field.serialize("time_registered", user) == expected user.time_registered = None assert field.serialize("time_registered", user) is None @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) @pytest.mark.parametrize( ("value", "expected"), [ (dt.time(1, 23, 45), "01:23:45"), (dt.time(1, 23, 45, 123000), "01:23:45.123000"), (dt.time(1, 23, 45, 123456), "01:23:45.123456"), ], ) def test_time_field_iso8601(self, fmt, value, expected): if fmt is None: # Test default is ISO field = fields.Time() else: field = fields.Time(format=fmt) assert field.serialize("d", {"d": value}) == expected def test_time_field_format(self, user): fmt = "%H:%M:%S" field = fields.Time(format=fmt) assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) def test_date_field(self, user): field = fields.Date() assert field.serialize("birthdate", user) == user.birthdate.isoformat() user.birthdate = None assert field.serialize("birthdate", user) is None def test_timedelta_field(self, user): user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) user.d6 = dt.timedelta( days=1, seconds=1, microseconds=1, milliseconds=1, minutes=1, hours=1, weeks=1, ) field = fields.TimeDelta(fields.TimeDelta.DAYS) assert field.serialize("d1", user) == 1 field = fields.TimeDelta(fields.TimeDelta.SECONDS) assert field.serialize("d1", user) == 86401 field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) assert field.serialize("d1", user) == 86401000001 field = fields.TimeDelta(fields.TimeDelta.HOURS) assert field.serialize("d1", user) == 24 field = fields.TimeDelta(fields.TimeDelta.DAYS) assert field.serialize("d2", user) == 1 field = fields.TimeDelta(fields.TimeDelta.SECONDS) assert field.serialize("d2", user) == 86401 field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) assert field.serialize("d2", user) == 86401000001 field = fields.TimeDelta(fields.TimeDelta.DAYS) assert field.serialize("d3", user) == 1 field = fields.TimeDelta(fields.TimeDelta.SECONDS) assert field.serialize("d3", user) == 86401 field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) assert field.serialize("d3", user) == 86401000001 field = fields.TimeDelta(fields.TimeDelta.DAYS) assert field.serialize("d4", user) == 0 field = fields.TimeDelta(fields.TimeDelta.SECONDS) assert field.serialize("d4", user) == 0 field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) assert field.serialize("d4", user) == 0 field = fields.TimeDelta(fields.TimeDelta.DAYS) assert field.serialize("d5", user) == -1 field = fields.TimeDelta(fields.TimeDelta.SECONDS) assert field.serialize("d5", user) == -86400 field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) assert field.serialize("d5", user) == -86400000000 field = fields.TimeDelta(fields.TimeDelta.WEEKS) assert field.serialize("d6", user) == 1 field = fields.TimeDelta(fields.TimeDelta.DAYS) assert field.serialize("d6", user) == 7 + 1 field = fields.TimeDelta(fields.TimeDelta.HOURS) assert field.serialize("d6", user) == 7 * 24 + 24 + 1 field = fields.TimeDelta(fields.TimeDelta.MINUTES) assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 d6_seconds = ( 7 * 24 * 60 * 60 + 24 * 60 * 60 # 1 week + 60 * 60 # 1 day + 60 # 1 hour + 1 # 1 minute ) field = fields.TimeDelta(fields.TimeDelta.SECONDS) assert field.serialize("d6", user) == d6_seconds field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) assert field.serialize("d6", user) == d6_seconds * 1000 + 1 field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 user.d7 = None assert field.serialize("d7", user) is None # https://github.com/marshmallow-code/marshmallow/issues/1856 user.d8 = dt.timedelta(milliseconds=345) field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) assert field.serialize("d8", user) == 345 user.d9 = dt.timedelta(milliseconds=1999) field = fields.TimeDelta(fields.TimeDelta.SECONDS) assert field.serialize("d9", user) == 1 user.d10 = dt.timedelta( weeks=1, days=6, hours=2, minutes=5, seconds=51, milliseconds=10, microseconds=742, ) field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) unit_value = dt.timedelta(microseconds=1).total_seconds() assert math.isclose( field.serialize("d10", user), user.d10.total_seconds() / unit_value ) field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) unit_value = dt.timedelta(milliseconds=1).total_seconds() assert math.isclose( field.serialize("d10", user), user.d10.total_seconds() / unit_value ) field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) unit_value = dt.timedelta(minutes=1).total_seconds() assert math.isclose( field.serialize("d10", user), user.d10.total_seconds() / unit_value ) field = fields.TimeDelta(fields.TimeDelta.HOURS, float) unit_value = dt.timedelta(hours=1).total_seconds() assert math.isclose( field.serialize("d10", user), user.d10.total_seconds() / unit_value ) field = fields.TimeDelta(fields.TimeDelta.DAYS, float) unit_value = dt.timedelta(days=1).total_seconds() assert math.isclose( field.serialize("d10", user), user.d10.total_seconds() / unit_value ) field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) unit_value = dt.timedelta(weeks=1).total_seconds() assert math.isclose( field.serialize("d10", user), user.d10.total_seconds() / unit_value ) with pytest.raises(ValueError): fields.TimeDelta(fields.TimeDelta.SECONDS, str) def test_datetime_list_field(self): obj = DateTimeList([dt.datetime.utcnow(), dt.datetime.now()]) field = fields.List(fields.DateTime) result = field.serialize("dtimes", obj) assert all(type(each) == str for each in result) def test_list_field_serialize_none_returns_none(self): obj = DateTimeList(None) field = fields.List(fields.DateTime) assert field.serialize("dtimes", obj) is None def test_list_field_work_with_generator_single_value(self): def custom_generator(): yield dt.datetime.utcnow() obj = DateTimeList(custom_generator()) field = fields.List(fields.DateTime) result = field.serialize("dtimes", obj) assert len(result) == 1 def test_list_field_work_with_generators_multiple_values(self): def custom_generator(): yield from [dt.datetime.utcnow(), dt.datetime.now()] obj = DateTimeList(custom_generator()) field = fields.List(fields.DateTime) result = field.serialize("dtimes", obj) assert len(result) == 2 def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 self, ): def custom_generator(): yield yield obj = DateTimeList(custom_generator()) field = fields.List(fields.DateTime, allow_none=True) result = field.serialize("dtimes", obj) assert len(result) == 2 assert result[0] is None assert result[1] is None def test_list_field_work_with_set(self): custom_set = {1, 2, 3} obj = IntegerList(custom_set) field = fields.List(fields.Int) result = field.serialize("ints", obj) assert len(result) == 3 assert 1 in result assert 2 in result assert 3 in result def test_list_field_work_with_custom_class_with_iterator_protocol(self): class IteratorSupportingClass: def __init__(self, iterable): self.iterable = iterable def __iter__(self): return iter(self.iterable) ints = IteratorSupportingClass([1, 2, 3]) obj = IntegerList(ints) field = fields.List(fields.Int) result = field.serialize("ints", obj) assert len(result) == 3 assert result[0] == 1 assert result[1] == 2 assert result[2] == 3 def test_bad_list_field(self): class ASchema(Schema): id = fields.Int() with pytest.raises(ValueError): fields.List("string") expected_msg = ( "The list elements must be a subclass or instance of " "marshmallow.base.FieldABC" ) with pytest.raises(ValueError, match=expected_msg): fields.List(ASchema) def test_datetime_integer_tuple_field(self): obj = DateTimeIntegerTuple((dt.datetime.utcnow(), 42)) field = fields.Tuple([fields.DateTime, fields.Integer]) result = field.serialize("dtime_int", obj) assert type(result[0]) == str assert type(result[1]) == int def test_tuple_field_serialize_none_returns_none(self): obj = DateTimeIntegerTuple(None) field = fields.Tuple([fields.DateTime, fields.Integer]) assert field.serialize("dtime_int", obj) is None def test_bad_tuple_field(self): class ASchema(Schema): id = fields.Int() with pytest.raises(ValueError): fields.Tuple(["string"]) with pytest.raises(ValueError): fields.Tuple(fields.String) expected_msg = ( 'Elements of "tuple_fields" must be subclasses or ' "instances of marshmallow.base.FieldABC." ) with pytest.raises(ValueError, match=expected_msg): fields.Tuple([ASchema]) def test_serialize_does_not_apply_validators(self, user): field = fields.Field(validate=lambda x: False) # No validation error raised assert field.serialize("age", user) == user.age def test_constant_field_serialization(self, user): field = fields.Constant("something") assert field.serialize("whatever", user) == "something" def test_constant_is_always_included_in_serialized_data(self): class MySchema(Schema): foo = fields.Constant(42) sch = MySchema() assert sch.dump({"bar": 24})["foo"] == 42 assert sch.dump({"foo": 24})["foo"] == 42 def test_constant_field_serialize_when_omitted(self): class MiniUserSchema(Schema): name = fields.Constant("bill") s = MiniUserSchema() assert s.dump({})["name"] == "bill" @pytest.mark.parametrize("FieldClass", ALL_FIELDS) def test_all_fields_serialize_none_to_none(self, FieldClass): field = FieldClass(allow_none=True) res = field.serialize("foo", {"foo": None}) assert res is None class TestSchemaSerialization: def test_serialize_with_missing_param_value(self): class AliasingUserSerializer(Schema): name = fields.String() birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) data = {"name": "Mick"} result = AliasingUserSerializer().dump(data) assert result["name"] == "Mick" assert result["birthdate"] == "2017-09-29T00:00:00" def test_serialize_with_missing_param_callable(self): class AliasingUserSerializer(Schema): name = fields.String() birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) data = {"name": "Mick"} result = AliasingUserSerializer().dump(data) assert result["name"] == "Mick" assert result["birthdate"] == "2017-09-29T00:00:00" def test_serializing_named_tuple(): Point = namedtuple("Point", ["x", "y"]) field = fields.Field() p = Point(x=4, y=2) assert field.serialize("x", p) == 4 def test_serializing_named_tuple_with_meta(): Point = namedtuple("Point", ["x", "y"]) p = Point(x=4, y=2) class PointSerializer(Schema): class Meta: fields = ("x", "y") serialized = PointSerializer().dump(p) assert serialized["x"] == 4 assert serialized["y"] == 2 def test_serializing_slice(): values = [{"value": value} for value in range(5)] slice = itertools.islice(values, None) class ValueSchema(Schema): value = fields.Int() serialized = ValueSchema(many=True).dump(slice) assert serialized == values # https://github.com/marshmallow-code/marshmallow/issues/1163 def test_nested_field_many_serializing_generator(): class MySchema(Schema): name = fields.Str() class OtherSchema(Schema): objects = fields.Nested(MySchema, many=True) def gen(): yield {"name": "foo"} yield {"name": "bar"} obj = {"objects": gen()} data = OtherSchema().dump(obj) assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}]
{ "content_hash": "14fafe865a1f21eda2f9eb8eb1a41322", "timestamp": "", "source": "github", "line_count": 1014, "max_line_length": 128, "avg_line_length": 37.37376725838264, "alnum_prop": 0.6115259783096287, "repo_name": "mwstobo/marshmallow", "id": "51671ddf6e4e405209c5ad9ca61db3c32917075e", "size": "37897", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "tests/test_serialization.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "523097" } ], "symlink_target": "" }
class DjangoShardingException(Exception): pass class ShardedModelInitializationException(DjangoShardingException): pass class InvalidMigrationException(DjangoShardingException): pass class NonExistentDatabaseException(DjangoShardingException): pass
{ "content_hash": "cade2e0c620bddb08265deaa81d70a2d", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 67, "avg_line_length": 19.357142857142858, "alnum_prop": 0.8302583025830258, "repo_name": "jwadden/django-sharding", "id": "2121883028e8271bef8b096974b5d1e145c7c9a0", "size": "271", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "django_sharding_library/exceptions.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "87882" }, { "name": "Shell", "bytes": "209" } ], "symlink_target": "" }
"""These are job parameters that are common to every type of Jenkins job. Example: .. literalinclude:: /../../tests/yamlparser/fixtures/general-example-001.yaml :Job Parameters: * **project-type**: Defaults to "freestyle", but "maven" as well as "multijob" or "flow" can also be specified. * **defaults**: Specifies a set of :ref:`defaults` to use for this job, defaults to ''global''. If you have values that are common to all of your jobs, create a ``global`` :ref:`defaults` object to hold them, and no further configuration of individual jobs is necessary. If some jobs should not use the ``global`` defaults, use this field to specify a different set of defaults. * **description**: The description for the job. By default, the description "!-- Managed by Jenkins Job Builder" is applied. * **disabled**: Boolean value to set whether or not this job should be disabled in Jenkins. Defaults to ``false`` (job will be enabled). * **display-name**: Optional name shown for the project throughout the Jenkins web GUI in place of the actual job name. The jenkins_jobs tool cannot fully remove this trait once it is set, so use caution when setting it. Setting it to the same string as the job's name is an effective un-set workaround. Alternately, the field can be cleared manually using the Jenkins web interface. * **concurrent**: Boolean value to set whether or not Jenkins can run this job concurrently. Defaults to ``false``. * **workspace**: Path for a custom workspace. Defaults to Jenkins default configuration. * **quiet-period**: Number of seconds to wait between consecutive runs of this job. Defaults to ``0``. * **block-downstream**: Boolean value to set whether or not this job must block while downstream jobs are running. Downstream jobs are determined transitively. Defaults to ``false``. * **block-upstream**: Boolean value to set whether or not this job must block while upstream jobs are running. Upstream jobs are determined transitively. Defaults to ``false``. * **auth-token**: Specifies an authentication token that allows new builds to be triggered by accessing a special predefined URL. Only those who know the token will be able to trigger builds remotely. * **retry-count**: If a build fails to checkout from the repository, Jenkins will retry the specified number of times before giving up. * **node**: Restrict where this job can be run. If there is a group of machines that the job can be built on, you can specify that label as the node to tie on, which will cause Jenkins to build the job on any of the machines with that label. * **logrotate**: The Logrotate section allows you to automatically remove old build history. It adds the ``logrotate`` attribute to the :ref:`Job` definition. All logrotate attributes default to "-1" (keep forever). """ import xml.etree.ElementTree as XML import jenkins_jobs.modules.base class General(jenkins_jobs.modules.base.Base): sequence = 10 def gen_xml(self, parser, xml, data): jdk = data.get('jdk', None) if jdk: XML.SubElement(xml, 'jdk').text = jdk XML.SubElement(xml, 'actions') desc_text = data.get('description', None) if desc_text is not None: description = XML.SubElement(xml, 'description') description.text = desc_text XML.SubElement(xml, 'keepDependencies').text = 'false' disabled = data.get('disabled', None) if disabled is not None: if disabled: XML.SubElement(xml, 'disabled').text = 'true' else: XML.SubElement(xml, 'disabled').text = 'false' if 'display-name' in data: XML.SubElement(xml, 'displayName').text = data['display-name'] if data.get('block-downstream'): XML.SubElement(xml, 'blockBuildWhenDownstreamBuilding').text = 'true' else: XML.SubElement(xml, 'blockBuildWhenDownstreamBuilding').text = 'false' if data.get('block-upstream'): XML.SubElement(xml, 'blockBuildWhenUpstreamBuilding').text = 'true' else: XML.SubElement(xml, 'blockBuildWhenUpstreamBuilding').text = 'false' if 'auth-token' in data: XML.SubElement(xml, 'authToken').text = data['auth-token'] if data.get('concurrent'): XML.SubElement(xml, 'concurrentBuild').text = 'true' else: XML.SubElement(xml, 'concurrentBuild').text = 'false' if 'workspace' in data: XML.SubElement(xml, 'customWorkspace').text = \ str(data['workspace']) if 'quiet-period' in data: XML.SubElement(xml, 'quietPeriod').text = str(data['quiet-period']) node = data.get('node', None) if node: XML.SubElement(xml, 'assignedNode').text = node XML.SubElement(xml, 'canRoam').text = 'false' else: XML.SubElement(xml, 'canRoam').text = 'true' if 'retry-count' in data: XML.SubElement(xml, 'scmCheckoutRetryCount').text = \ str(data['retry-count']) if 'logrotate' in data: lr_xml = XML.SubElement(xml, 'logRotator') logrotate = data['logrotate'] lr_days = XML.SubElement(lr_xml, 'daysToKeep') lr_days.text = str(logrotate.get('daysToKeep', -1)) lr_num = XML.SubElement(lr_xml, 'numToKeep') lr_num.text = str(logrotate.get('numToKeep', -1)) lr_adays = XML.SubElement(lr_xml, 'artifactDaysToKeep') lr_adays.text = str(logrotate.get('artifactDaysToKeep', -1)) lr_anum = XML.SubElement(lr_xml, 'artifactNumToKeep') lr_anum.text = str(logrotate.get('artifactNumToKeep', -1))
{ "content_hash": "74f6e73dba8ed5f7e2445da34bec1f3f", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 79, "avg_line_length": 41.53378378378378, "alnum_prop": 0.6198145436798438, "repo_name": "therootcause/jenkins-job-builder", "id": "e3c694e8f5f8fa4c45121722648d79aa20c10a9b", "size": "6750", "binary": false, "copies": "1", "ref": "refs/heads/upstream/master", "path": "jenkins_jobs/modules/general.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "5620" }, { "name": "Python", "bytes": "534787" }, { "name": "Shell", "bytes": "869" } ], "symlink_target": "" }
import re import struct try: exec("from . import png", globals(), locals()) except (SyntaxError, ValueError): # On Python < 2.5 relative import cause syntax error # Also works when running outside of package import png def pdskey(s, k): """ Lookup key `k` in string `s`. Returns value (as a string), or raises exception if not found. """ assert re.match(r' *\^?[:\w]+$', k) safere = png.strtobytes('^' + re.escape(k) + r' *= *(\w+)') m = re.search(safere, s, re.MULTILINE) if not m: raise png.FormatError("Can't find %s." % k) return m.group(1) def img(inp): """ Open the PDS IMG file `inp` and return (*pixels*, *info*). *pixels* is an iterator over the rows, *info* is the information dictionary. """ consumed = 1024 s = inp.read(consumed) record_type = pdskey(s, 'RECORD_TYPE') if record_type != png.strtobytes('FIXED_LENGTH'): raise png.FormatError( "Can only deal with FIXED_LENGTH record type (found %s)" % record_type) record_bytes = int(pdskey(s, 'RECORD_BYTES')) # file_records = int(pdskey(s, 'FILE_RECORDS')) label_records = int(pdskey(s, 'LABEL_RECORDS')) remaining = label_records * record_bytes - consumed s += inp.read(remaining) consumed += remaining image_pointer = int(pdskey(s, '^IMAGE')) # "^IMAGE" locates a record. Records are numbered starting from 1. image_index = image_pointer - 1 image_offset = image_index * record_bytes gap = image_offset - consumed assert gap >= 0 if gap: inp.read(gap) # This assumes there is only one OBJECT in the file, and it is the # IMAGE. height = int(pdskey(s, ' LINES')) width = int(pdskey(s, ' LINE_SAMPLES')) sample_type = pdskey(s, ' SAMPLE_TYPE') sample_bits = int(pdskey(s, ' SAMPLE_BITS')) # TODO: For Messenger MDIS, SAMPLE_BITS is reported as 16, but only values # from 0 ot 4095 are used. bitdepth = sample_bits if bitdepth == 16 and\ sample_type == png.strtobytes('MSB_UNSIGNED_INTEGER'): fmt = '>H' elif bitdepth == 8: fmt = '@B' else: raise png.FormatError('Unknown sample type: %s.' % sample_type) sample_bytes = (1, 2)[bitdepth > 8] row_bytes = sample_bytes * width fmt = fmt[:1] + str(width) + fmt[1:] def rowiter(): for y in range(height): yield struct.unpack(fmt, inp.read(row_bytes)) info = dict(greyscale=True, alpha=False, bitdepth=bitdepth, size=(width, height), gamma=1.0) return rowiter(), info def main(argv=None): import sys if sys.platform == "win32": import msvcrt, os try: msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) except: pass if argv is None: argv = sys.argv argv = argv[1:] arg = argv if len(arg) >= 1: f = open(arg[0], 'rb') should_close = True else: f = sys.stdin should_close = False pixels, info = img(f) w = png.Writer(**info) w.write(sys.stdout, pixels) if should_close: f.close() if __name__ == '__main__': main()
{ "content_hash": "e79723fbfb88e3e44f8c276b0f270b22", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 78, "avg_line_length": 29.574074074074073, "alnum_prop": 0.5848465873512837, "repo_name": "Scondo/purepng", "id": "bd460a6502393d8e8446d055d4f51125dd636c64", "size": "3252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "png/pdsimgtopng.py", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1842" }, { "name": "PowerShell", "bytes": "6109" }, { "name": "Python", "bytes": "294339" }, { "name": "Shell", "bytes": "61" } ], "symlink_target": "" }
""" Quicksort is a divide and conquer algorithm which relies on a partition operation: to partition an array an element called a pivot is selected. All elements smaller than the pivot are moved before it and all greater elements are moved after it. This can be done efficiently in linear time and in-place. The lesser and greater sublists are then recursively sorted. This yields average time complexity of O(n log n), with low overhead, and thus this is a popular algorithm. Efficient implementations of quicksort (with in-place partitioning) are typically unstable sorts and somewhat complex, but are among the fastest sorting algorithms in practice. Together with its modest O(log n) space usage, quicksort is one of the most popular sorting algorithms and is available in many standard programming libraries. The important caveat about quicksort is that its worst-case performance is O(n^2); while this is rare, in naive implementations (choosing the first or last element as pivot) this occurs for sorted data, which is a common case. The most complex issue in quicksort is thus choosing a good pivot element, as consistently poor choices of pivots can result in drastically slower O(n^2) performance, but good choice of pivots yields O(n log n) performance, which is asymptotically optimal. For example, if at each step the median is chosen as the pivot then the algorithm works in O(n log n). Finding the median, such as by the median of medians selection algorithm is however an O(n) operation on unsorted lists and therefore exacts significant overhead with sorting. In practice choosing a random pivot almost certainly yields O(n log n) performance. Best Case: O(n log n) Average Case: O(n log n) Worst Case: O(n^2) Space Complexity: O(log n) """ class QuickSort(object): number = 0 numbers = [] def sort(values): if not values or len(values) == 0: return QuickSort.numbers = values QuickSort.number = len(values) QuickSort.__quicksort(0, QuickSort.number - 1) @staticmethod def __exchange(i, j): QuickSort.numbers[i], QuickSort.numbers[ j] = QuickSort.numbers[j], QuickSort.numbers[i] @staticmethod def __quicksort(low, high): i = int(low) j = int(high) pivot = QuickSort.numbers[low + int((high - low) / 2)] while i <= j: while QuickSort.numbers[i] < pivot: i += 1 while QuickSort.numbers[j] > pivot: j -= 1 if i <= j: QuickSort.__exchange(i, j) i += 1 j -= 1 if low < j: QuickSort.__quicksort(low, j) if i < high: QuickSort.__quicksort(i, high)
{ "content_hash": "07c2f66ceaba290c972db1dc1179b66c", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 87, "avg_line_length": 35.33783783783784, "alnum_prop": 0.7204588910133843, "repo_name": "rahulnadella/Sort_Algorithms", "id": "aac9d53b1ef029fea07b604e1b63adb353d98f4c", "size": "2615", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "quicksort/quicksort.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "24888" } ], "symlink_target": "" }
import sys import warnings from django.core.mail import mail_admins from django.core.management.base import BaseCommand class Command(BaseCommand): help = '[DEPRECATED] Send args as a one-shot email to the admins.' def add_arguments(self, parser): parser.add_argument( 'message', nargs='*', ) parser.add_argument('--subject', help='Subject', default='Mail from the console'), parser.add_argument('--stdin', action='store_true', default=False, help='Read message body from stdin'), parser.add_argument('--html', action='store_true', default=False, help='HTML payload'), parser.add_argument('--environment', default='', help='The environment we are mailing about'), def handle(self, message, **options): warnings.warn( "mail_admins is deprecated. Use 'send_email --to-admins' instead.", DeprecationWarning, ) if options['stdin']: message = sys.stdin.read() else: message = ' '.join(message) html = None if options['html']: html = message mail_admins(options['subject'], message, html_message=html)
{ "content_hash": "346992776772a9a569ddcd95728348ed", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 112, "avg_line_length": 34.371428571428574, "alnum_prop": 0.6118038237738986, "repo_name": "dimagi/commcare-hq", "id": "7a07db1fa5526598af64d4216e1a2b0b72791e4b", "size": "1203", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "corehq/apps/hqadmin/management/commands/mail_admins.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "82928" }, { "name": "Dockerfile", "bytes": "2341" }, { "name": "HTML", "bytes": "2589268" }, { "name": "JavaScript", "bytes": "5889543" }, { "name": "Jinja", "bytes": "3693" }, { "name": "Less", "bytes": "176180" }, { "name": "Makefile", "bytes": "1622" }, { "name": "PHP", "bytes": "2232" }, { "name": "PLpgSQL", "bytes": "66704" }, { "name": "Python", "bytes": "21779773" }, { "name": "Roff", "bytes": "150" }, { "name": "Shell", "bytes": "67473" } ], "symlink_target": "" }
from .commands.general import (Author, Uptime) from .commands.sc2cm import (Top, Player, ClanWar) from .commands import help as help_command from .commands.teamliquid import TeamLiquidFeed # Configuration for AlphaGG # Auth token BOT_TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' COMMAND_PREFIX = '.' # Registered commands/plugins COMMANDS = [ help_command.Help, Top, Player, ClanWar, TeamLiquidFeed, Author, Uptime ]
{ "content_hash": "8ec5b391c127e6c2e504d3bd82715666", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 73, "avg_line_length": 21.545454545454547, "alnum_prop": 0.7489451476793249, "repo_name": "pundurs/alpha-gg", "id": "1fbbabdd556042bb743817a69521630ef15d22c1", "size": "493", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "alphaGG/config.example.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "20789" } ], "symlink_target": "" }
from __future__ import absolute_import, division, print_function import re import pytest import responses import dosagelib.cmd import httpmocks def cmd(*options): """'Fake' run dosage with given options.""" assert dosagelib.cmd.main(("--allow-multiple",) + options) == 0 @pytest.mark.usefixtures("nosleep") class TestModules(object): """Test that specific comic modules work correctly.""" @responses.activate def test_turnoff(self, tmpdir): httpmocks.page('https://turnoff.us/', 'turnoff-home') httpmocks.page('https://turnoff.us/geek/the-bad-design-punisher', 'turnoff-229') httpmocks.png(re.compile(r'https://turnoff\.us/image/en/.*\.png')) cmd('--numstrips', '2', '--basepath', str(tmpdir), 'turnoff')
{ "content_hash": "b674ce607b6d619a8e44a2ac60696a0b", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 74, "avg_line_length": 26.862068965517242, "alnum_prop": 0.6649550706033376, "repo_name": "peterjanes/dosage", "id": "4cadf8ed7a0a0f6cbf470c7bc6e3872f3a989a80", "size": "845", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_modules.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "33" }, { "name": "Python", "bytes": "502958" }, { "name": "Shell", "bytes": "1554" } ], "symlink_target": "" }
from __future__ import absolute_import from distutils import log from distutils.command.upload import upload as _upload from pkg_resources import iter_entry_points class BundleCommand(_upload): user_options = _upload.user_options + [ # - from 'register' ("strict", None, "Will stop if the meta-data are not fully compliant"), # - from 'sdist' ("formats=", None, "formats for source distribution (comma-separated list)"), ] boolean_options = _upload.boolean_options + ["strict"] _bundles = None def handle(self): for bundle in self.get_bundles(): self.handle_bundle(bundle) def handle_bundle(self, bundle): raise NotImplementedError("subclass responsibility") def run(self): if not self.username: raise KeyError( "Missing PyPI username: Do you have a valid .pypirc?") if not self.get_bundles(): return log.error("No bundle entry-points for distribution %r" % ( self.distribution.metadata.name, )) self.handle() def get_bundles(self): # can't use property because of ancient old-style classes used. if not self._bundles: self._bundles = self._get_bundles() return self._bundles def _get_bundles(self): for ep in iter_entry_points('bundle.bundles'): if ep.name == self.distribution.metadata.name: return ep.load() class register_bundles(BundleCommand): description = "Register bundles at PyPI" def handle_bundle(self, bundle): log.info("* Registering bundle %s (%s)" % (bundle.name, bundle.version)) bundle.register() class upload_bundles(BundleCommand): description = "Upload bundles to PyPI (if version not already released)" def handle_bundle(self, bundle): log.info("* Uploading bundle %s (%s)" % (bundle.name, bundle.version)) bundle.upload() class upload_bundles_fix(BundleCommand): description = "Uploads new version of all bundles to PyPI" def handle_bundle(self, bundle): log.info("* Uploading new bundle version for %s (%s)" % ( bundle.name, bundle.version)) bundle.upload_fix()
{ "content_hash": "d0ae40fe4a923c836a9a673ce1f40c64", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 77, "avg_line_length": 31.89189189189189, "alnum_prop": 0.5991525423728814, "repo_name": "ask/bundle", "id": "93c9ad5c96e2d897a0c11b472a5e51bbfd5ca95a", "size": "2360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bundle/setup.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Perl", "bytes": "1662" }, { "name": "Python", "bytes": "15685" } ], "symlink_target": "" }
from scipy.io.wavfile import read from scipy.fftpack import fft,ifft,dct from scipy.signal import get_window import numpy as np from pdb import set_trace from os.path import join,split from glob import glob from SignalProcessor import Signal # linear scale to mel scale def mel_scale(f): return 1127.0 * np.log(1 + f / 700.0) # mel scale to linear scale def linear_scale(m): return 700.0 * (np.exp(m / 1127.0) - 1) # Pre-emphasize the signal, strengthen its high frequency components def pre_emph(x): return x - 0.95 * np.hstack((x[len(x) - 1:len(x)],x[0:len(x) - 1])) # Frame signal def _frame(x,width=512): frames = [] hann_win = get_window('hann',width) step = width // 2 pad_size = step - len(x) % step + 1 num_frames = (len(x) - width + pad_size) // step + 1 zeros = np.zeros(pad_size) data = np.hstack((x,zeros)) zeros = np.zeros(step) data = np.hstack((zeros,data)) num_frames += 1 for i in range(num_frames): start = i * step frame = data[start:start + width] * hann_win frames.append(frame) return frames def triang_win(width,center=0.5): win = [] cpos = center * width for i in range(width + 1): if i <= cpos: win.append(1.0 / cpos * i) else: win.append(float(width - i) / (width - cpos)) return np.array(win)[0:width] def frame_mfcc(frame,rate): width = len(frame) spectrum = fft(frame)[0:width // 2 + 1] linear_upperbound = 44100.0 / 2 linear_lowerbound = 0.0 mel_upperbound = mel_scale(linear_upperbound) mel_lowerbound = mel_scale(linear_lowerbound) # Number of MFCC entries N = 13 mel_step = (mel_upperbound - mel_lowerbound) / N mel_center = list(map(lambda i:(i + 0.5) * mel_step,range(N))) linear_center = [linear_lowerbound] + list(map(linear_scale,mel_center)) + [linear_upperbound] banks = [] # frequency step of the FFT output freq_unit = float(rate) / (width + 2) for i in range(N): length = linear_center[i + 2] - linear_center[i] center = (linear_center[i + 1] - linear_center[i]) / length win_size = int(length / freq_unit) banks.append(triang_win(win_size,center)) energy = [] for i in range(N): start = int(linear_center[i] / freq_unit) energy.append(np.log(1e-25 + sum(list(map(lambda x:np.power(np.abs(x),2),spectrum[start:start + len(banks[i])] * banks[i]))))) # energy.append(sum(list(map(lambda) # x:np.power(np.abs(x),2),spectrum[start:start+len(banks[i])]*banks[i]))) energy = np.array(energy) # obtain mfcc mfcc = dct(energy) # replace first cepstral coefficient with log of frame energy # frame_energy = np.log(1e-25+sum(list(map(lambda) # x:np.power(np.abs(x),2),frame))) # frame_energy = sum(list(map(lambda x:np.power(np.abs(x),2),frame))) # set_trace() # mfcc[0] = frame_energy return mfcc def diff(coefs): dim = len(coefs[0]) cs = coefs[:] cs.append(np.zeros(dim)) deltas = [] for i in range(len(cs) - 1): deltas.append(cs[i + 1] - cs[i]) return deltas def mfcc(x,rate): x = pre_emph(x) frames = _frame(x) mfccs = [] for frame in frames: mfccs.append(frame_mfcc(frame,rate)) # Compute velocity vel = diff(mfccs) # Compute acceleration acc = diff(vel) for i in range(len(mfccs)): # mfcc + velocity + acceleration + time # mfccs[i] = np.hstack((mfccs[i],vel[i],acc[i],np.array([float(i)]))) mfccs[i] = np.hstack((mfccs[i],vel[i],acc[i])) return mfccs def load(filename): f = open(filename) mfccs = [] for line in f: mfccs.append(list(map(float,line.strip().split(',')))) return mfccs def cook(wavfilename,output_dir): print('Cooking ' + split(wavfilename)[1]) signal = Signal(wavfilename) feat = mfcc(signal.data,signal.rate) outname = output_dir + split(wavfilename)[1].replace('wav','txt') out = open(outname,'w') for i in range(len(feat)): out.write(str(list(feat[i])).strip('[]').replace(' ','') + '\n') out.close()
{ "content_hash": "105db048c07304646a2a32d8dc9b849b", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 134, "avg_line_length": 30.881481481481483, "alnum_prop": 0.6013432477812425, "repo_name": "RockmanZheng/Digital-Speech-Recognizer", "id": "eed4717d8af84864c88b6f6d5aed8b46dcb3eab0", "size": "4169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "0.3.8/src/MFCC.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "97704" }, { "name": "C++", "bytes": "3156" }, { "name": "Python", "bytes": "70971" } ], "symlink_target": "" }
__author__ = 'charlie' import numpy as np import os, sys, inspect import random from six.moves import cPickle as pickle from tensorflow.python.platform import gfile import glob utils_path = os.path.abspath( os.path.realpath(os.path.join(os.path.split(inspect.getfile(inspect.currentframe()))[0], ".."))) if utils_path not in sys.path: sys.path.insert(0, utils_path) import utils as utils DATA_URL = 'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip' random.seed(5) class Dataset_Reader(): def __init__(self, dict): self.train_images = dict['train'] self.test_images = dict['test'] self.validation_images = dict['validation'] """ This is used to train on local genereated data, slightly modify the original to fit our image format __author__ = 'kun ouyang' """ def read_local_data(data_dir, validation_percentage = 0.0, testing_percentage = 0.0): for x in os.walk(data_dir): file_list = x[2] training_images = [data_dir+x for x in file_list] random.shuffle(training_images) no_of_images = len(training_images) validation_offset = int(validation_percentage * no_of_images) validation_images = training_images[:validation_offset] test_offset = int(testing_percentage * no_of_images) testing_images = training_images[validation_offset:validation_offset + test_offset] training_images = training_images[validation_offset + test_offset:] result = { 'train': training_images, 'test': testing_images, 'validation': validation_images, } return result def read_dataset(data_dir): pickle_filename = "celebA.pickle" pickle_filepath = os.path.join(data_dir, pickle_filename) if not os.path.exists(pickle_filepath): # utils.maybe_download_and_extract(data_dir, DATA_URL, is_zipfile=True) celebA_folder = os.path.splitext(DATA_URL.split("/")[-1])[0] dir_path = os.path.join(data_dir, celebA_folder) if not os.path.exists(dir_path): print ("CelebA dataset needs to be downloaded and unzipped manually") print ("Download from: %s" % DATA_URL) raise ValueError("Dataset not found") result = create_image_lists(dir_path) print ("Training set: %d" % len(result['train'])) print ("Test set: %d" % len(result['test'])) print ("Validation set: %d" % len(result['validation'])) print ("Pickling ...") with open(pickle_filepath, 'wb') as f: pickle.dump(result, f, pickle.HIGHEST_PROTOCOL) else: print ("Found pickle file!") with open(pickle_filepath, 'rb') as f: result = pickle.load(f) celebA = CelebA_Dataset(result) del result return celebA def create_image_lists(image_dir, testing_percentage=0.0, validation_percentage=0.0): """ Code modified from tensorflow/tensorflow/examples/image_retraining """ if not gfile.Exists(image_dir): print("Image directory '" + image_dir + "' not found.") return None training_images = [] extensions = ['jpg', 'jpeg', 'JPG', 'JPEG'] sub_dirs = [x[0] for x in os.walk(image_dir)] file_list = [] for extension in extensions: file_glob = os.path.join(image_dir, '*.' + extension) file_list.extend(glob.glob(file_glob)) if not file_list: print('No files found') else: # print "No. of files found: %d" % len(file_list) training_images.extend([f for f in file_list]) random.shuffle(training_images) no_of_images = len(training_images) validation_offset = int(validation_percentage * no_of_images) validation_images = training_images[:validation_offset] test_offset = int(testing_percentage * no_of_images) testing_images = training_images[validation_offset:validation_offset + test_offset] training_images = training_images[validation_offset + test_offset:] result = { 'train': training_images, 'test': testing_images, 'validation': validation_images, } return result
{ "content_hash": "7bee7e1ebfbef4e7256e0182c536a996", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 106, "avg_line_length": 36.705357142857146, "alnum_prop": 0.6521527608854293, "repo_name": "kunrenzhilu/GAN", "id": "67c09292a3dbfc94b9a6914c75104a41144732fa", "size": "4111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Dataset_Reader/read_celebADataset.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "36236" }, { "name": "Shell", "bytes": "405" } ], "symlink_target": "" }
import MySQLdb import functools from .config import ( db, ) def memoize(obj): cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer class Consumer(object): def __init__(self, start, wattUsage): self.start = start self.wattUsage = wattUsage pass def toDict(self): return { 'start' : self.start, 'stop': 0, 'watt': self.wattUsage} class Measurements(object): def __init__(self, x): self.logbuffer = [] self.consumers = [] self.values = [] self.x = x self.wattmargin = 29 self.samples = 9 self.startDate = "2013-11-15 00:45:00" self.endDate = "2013-11-15 09:30:00" self.log("", "Measurements from " + self.startDate + " to " + self.endDate) self.log("", "Watt tolerancemargin " + str(self.wattmargin)) self.log("", "Watt averaging sample count " + str(self.samples)) # you must create a Cursor object. It will let # you execute all the query you need cur = db.cursor() # Use all the SQL you like cur.execute("SELECT UNIX_TIMESTAMP(time) as epochtime,data FROM measure_watt where time > '" + self.startDate + "' and time < '" + self.endDate + "'") # print all the first cell of all the rows for row in cur.fetchall() : self.values.append( { 'x': int(row[0]), 'y' : row[1], 'info' : {} } ) self.x = row[0] self.log("", "Total sample count " + str(len(self.values)) ) self.analyze() def log(self, time, message, level = 0): outmesg = str(time) + " | " + " " * level + str(message) print outmesg self.logbuffer.append(outmesg) def getConsumer(self, wattUsage): for cons in self.consumers: if cons.wattUsage >= wattUsage-self.wattmargin and cons.wattUsage <= wattUsage+self.wattmargin: return cons return None def addConsumer(self, start, wattUsage): cons = Consumer(start, wattUsage) self.consumers.append(cons) return cons def getOrCreateConsumer(self, start, wattUsage): cons = self.getConsumer(wattUsage) if cons is None: cons = self.addConsumer(start, wattUsage) self.log(start, "Adding Consumer using " + str(wattUsage) + " watts",2) return cons def subsetsum(self, items, maxweight): @memoize def f(v, i, S): if i >= len(v): return 1 if (S >= (-1*self.wattmargin) and S <= self.wattmargin) else 0 count = f(v, i + 1, S) count += f(v, i + 1, S - v[i].wattUsage) return count # <-- Return memoized value. tempWeight = maxweight subset = [] for i, item in enumerate(items): # Check if there is still a solution if we include items[i] #print " ## Checking item: " + str(item.wattUsage) if f(items, i + 1, tempWeight - item.wattUsage) > 0: subset.append(item) tempWeight -= item.wattUsage return subset def removeConsumer(self, wattUsage): self.consumers[:] = [x for x in self.consumers if not (x.wattUsage >= wattUsage-self.wattmargin and x.wattUsage <= wattUsage+self.wattmargin)] def removeConsumers(self, time, wattUsage): matchedConsumers = self.subsetsum(self.consumers, wattUsage) if len(matchedConsumers) == 0: self.log(time, "Trying to remove consumers using: " + str(wattUsage) + " but none found!!", 2) #directMatch = [x for x in self.consumers if (x.wattUsage >= wattUsage-self.wattmargin and x.wattUsage <= wattUsage+self.wattmargin)] for cons in matchedConsumers: self.consumers.remove(cons) self.log(time, "Removed consumer using " + str(cons.wattUsage) + " watts",2) def getConsumers(self): out = "" for cons in self.consumers: out += "Consumer Started: " + str(cons['start']) + ", Using: " + str(cons['watt']) + "\n" return out def analyze(self): consumers = [] runningAvgValue = 0 avgWatt = 0 avgDiff = 0 avgValues = -1 avgStartWatt = self.values[0]['y'] matchStartTime = 0 for point in self.values: #print "Checking: " + point['x'] + "\n" #diff = point['y'] - lastUsage runningAvgValue += point['y'] runningAvgValue /= 2 #point['y'] = runningAvgValue avgStartDiff = point['y'] - avgStartWatt if avgValues == -1 and abs(avgStartDiff) > self.wattmargin: avgValues = self.samples avgWatt = point['y'] avgDiff = avgStartDiff matchStartTime = point['x'] self.log(matchStartTime, "Possible consumer change with diff: " + str(avgDiff) + " watts. Starting averaging", 0) if avgValues > 0: avgValues -= 1 avgWatt += point['y'] avgWatt = avgWatt / 2 avgDiff += avgStartDiff avgDiff = avgDiff / 2 #else: # avgStartWatt = point['y'] if avgValues == 0: avgValues = -1 avgStartWatt = avgWatt self.log(matchStartTime, "Consumer avgdiff " + str(avgDiff), 1) if abs(avgDiff) > self.wattmargin: if avgDiff > 0: cons = self.getOrCreateConsumer(matchStartTime, avgDiff) else: self.removeConsumers(matchStartTime, abs(avgDiff)) point['info'] = [x.toDict() for x in self.consumers] pass def __json__(self, request): return {'wattdata': self.values, 'log': self.logbuffer}
{ "content_hash": "e6ef5730484735246e115fef76d78fc3", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 152, "avg_line_length": 29.197802197802197, "alnum_prop": 0.625705683101242, "repo_name": "alekslt/powerusageanalysis", "id": "7b30b10992d8395d62d20a126d11e73411781d7c", "size": "5314", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "measure/models.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6015" }, { "name": "Python", "bytes": "7571" }, { "name": "Shell", "bytes": "81" } ], "symlink_target": "" }
from bs4 import BeautifulSoup import urllib from scraper import * import re, json class Galaxy(Scraper): def get_planets(self, galaxy, system): """ Get planets in the given galaxy and system """ self.logger.info('Getting data from system %s:%s' % (galaxy, system)) url = self.url_provider.get_page_url('galaxyContent') data = urllib.urlencode({'galaxy': galaxy, 'system': system}) res = self.open_url(url, data).read() # The server call returns json data jsonData = json.loads(res) data = jsonData['galaxy'].encode('utf8') soup = BeautifulSoup(self.strip_text(data), "lxml") table = soup.find("table", {"id": "galaxytable"}) if table is None: self.logger.error("Invalid response from server, could not find #galaxytable") return [] table_rows = table.findAll("tr", {"class": "row"}) planets = [] for table_row in table_rows: # skip empty table rows if "empty_filter" in table_row.get("class"): continue planet_name = self.strip_text(table_row(attrs={'class': "planetname"})[0].text) planet_position = self.strip_text(table_row.find('td', {'class': "position"}).text) planet_coordinates = ":".join([galaxy, system, planet_position]) player_name_data = table_row(attrs={'class': "playername"})[0] player_name_heading = player_name_data.find('h1') if player_name_heading is None: continue player_name = player_name_heading.find('span').text.encode('utf8') # Set player state player_name_classes = player_name_data.get("class") if 'longinactive' in player_name_classes or 'inactive' in player_name_classes: player_state = PlayerState.Inactive elif 'vacationlonginactive' in player_name_classes or 'vacation' in player_name_classes: player_state = PlayerState.Vacation else: player_state = PlayerState.Active player_rank = self.get_rank(soup, player_name) planets.append(Planet(planet_name, planet_coordinates, player_name, player_state, player_rank)) return planets @staticmethod def strip_text(text): return text.replace("\\n", '').strip("u' [ ]").strip() @staticmethod def get_rank(soup, player_name): rank_nodes = soup.findAll("li", {"class": "rank"}) player_rank_node_match = [rank_node for rank_node in rank_nodes if player_name in rank_node.parent.parent.text] if len(player_rank_node_match) == 0: return 0 else: player_rank_node = player_rank_node_match[0] player_rank_string = player_rank_node.find("a").text.strip() s = re.findall('^\d*', player_rank_string) player_rank = int(s[0] if s[0] else "-1") return player_rank class Planet(object): def __init__(self, name, coordinates, player_name, player_state, player_rank): self.name = name self.coordinates = coordinates self.player_name = player_name self.player_state = player_state self.player_rank = player_rank def __str__(self): return unicode(self).encode('utf-8') def __unicode__(self): description = "Planet: %s, Coordinates: %s, Player %s (%s)(%d)" % (self.name, self.coordinates, self.player_name, self.player_state, self.player_rank) return description
{ "content_hash": "532ed3fce643bc87115a82bfe32e9de2", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 111, "avg_line_length": 37.95049504950495, "alnum_prop": 0.5554396034437777, "repo_name": "yosh778/OG-Bot", "id": "e7ea2c097185d8d2da655642947e994638c25901", "size": "3833", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ogbot/scraping/galaxy.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "4779" }, { "name": "PHP", "bytes": "1676" }, { "name": "Python", "bytes": "156684" } ], "symlink_target": "" }
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest from mock import ANY from ansible.module_utils.network.fortios.fortios import FortiOSHandler try: from ansible.modules.network.fortios import fortios_web_proxy_debug_url except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_web_proxy_debug_url.Connection') return connection_class_mock fos_instance = FortiOSHandler(connection_mock) def test_web_proxy_debug_url_creation(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'web_proxy_debug_url': { 'exact': 'enable', 'name': 'default_name_4', 'status': 'enable', 'url_pattern': 'test_value_6' }, 'vdom': 'root'} is_error, changed, response = fortios_web_proxy_debug_url.fortios_web_proxy(input_data, fos_instance) expected_data = { 'exact': 'enable', 'name': 'default_name_4', 'status': 'enable', 'url-pattern': 'test_value_6' } set_method_mock.assert_called_with('web-proxy', 'debug-url', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_web_proxy_debug_url_creation_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'web_proxy_debug_url': { 'exact': 'enable', 'name': 'default_name_4', 'status': 'enable', 'url_pattern': 'test_value_6' }, 'vdom': 'root'} is_error, changed, response = fortios_web_proxy_debug_url.fortios_web_proxy(input_data, fos_instance) expected_data = { 'exact': 'enable', 'name': 'default_name_4', 'status': 'enable', 'url-pattern': 'test_value_6' } set_method_mock.assert_called_with('web-proxy', 'debug-url', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_web_proxy_debug_url_removal(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') delete_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} delete_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.delete', return_value=delete_method_result) input_data = { 'username': 'admin', 'state': 'absent', 'web_proxy_debug_url': { 'exact': 'enable', 'name': 'default_name_4', 'status': 'enable', 'url_pattern': 'test_value_6' }, 'vdom': 'root'} is_error, changed, response = fortios_web_proxy_debug_url.fortios_web_proxy(input_data, fos_instance) delete_method_mock.assert_called_with('web-proxy', 'debug-url', mkey=ANY, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_web_proxy_debug_url_deletion_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') delete_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} delete_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.delete', return_value=delete_method_result) input_data = { 'username': 'admin', 'state': 'absent', 'web_proxy_debug_url': { 'exact': 'enable', 'name': 'default_name_4', 'status': 'enable', 'url_pattern': 'test_value_6' }, 'vdom': 'root'} is_error, changed, response = fortios_web_proxy_debug_url.fortios_web_proxy(input_data, fos_instance) delete_method_mock.assert_called_with('web-proxy', 'debug-url', mkey=ANY, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_web_proxy_debug_url_idempotent(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'web_proxy_debug_url': { 'exact': 'enable', 'name': 'default_name_4', 'status': 'enable', 'url_pattern': 'test_value_6' }, 'vdom': 'root'} is_error, changed, response = fortios_web_proxy_debug_url.fortios_web_proxy(input_data, fos_instance) expected_data = { 'exact': 'enable', 'name': 'default_name_4', 'status': 'enable', 'url-pattern': 'test_value_6' } set_method_mock.assert_called_with('web-proxy', 'debug-url', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 404 def test_web_proxy_debug_url_filter_foreign_attributes(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'web_proxy_debug_url': { 'random_attribute_not_valid': 'tag', 'exact': 'enable', 'name': 'default_name_4', 'status': 'enable', 'url_pattern': 'test_value_6' }, 'vdom': 'root'} is_error, changed, response = fortios_web_proxy_debug_url.fortios_web_proxy(input_data, fos_instance) expected_data = { 'exact': 'enable', 'name': 'default_name_4', 'status': 'enable', 'url-pattern': 'test_value_6' } set_method_mock.assert_called_with('web-proxy', 'debug-url', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200
{ "content_hash": "5e99ad24d2313567a32973bf250574f7", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 142, "avg_line_length": 36.201877934272304, "alnum_prop": 0.6285825444170665, "repo_name": "thaim/ansible", "id": "75247b23a9c3c7ad9f2886c6c4b163d125e3d82e", "size": "8407", "binary": false, "copies": "20", "ref": "refs/heads/fix-broken-link", "path": "test/units/modules/network/fortios/test_fortios_web_proxy_debug_url.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "7" }, { "name": "Shell", "bytes": "246" } ], "symlink_target": "" }
"""Unit tests for abc.py.""" import unittest import abc import _py_abc from inspect import isabstract def test_factory(abc_ABCMeta, abc_get_cache_token): class TestLegacyAPI(unittest.TestCase): def test_abstractproperty_basics(self): @abc.abstractproperty def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(hasattr(bar, "__isabstractmethod__")) class C(metaclass=abc_ABCMeta): @abc.abstractproperty def foo(self): return 3 self.assertRaises(TypeError, C) class D(C): @property def foo(self): return super().foo self.assertEqual(D().foo, 3) self.assertFalse(getattr(D.foo, "__isabstractmethod__", False)) def test_abstractclassmethod_basics(self): @abc.abstractclassmethod def foo(cls): pass self.assertTrue(foo.__isabstractmethod__) @classmethod def bar(cls): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc_ABCMeta): @abc.abstractclassmethod def foo(cls): return cls.__name__ self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D') self.assertEqual(D().foo(), 'D') def test_abstractstaticmethod_basics(self): @abc.abstractstaticmethod def foo(): pass self.assertTrue(foo.__isabstractmethod__) @staticmethod def bar(): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc_ABCMeta): @abc.abstractstaticmethod def foo(): return 3 self.assertRaises(TypeError, C) class D(C): @staticmethod def foo(): return 4 self.assertEqual(D.foo(), 4) self.assertEqual(D().foo(), 4) class TestABC(unittest.TestCase): def test_ABC_helper(self): # create an ABC using the helper class and perform basic checks class C(abc.ABC): @classmethod @abc.abstractmethod def foo(cls): return cls.__name__ self.assertEqual(type(C), abc.ABCMeta) self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D') def test_abstractmethod_basics(self): @abc.abstractmethod def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(hasattr(bar, "__isabstractmethod__")) def test_abstractproperty_basics(self): @property @abc.abstractmethod def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc_ABCMeta): @property @abc.abstractmethod def foo(self): return 3 self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertEqual(D().foo, 3) def test_abstractclassmethod_basics(self): @classmethod @abc.abstractmethod def foo(cls): pass self.assertTrue(foo.__isabstractmethod__) @classmethod def bar(cls): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc_ABCMeta): @classmethod @abc.abstractmethod def foo(cls): return cls.__name__ self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D') self.assertEqual(D().foo(), 'D') def test_abstractstaticmethod_basics(self): @staticmethod @abc.abstractmethod def foo(): pass self.assertTrue(foo.__isabstractmethod__) @staticmethod def bar(): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc_ABCMeta): @staticmethod @abc.abstractmethod def foo(): return 3 self.assertRaises(TypeError, C) class D(C): @staticmethod def foo(): return 4 self.assertEqual(D.foo(), 4) self.assertEqual(D().foo(), 4) def test_object_new_with_one_abstractmethod(self): class C(metaclass=abc_ABCMeta): @abc.abstractmethod def method_one(self): pass msg = r"class C with abstract method method_one" self.assertRaisesRegex(TypeError, msg, C) def test_object_new_with_many_abstractmethods(self): class C(metaclass=abc_ABCMeta): @abc.abstractmethod def method_one(self): pass @abc.abstractmethod def method_two(self): pass msg = r"class C with abstract methods method_one, method_two" self.assertRaisesRegex(TypeError, msg, C) def test_abstractmethod_integration(self): for abstractthing in [abc.abstractmethod, abc.abstractproperty, abc.abstractclassmethod, abc.abstractstaticmethod]: class C(metaclass=abc_ABCMeta): @abstractthing def foo(self): pass # abstract def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, C) # because foo is abstract self.assertTrue(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, D) # because foo is still abstract self.assertTrue(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too self.assertFalse(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, {"bar"}) self.assertRaises(TypeError, F) # because bar is abstract now self.assertTrue(isabstract(F)) def test_descriptors_with_abstractmethod(self): class C(metaclass=abc_ABCMeta): @property @abc.abstractmethod def foo(self): return 3 @foo.setter @abc.abstractmethod def foo(self, val): pass self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertRaises(TypeError, D) class E(D): @D.foo.setter def foo(self, val): pass self.assertEqual(E().foo, 3) # check that the property's __isabstractmethod__ descriptor does the # right thing when presented with a value that fails truth testing: class NotBool(object): def __bool__(self): raise ValueError() __len__ = __bool__ with self.assertRaises(ValueError): class F(C): def bar(self): pass bar.__isabstractmethod__ = NotBool() foo = property(bar) def test_customdescriptors_with_abstractmethod(self): class Descriptor: def __init__(self, fget, fset=None): self._fget = fget self._fset = fset def getter(self, callable): return Descriptor(callable, self._fget) def setter(self, callable): return Descriptor(self._fget, callable) @property def __isabstractmethod__(self): return (getattr(self._fget, '__isabstractmethod__', False) or getattr(self._fset, '__isabstractmethod__', False)) class C(metaclass=abc_ABCMeta): @Descriptor @abc.abstractmethod def foo(self): return 3 @foo.setter @abc.abstractmethod def foo(self, val): pass self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertRaises(TypeError, D) class E(D): @D.foo.setter def foo(self, val): pass self.assertFalse(E.foo.__isabstractmethod__) def test_metaclass_abc(self): # Metaclasses can be ABCs, too. class A(metaclass=abc_ABCMeta): @abc.abstractmethod def x(self): pass self.assertEqual(A.__abstractmethods__, {"x"}) class meta(type, A): def x(self): return 1 class C(metaclass=meta): pass def test_registration_basics(self): class A(metaclass=abc_ABCMeta): pass class B(object): pass b = B() self.assertFalse(issubclass(B, A)) self.assertFalse(issubclass(B, (A,))) self.assertNotIsInstance(b, A) self.assertNotIsInstance(b, (A,)) B1 = A.register(B) self.assertTrue(issubclass(B, A)) self.assertTrue(issubclass(B, (A,))) self.assertIsInstance(b, A) self.assertIsInstance(b, (A,)) self.assertIs(B1, B) class C(B): pass c = C() self.assertTrue(issubclass(C, A)) self.assertTrue(issubclass(C, (A,))) self.assertIsInstance(c, A) self.assertIsInstance(c, (A,)) def test_register_as_class_deco(self): class A(metaclass=abc_ABCMeta): pass @A.register class B(object): pass b = B() self.assertTrue(issubclass(B, A)) self.assertTrue(issubclass(B, (A,))) self.assertIsInstance(b, A) self.assertIsInstance(b, (A,)) @A.register class C(B): pass c = C() self.assertTrue(issubclass(C, A)) self.assertTrue(issubclass(C, (A,))) self.assertIsInstance(c, A) self.assertIsInstance(c, (A,)) self.assertIs(C, A.register(C)) def test_isinstance_invalidation(self): class A(metaclass=abc_ABCMeta): pass class B: pass b = B() self.assertFalse(isinstance(b, A)) self.assertFalse(isinstance(b, (A,))) token_old = abc_get_cache_token() A.register(B) token_new = abc_get_cache_token() self.assertGreater(token_new, token_old) self.assertTrue(isinstance(b, A)) self.assertTrue(isinstance(b, (A,))) def test_registration_builtins(self): class A(metaclass=abc_ABCMeta): pass A.register(int) self.assertIsInstance(42, A) self.assertIsInstance(42, (A,)) self.assertTrue(issubclass(int, A)) self.assertTrue(issubclass(int, (A,))) class B(A): pass B.register(str) class C(str): pass self.assertIsInstance("", A) self.assertIsInstance("", (A,)) self.assertTrue(issubclass(str, A)) self.assertTrue(issubclass(str, (A,))) self.assertTrue(issubclass(C, A)) self.assertTrue(issubclass(C, (A,))) def test_registration_edge_cases(self): class A(metaclass=abc_ABCMeta): pass A.register(A) # should pass silently class A1(A): pass self.assertRaises(RuntimeError, A1.register, A) # cycles not allowed class B(object): pass A1.register(B) # ok A1.register(B) # should pass silently class C(A): pass A.register(C) # should pass silently self.assertRaises(RuntimeError, C.register, A) # cycles not allowed C.register(B) # ok def test_register_non_class(self): class A(metaclass=abc_ABCMeta): pass self.assertRaisesRegex(TypeError, "Can only register classes", A.register, 4) def test_registration_transitiveness(self): class A(metaclass=abc_ABCMeta): pass self.assertTrue(issubclass(A, A)) self.assertTrue(issubclass(A, (A,))) class B(metaclass=abc_ABCMeta): pass self.assertFalse(issubclass(A, B)) self.assertFalse(issubclass(A, (B,))) self.assertFalse(issubclass(B, A)) self.assertFalse(issubclass(B, (A,))) class C(metaclass=abc_ABCMeta): pass A.register(B) class B1(B): pass self.assertTrue(issubclass(B1, A)) self.assertTrue(issubclass(B1, (A,))) class C1(C): pass B1.register(C1) self.assertFalse(issubclass(C, B)) self.assertFalse(issubclass(C, (B,))) self.assertFalse(issubclass(C, B1)) self.assertFalse(issubclass(C, (B1,))) self.assertTrue(issubclass(C1, A)) self.assertTrue(issubclass(C1, (A,))) self.assertTrue(issubclass(C1, B)) self.assertTrue(issubclass(C1, (B,))) self.assertTrue(issubclass(C1, B1)) self.assertTrue(issubclass(C1, (B1,))) C1.register(int) class MyInt(int): pass self.assertTrue(issubclass(MyInt, A)) self.assertTrue(issubclass(MyInt, (A,))) self.assertIsInstance(42, A) self.assertIsInstance(42, (A,)) def test_issubclass_bad_arguments(self): class A(metaclass=abc_ABCMeta): pass with self.assertRaises(TypeError): issubclass({}, A) # unhashable with self.assertRaises(TypeError): issubclass(42, A) # No __mro__ # Python version supports any iterable as __mro__. # But it's implementation detail and don't emulate it in C version. class C: __mro__ = 42 # __mro__ is not tuple with self.assertRaises(TypeError): issubclass(C(), A) # bpo-34441: Check that issubclass() doesn't crash on bogus # classes. bogus_subclasses = [ None, lambda x: [], lambda: 42, lambda: [42], ] for i, func in enumerate(bogus_subclasses): class S(metaclass=abc_ABCMeta): __subclasses__ = func with self.subTest(i=i): with self.assertRaises(TypeError): issubclass(int, S) # Also check that issubclass() propagates exceptions raised by # __subclasses__. exc_msg = "exception from __subclasses__" def raise_exc(): raise Exception(exc_msg) class S(metaclass=abc_ABCMeta): __subclasses__ = raise_exc with self.assertRaisesRegex(Exception, exc_msg): issubclass(int, S) def test_subclasshook(self): class A(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, C): if cls is A: return 'foo' in C.__dict__ return NotImplemented self.assertFalse(issubclass(A, A)) self.assertFalse(issubclass(A, (A,))) class B: foo = 42 self.assertTrue(issubclass(B, A)) self.assertTrue(issubclass(B, (A,))) class C: spam = 42 self.assertFalse(issubclass(C, A)) self.assertFalse(issubclass(C, (A,))) def test_all_new_methods_are_called(self): class A(metaclass=abc_ABCMeta): pass class B(object): counter = 0 def __new__(cls): B.counter += 1 return super().__new__(cls) class C(A, B): pass self.assertEqual(B.counter, 0) C() self.assertEqual(B.counter, 1) def test_ABC_has___slots__(self): self.assertTrue(hasattr(abc.ABC, '__slots__')) def test_tricky_new_works(self): def with_metaclass(meta, *bases): class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) class A: ... class B: ... class C(with_metaclass(abc_ABCMeta, A, B)): pass self.assertEqual(C.__class__, abc_ABCMeta) def test_update_del(self): class A(metaclass=abc_ABCMeta): @abc.abstractmethod def foo(self): pass del A.foo self.assertEqual(A.__abstractmethods__, {'foo'}) self.assertFalse(hasattr(A, 'foo')) abc.update_abstractmethods(A) self.assertEqual(A.__abstractmethods__, set()) A() def test_update_new_abstractmethods(self): class A(metaclass=abc_ABCMeta): @abc.abstractmethod def bar(self): pass @abc.abstractmethod def updated_foo(self): pass A.foo = updated_foo abc.update_abstractmethods(A) self.assertEqual(A.__abstractmethods__, {'foo', 'bar'}) msg = "class A with abstract methods bar, foo" self.assertRaisesRegex(TypeError, msg, A) def test_update_implementation(self): class A(metaclass=abc_ABCMeta): @abc.abstractmethod def foo(self): pass class B(A): pass msg = "class B with abstract method foo" self.assertRaisesRegex(TypeError, msg, B) self.assertEqual(B.__abstractmethods__, {'foo'}) B.foo = lambda self: None abc.update_abstractmethods(B) B() self.assertEqual(B.__abstractmethods__, set()) def test_update_as_decorator(self): class A(metaclass=abc_ABCMeta): @abc.abstractmethod def foo(self): pass def class_decorator(cls): cls.foo = lambda self: None return cls @abc.update_abstractmethods @class_decorator class B(A): pass B() self.assertEqual(B.__abstractmethods__, set()) def test_update_non_abc(self): class A: pass @abc.abstractmethod def updated_foo(self): pass A.foo = updated_foo abc.update_abstractmethods(A) A() self.assertFalse(hasattr(A, '__abstractmethods__')) def test_update_del_implementation(self): class A(metaclass=abc_ABCMeta): @abc.abstractmethod def foo(self): pass class B(A): def foo(self): pass B() del B.foo abc.update_abstractmethods(B) msg = "class B with abstract method foo" self.assertRaisesRegex(TypeError, msg, B) def test_update_layered_implementation(self): class A(metaclass=abc_ABCMeta): @abc.abstractmethod def foo(self): pass class B(A): pass class C(B): def foo(self): pass C() del C.foo abc.update_abstractmethods(C) msg = "class C with abstract method foo" self.assertRaisesRegex(TypeError, msg, C) def test_update_multi_inheritance(self): class A(metaclass=abc_ABCMeta): @abc.abstractmethod def foo(self): pass class B(metaclass=abc_ABCMeta): def foo(self): pass class C(B, A): @abc.abstractmethod def foo(self): pass self.assertEqual(C.__abstractmethods__, {'foo'}) del C.foo abc.update_abstractmethods(C) self.assertEqual(C.__abstractmethods__, set()) C() class TestABCWithInitSubclass(unittest.TestCase): def test_works_with_init_subclass(self): class abc_ABC(metaclass=abc_ABCMeta): __slots__ = () saved_kwargs = {} class ReceivesClassKwargs: def __init_subclass__(cls, **kwargs): super().__init_subclass__() saved_kwargs.update(kwargs) class Receiver(ReceivesClassKwargs, abc_ABC, x=1, y=2, z=3): pass self.assertEqual(saved_kwargs, dict(x=1, y=2, z=3)) def test_positional_only_and_kwonlyargs_with_init_subclass(self): saved_kwargs = {} class A: def __init_subclass__(cls, **kwargs): super().__init_subclass__() saved_kwargs.update(kwargs) class B(A, metaclass=abc_ABCMeta, name="test"): pass self.assertEqual(saved_kwargs, dict(name="test")) return TestLegacyAPI, TestABC, TestABCWithInitSubclass TestLegacyAPI_Py, TestABC_Py, TestABCWithInitSubclass_Py = test_factory(abc.ABCMeta, abc.get_cache_token) TestLegacyAPI_C, TestABC_C, TestABCWithInitSubclass_C = test_factory(_py_abc.ABCMeta, _py_abc.get_cache_token) if __name__ == "__main__": unittest.main()
{ "content_hash": "af423a72d6bdfb95bed488179ab2c94a", "timestamp": "", "source": "github", "line_count": 686, "max_line_length": 93, "avg_line_length": 34.8600583090379, "alnum_prop": 0.49284937693401354, "repo_name": "brython-dev/brython", "id": "1e7a0351db489d13c9577b42229b6aa239bcfbf6", "size": "24170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/src/Lib/test/test_abc.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "24308" }, { "name": "HTML", "bytes": "5144999" }, { "name": "JavaScript", "bytes": "4143100" }, { "name": "PLSQL", "bytes": "22886" }, { "name": "Python", "bytes": "22236375" }, { "name": "Roff", "bytes": "21126" }, { "name": "VBScript", "bytes": "481" } ], "symlink_target": "" }
import bz2, json, importScheduledMonuments, os, web import poidatabase import xml.parsers.expat if __name__=="__main__": curdir = os.path.dirname(__file__) db = web.database(dbn='sqlite', db=os.path.join(curdir, 'data.db')) t = db.transaction() inFi = bz2.BZ2File("LB.kml.bz2", "r") dbInt = poidatabase.DbInt(db) datasetId = dbInt.AddDataset("Sch Mon", 1, {"public": 1}) ep = importScheduledMonuments.ParseKml() ep.dbInt = dbInt ep.datasetId = datasetId ep.ParseFile(inFi) t.commit() del dbInt ep.dbInt = None del ep del db
{ "content_hash": "d406f6bfb7e1d402a5639c4abd13bb5b", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 69, "avg_line_length": 21.03846153846154, "alnum_prop": 0.6837294332723949, "repo_name": "TimSC/POIware-server", "id": "573bd6733cc26068d95df908cb1eb5390fb52567", "size": "688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "importListedBuildings.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "23710" } ], "symlink_target": "" }
"""Test for the sqlite3 data connector.""" from unittest import TestCase from tests.dc.test import AbstractDCTest from tests.dc.query_manager import AbstractQMTest from dc.yaml.connector import YAMLConnector class DCTest(AbstractDCTest, AbstractQMTest, TestCase): name = "yaml" connector = YAMLConnector
{ "content_hash": "518c3e214496f6a473b34b2dce926820", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 55, "avg_line_length": 26.333333333333332, "alnum_prop": 0.7879746835443038, "repo_name": "v-legoff/pa-poc3", "id": "6f8e875b7b545f487e9fd0aa0d26cd3040af6452", "size": "1856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/tests/dc/yaml/test.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "12354" }, { "name": "Python", "bytes": "643635" }, { "name": "Shell", "bytes": "6471" } ], "symlink_target": "" }
people = 30 cars = 40 buses = 15 if cars > people: print "We should take the cars." elif cars <people: print "We should not take the cars." else: print "We can't bloody decide!" if buses > cars: print "That's too many buses!" elif buses < cars: print "Maybe we could take the buses." else: print "We still can't even decide! ZOMG" if people > buses: print "Alright, let's just take the buses." else: print "Fine, let's stay home then. Jeez"
{ "content_hash": "00eff846a18dd5930622a787d4d73e87", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 45, "avg_line_length": 20.90909090909091, "alnum_prop": 0.6782608695652174, "repo_name": "nchristiny/python", "id": "c3c4c4753f8afbe8f0c861b34204a29470ffa515", "size": "460", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ex30.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "34402" } ], "symlink_target": "" }
"""Sample file configuration for celery_app worker This file is intended only for a sample. Please copy it as celeryconfig.py so it can be read """ import os __copyright__ = "Copyright 2018, The InaSAFE Project" __license__ = "GPL version 3" __email__ = "info@inasafe.org" __revision__ = '$Format:%H$' broker_url = os.environ.get('INASAFE_HEADLESS_BROKER_URL') result_backend = broker_url task_routes = { 'inasafe.headless.tasks.get_keywords': { 'queue': 'inasafe-headless' }, 'inasafe.headless.tasks.run_analysis': { 'queue': 'inasafe-headless-analysis' }, 'inasafe.headless.tasks.run_multi_exposure_analysis': { 'queue': 'inasafe-headless-analysis' }, 'inasafe.headless.tasks.generate_report': { 'queue': 'inasafe-headless-reporting' }, 'inasafe.headless.tasks.get_generated_report': { 'queue': 'inasafe-headless' }, 'inasafe.headless.tasks.generate_contour': { 'queue': 'inasafe-headless-contour' }, 'inasafe.headless.tasks.check_broker_connection': { 'queue': 'inasafe-headless' }, } # RMN: This is really important. # Long bug description ahead! Beware. # This set InaSAFE Headless concurrency to 1. Which means this celery worker # will only uses 1 thread. This is necessary because we are using Xvfb to # handle graphical report generation (used by processing framework). # Somehow, qgis processing framework is not thread safe. It forgot to call # XInitThreads() which is necessary for multithreading. Read long description # here about XInitThreads(): http://www.remlab.net/op/xlib.shtml # In other words, you should always set this to 1. If not, it will default to # number of CPUs/core which can be multithreaded and will invoke debugging # **NIGHTMARE** to your celery worker. Read about this particular settings # here: # http://docs.celeryproject.org/en/latest/configuration.html#celeryd-concurrency worker_concurrency = 1 worker_prefetch_multiplier = 1 # Celery config task_serializer = 'pickle' accept_content = {'pickle'} result_serializer = 'pickle' # Late ACK settings task_acks_late = True task_reject_on_worker_lost = True
{ "content_hash": "b81fa6ef6490cc5247fbda4f853629c3", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 80, "avg_line_length": 31.434782608695652, "alnum_prop": 0.7076994006454588, "repo_name": "AIFDR/inasafe-django", "id": "2e6e312309eb0a4864742924ae3078fc3427d479", "size": "2184", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "django_project/realtime/tasks/headless/celeryconfig.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "196369" }, { "name": "HTML", "bytes": "93481" }, { "name": "JavaScript", "bytes": "346781" }, { "name": "Makefile", "bytes": "9201" }, { "name": "Python", "bytes": "285851" }, { "name": "Shell", "bytes": "2169" } ], "symlink_target": "" }
import sys from PyQt5.QtCore import Qt, QVariant from PyQt5.QtGui import QStandardItemModel, QStandardItem from PyQt5.QtWidgets import QApplication, QTreeView if __name__ == '__main__': app = QApplication(sys.argv) tree_view = QTreeView() ### model = QStandardItemModel(None) row1 = [QStandardItem("a"), QStandardItem("b")] row2 = [QStandardItem("c"), QStandardItem("d")] row3 = [QStandardItem("e"), QStandardItem("f")] row4 = [QStandardItem("g"), QStandardItem("h")] row5 = [QStandardItem("i"), QStandardItem("j")] root_item = model.invisibleRootItem() root_item.appendRow(row1) row1[0].appendRow(row2) row1[0].appendRow(row3) #row1[1].appendRow(row4) # ignored root_item.appendRow(row5) ### tree_view.setModel(model) tree_view.expandAll() # expand all (this is not the case by default) tree_view.show() # The mainloop of the application. The event handling starts from this point. # The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead. exit_code = app.exec_() # The sys.exit() method ensures a clean exit. # The environment will be informed, how the application ended. sys.exit(exit_code)
{ "content_hash": "393a39facc51b62b1dc43f79d660f8b6", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 123, "avg_line_length": 31.048780487804876, "alnum_prop": 0.6684996072270227, "repo_name": "jeremiedecock/snippets", "id": "1fe0429f7b33f2b9167e026f9d8849571aabb5be", "size": "1388", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/pyqt/pyqt5/widget_QTreeView_with_multiple_columns_append_example.py", "mode": "33261", "license": "mit", "language": [ { "name": "AMPL", "bytes": "4294" }, { "name": "Batchfile", "bytes": "6779" }, { "name": "C", "bytes": "102107" }, { "name": "C++", "bytes": "320943" }, { "name": "CMake", "bytes": "11424" }, { "name": "CSS", "bytes": "21121" }, { "name": "Cython", "bytes": "21" }, { "name": "Dockerfile", "bytes": "1818" }, { "name": "Fortran", "bytes": "633" }, { "name": "Gnuplot", "bytes": "39999" }, { "name": "Go", "bytes": "3166" }, { "name": "Groovy", "bytes": "3009" }, { "name": "HTML", "bytes": "138995" }, { "name": "IDL", "bytes": "43" }, { "name": "Java", "bytes": "120221" }, { "name": "JavaScript", "bytes": "32342" }, { "name": "Jinja", "bytes": "206" }, { "name": "Jupyter Notebook", "bytes": "95991" }, { "name": "Lua", "bytes": "200" }, { "name": "M4", "bytes": "111" }, { "name": "MATLAB", "bytes": "31972" }, { "name": "Makefile", "bytes": "81307" }, { "name": "OpenSCAD", "bytes": "14995" }, { "name": "PHP", "bytes": "94" }, { "name": "Perl", "bytes": "46" }, { "name": "Processing", "bytes": "208" }, { "name": "Prolog", "bytes": "454" }, { "name": "Python", "bytes": "1685966" }, { "name": "R", "bytes": "76" }, { "name": "Raku", "bytes": "43" }, { "name": "Ruby", "bytes": "42" }, { "name": "Scheme", "bytes": "649" }, { "name": "Shell", "bytes": "52865" }, { "name": "Smalltalk", "bytes": "55" }, { "name": "TeX", "bytes": "1189" }, { "name": "Vue", "bytes": "49445" }, { "name": "XSLT", "bytes": "1816" } ], "symlink_target": "" }
"""UniFi Controller abstraction.""" import asyncio import async_timeout from aiohttp import CookieJar from homeassistant import config_entries from homeassistant.const import CONF_HOST from homeassistant.helpers import aiohttp_client from .const import CONF_CONTROLLER, CONF_POE_CONTROL, LOGGER from .errors import AuthenticationRequired, CannotConnect class UniFiController: """Manages a single UniFi Controller.""" def __init__(self, hass, config_entry): """Initialize the system.""" self.hass = hass self.config_entry = config_entry self.available = True self.api = None self.progress = None self._cancel_retry_setup = None @property def host(self): """Return the host of this controller.""" return self.config_entry.data[CONF_CONTROLLER][CONF_HOST] @property def mac(self): """Return the mac address of this controller.""" for client in self.api.clients.values(): if self.host == client.ip: return client.mac return None async def async_setup(self, tries=0): """Set up a UniFi controller.""" hass = self.hass try: self.api = await get_controller( self.hass, **self.config_entry.data[CONF_CONTROLLER]) await self.api.initialize() except CannotConnect: retry_delay = 2 ** (tries + 1) LOGGER.error("Error connecting to the UniFi controller. Retrying " "in %d seconds", retry_delay) async def retry_setup(_now): """Retry setup.""" if await self.async_setup(tries + 1): # This feels hacky, we should find a better way to do this self.config_entry.state = config_entries.ENTRY_STATE_LOADED self._cancel_retry_setup = hass.helpers.event.async_call_later( retry_delay, retry_setup) return False except Exception: # pylint: disable=broad-except LOGGER.error( 'Unknown error connecting with UniFi controller.') return False if self.config_entry.data[CONF_POE_CONTROL]: hass.async_create_task( hass.config_entries.async_forward_entry_setup( self.config_entry, 'switch')) return True async def async_reset(self): """Reset this controller to default state. Will cancel any scheduled setup retry and will unload the config entry. """ # If we have a retry scheduled, we were never setup. if self._cancel_retry_setup is not None: self._cancel_retry_setup() self._cancel_retry_setup = None return True # If the authentication was wrong. if self.api is None: return True if self.config_entry.data[CONF_POE_CONTROL]: return await self.hass.config_entries.async_forward_entry_unload( self.config_entry, 'switch') return True async def get_controller( hass, host, username, password, port, site, verify_ssl): """Create a controller object and verify authentication.""" import aiounifi if verify_ssl: session = aiohttp_client.async_get_clientsession(hass) else: session = aiohttp_client.async_create_clientsession( hass, verify_ssl=verify_ssl, cookie_jar=CookieJar(unsafe=True)) controller = aiounifi.Controller( host, username=username, password=password, port=port, site=site, websession=session ) try: with async_timeout.timeout(10): await controller.login() return controller except aiounifi.Unauthorized: LOGGER.warning("Connected to UniFi at %s but not registered.", host) raise AuthenticationRequired except (asyncio.TimeoutError, aiounifi.RequestError): LOGGER.error("Error connecting to the UniFi controller at %s", host) raise CannotConnect except aiounifi.AiounifiException: LOGGER.exception('Unknown UniFi communication error occurred') raise AuthenticationRequired
{ "content_hash": "da3228348c8d4fcf075cbd0ed669914a", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 79, "avg_line_length": 32.274809160305345, "alnum_prop": 0.619678334910123, "repo_name": "PetePriority/home-assistant", "id": "11529cbe171abb420ce6d37bf149a0369238be5c", "size": "4228", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "homeassistant/components/unifi/controller.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1175" }, { "name": "Dockerfile", "bytes": "1073" }, { "name": "Python", "bytes": "13985647" }, { "name": "Ruby", "bytes": "745" }, { "name": "Shell", "bytes": "17364" } ], "symlink_target": "" }
import glob import os from PyQt4 import QtCore, QtGui from bmconfigparser import BMConfigParser import paths class LanguageBox(QtGui.QComboBox): languageName = {"system": "System Settings", "eo": "Esperanto", "en_pirate": "Pirate English"} def __init__(self, parent = None): super(QtGui.QComboBox, self).__init__(parent) self.populate() def populate(self): self.languages = [] self.clear() localesPath = os.path.join (paths.codePath(), 'translations') configuredLocale = "system" try: configuredLocale = BMConfigParser().get('bitmessagesettings', 'userlocale', "system") except: pass self.addItem(QtGui.QApplication.translate("settingsDialog", "System Settings", "system"), "system") self.setCurrentIndex(0) self.setInsertPolicy(QtGui.QComboBox.InsertAlphabetically) for translationFile in sorted(glob.glob(os.path.join(localesPath, "bitmessage_*.qm"))): localeShort = os.path.split(translationFile)[1].split("_", 1)[1][:-3] locale = QtCore.QLocale(QtCore.QString(localeShort)) if localeShort in LanguageBox.languageName: self.addItem(LanguageBox.languageName[localeShort], localeShort) elif locale.nativeLanguageName() == "": self.addItem(localeShort, localeShort) else: self.addItem(locale.nativeLanguageName(), localeShort) for i in range(self.count()): if self.itemData(i) == configuredLocale: self.setCurrentIndex(i) break
{ "content_hash": "5b9cf0dd23df79e3d7b2477697e1dcd7", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 107, "avg_line_length": 42.71052631578947, "alnum_prop": 0.6315465187923598, "repo_name": "hb9kns/PyBitmessage", "id": "552e0350449b4f40aaa58b2b983a7ad297ddd766", "size": "1623", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/bitmessageqt/languagebox.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7456" }, { "name": "C++", "bytes": "4482" }, { "name": "Makefile", "bytes": "4328" }, { "name": "Python", "bytes": "1520489" }, { "name": "QMake", "bytes": "2129" }, { "name": "Shell", "bytes": "14891" } ], "symlink_target": "" }
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='task.proto', package='tutorial', serialized_pb=_b('\n\ntask.proto\x12\x08tutorial\"\xed\x01\n\x04Task\x12\n\n\x02id\x18\x01 \x02(\x05\x12\r\n\x05title\x18\x02 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x02(\x05\x12\x0e\n\x06\x61uthor\x18\x05 \x01(\t\x12%\n\x06\x61nswer\x18\x06 \x03(\x0b\x32\x15.tutorial.Task.Answer\x1a\x44\n\x06\x41nswer\x12\x0c\n\x04\x64\x61ta\x18\x01 \x02(\x05\x12,\n\x04type\x18\x02 \x01(\x0e\x32\x19.tutorial.Task.AnswerType:\x03INT\"-\n\nAnswerType\x12\n\n\x06STRING\x10\x00\x12\x07\n\x03INT\x10\x01\x12\n\n\x06\x44OUBLE\x10\x02\"\'\n\x07\x41\x64\x64Task\x12\x1c\n\x04task\x18\x01 \x03(\x0b\x32\x0e.tutorial.Task') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _TASK_ANSWERTYPE = _descriptor.EnumDescriptor( name='AnswerType', full_name='tutorial.Task.AnswerType', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STRING', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='INT', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='DOUBLE', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=217, serialized_end=262, ) _sym_db.RegisterEnumDescriptor(_TASK_ANSWERTYPE) _TASK_ANSWER = _descriptor.Descriptor( name='Answer', full_name='tutorial.Task.Answer', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='data', full_name='tutorial.Task.Answer.data', index=0, number=1, type=5, cpp_type=1, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='type', full_name='tutorial.Task.Answer.type', index=1, number=2, type=14, cpp_type=8, label=1, has_default_value=True, default_value=1, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=147, serialized_end=215, ) _TASK = _descriptor.Descriptor( name='Task', full_name='tutorial.Task', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='tutorial.Task.id', index=0, number=1, type=5, cpp_type=1, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='title', full_name='tutorial.Task.title', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='content', full_name='tutorial.Task.content', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='score', full_name='tutorial.Task.score', index=3, number=4, type=5, cpp_type=1, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='author', full_name='tutorial.Task.author', index=4, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='answer', full_name='tutorial.Task.answer', index=5, number=6, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[_TASK_ANSWER, ], enum_types=[ _TASK_ANSWERTYPE, ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=25, serialized_end=262, ) _ADDTASK = _descriptor.Descriptor( name='AddTask', full_name='tutorial.AddTask', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='task', full_name='tutorial.AddTask.task', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=264, serialized_end=303, ) _TASK_ANSWER.fields_by_name['type'].enum_type = _TASK_ANSWERTYPE _TASK_ANSWER.containing_type = _TASK _TASK.fields_by_name['answer'].message_type = _TASK_ANSWER _TASK_ANSWERTYPE.containing_type = _TASK _ADDTASK.fields_by_name['task'].message_type = _TASK DESCRIPTOR.message_types_by_name['Task'] = _TASK DESCRIPTOR.message_types_by_name['AddTask'] = _ADDTASK Task = _reflection.GeneratedProtocolMessageType('Task', (_message.Message,), dict( Answer = _reflection.GeneratedProtocolMessageType('Answer', (_message.Message,), dict( DESCRIPTOR = _TASK_ANSWER, __module__ = 'task_pb2' # @@protoc_insertion_point(class_scope:tutorial.Task.Answer) )) , DESCRIPTOR = _TASK, __module__ = 'task_pb2' # @@protoc_insertion_point(class_scope:tutorial.Task) )) _sym_db.RegisterMessage(Task) _sym_db.RegisterMessage(Task.Answer) AddTask = _reflection.GeneratedProtocolMessageType('AddTask', (_message.Message,), dict( DESCRIPTOR = _ADDTASK, __module__ = 'task_pb2' # @@protoc_insertion_point(class_scope:tutorial.AddTask) )) _sym_db.RegisterMessage(AddTask) # @@protoc_insertion_point(module_scope)
{ "content_hash": "1c785e6591b15df7a1004711efd0595a", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 638, "avg_line_length": 32.86854460093897, "alnum_prop": 0.6851878303099557, "repo_name": "AlgorithmLover/OJCodes", "id": "30dc4ee852e3225b46969ad7e45b11d6d2735686", "size": "7082", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "qlcoder/serialization/protobuf/task_pb2.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "19271" }, { "name": "C++", "bytes": "105318" }, { "name": "CMake", "bytes": "18525" }, { "name": "CSS", "bytes": "1215" }, { "name": "HTML", "bytes": "11640" }, { "name": "Java", "bytes": "160067" }, { "name": "JavaScript", "bytes": "4932" }, { "name": "Makefile", "bytes": "22061" }, { "name": "Matlab", "bytes": "160" }, { "name": "PHP", "bytes": "829" }, { "name": "Python", "bytes": "169671" }, { "name": "Ruby", "bytes": "1148" }, { "name": "Scheme", "bytes": "6355" }, { "name": "Shell", "bytes": "1093" }, { "name": "Thrift", "bytes": "316" } ], "symlink_target": "" }
import json import os import hashlib import rinocloud CHUNK_SIZE = 6 * 1024 * 1024 class Object(object): def __init__(self, **kw): """ Initialise a bunch of variables """ # these are some rinocloud variables we dont mind showing to the users self.id = None self.created_on = None self.updated_on = None self._cloud_name = None self.name = None self.etag = None self.versions = [] # these are some variables we will keep hidden, marked with underscore self._size = None self._parent = None # this needs to be set by the user in order to save locally # they just call self.set_local_path self._path = rinocloud.path self.filepath = '' # lets set all the passed kwargs to this object for key, value in kw.items(): setattr(self, key, value) def __repr__(self): return "<rinocloud.Object name=%s id=%s>" % (self.name, self.id) def items(self): return self._prep_metadata().items() def iteritems(self): return self._prep_metadata().items() def keys(self): return self._prep_metadata().keys() def values(self): return self._prep_metadata().values() def __getitem__(self, key): return self.__dict__[key] def __setitem__(self, key, value): self.__dict__[key] = value def __delitem__(self, key): del self.__dict__[key] def __contains__(self, key): return key in self.__dict__ def __len__(self): return len(self.__dict__) def view(self): return json.dumps(self._prep_metadata(), indent=4) def increment_name(self, name, i): """ takes something like test.txt and returns test1.txt """ if i == 0: return name if '.' in name: split = name.split('.') split[-2] = split[-2] + str(i) return '.'.join(split) else: return name + str(i) def set_name(self, name, overwrite=False, increment=True): """ Sets the name of the file to be saved. @params name - the name to the file increment - whether or not to increment the filename if there is an existing file ie test.txt => test1.txt overwrite - whether or not to overwrite existing local file, renders increment redundant """ # check if the file exists exists = os.path.exists(os.path.join(self._path, self.increment_name(name, 0))) # make sure that we dont overwrite if overwrite and increment are both false warning = "Filename and path already exists, refusing to set filename without overwrite=True or increment=True" assert not (exists and not overwrite and not increment), warning if overwrite is True: increment = False # otherwise overwrite the file if increment is False: self.filepath = os.path.join(self._path, self.increment_name(name, 0)) self.name = self.increment_name(name, 0) return self.name # or increment the filename i = 0 while os.path.exists(os.path.join(self._path, self.increment_name(name, i))): i += 1 self.name = self.increment_name(name, i) self.filepath = os.path.join(self._path, self.increment_name(name, i)) return self.name def set_local_path(self, directory): """ sets path for local saving of information if create is true we will create the folder even if it doesnt exist """ self._path = directory def _prep_metadata(self): # copy the self.__dict__ and delete all that start with _ obj = self.__dict__.copy() [obj.pop(item) for item in list(obj.keys()) if item.startswith('_')] obj.pop('filepath') return obj def _process_response_metadata(self, response_metadata, **kw): self.__dict__.update(response_metadata["metadata"]) self.id = response_metadata["id"] self.created_on = response_metadata["created_on"] self.updated_on = response_metadata["updated_on"] self.etag = response_metadata["etag"] self._cloud_name = response_metadata["name"] self._rino_type = response_metadata["type"] self.versions = response_metadata["versions"] if self.name is None: self.set_name(response_metadata["name"], **kw) # these are some variables we will keep hidden, marked with underscore self._size = response_metadata["size"] self._parent = response_metadata["parent"] return self def save_local_metadata(self): """ save all the exposed variables to a json file """ # save to the set local path and add .json with open(self.filepath + '.json', 'w+') as outfile: json.dump(self._prep_metadata(), outfile, indent=4) def import_local_metadata(self): with open(self.filepath + '.json', 'r') as infile: meta = json.loads(infile.read()) self.__dict__.update(meta) def file_exists(self): return os.path.exists(self.filepath) def calculate_etag(self, expected=None): """ calculates a multipart upload etag in the same way as amazon s3 args: source_path -- The file to calculate the etage for chunk_size -- The chunk size to calculate for. expected -- optional If passed a string, the string will be compared to the resulting etag and raise an exception if they don't match """ md5s = [] with open(self.filepath, 'rb') as fp: while True: data = fp.read(CHUNK_SIZE) if not data: break md5s.append(hashlib.md5(data)) digests = b"".join(m.digest() for m in md5s) new_md5 = hashlib.md5(digests) new_etag = '%s-%s' % (new_md5.hexdigest(),len(md5s)) self.etag = new_etag return new_etag def upload(self): meta = self._prep_metadata() meta["parent"] = self._parent if self.file_exists(): r = rinocloud.http.upload(self.filepath, meta) else: r = rinocloud.http.upload_meta(meta) assert r.status_code == 201, "Upload failed:\n%s" % r.text self._process_response_metadata(r.json()) def upload_meta(self): meta = self._prep_metadata() meta["parent"] = self._parent r = rinocloud.http.upload_meta(meta) assert r.status_code == 201, "Upload failed:\n%s" % r.text self._process_response_metadata(r.json()) def update(self): meta = self._prep_metadata() meta["parent"] = self._parent r = rinocloud.http.upload_meta(meta) assert r.status_code == 201, "Upload failed:\n%s" % r.text self._process_response_metadata(r.json()) def get(self, id=None, truncate_metadata=True, **kw): _id = id if _id is None: if self.id is None: raise AttributeError("Can't fetch without an id. Need to either set Object.id or pass id to get.") else: _id = self.id r = rinocloud.http.get_metadata(_id, truncate_metadata=True) assert r.status_code != 404, "Object does not exist in Rinocloud. Error 404." self._process_response_metadata(r.json(), **kw) def download(self): assert self.id is not None, "Need to have id set to download data." assert self._rino_type == "file", "Target object is not a file, its a folder or empty object." r = rinocloud.http.download(self.id, self.filepath, self._size) assert r.status_code == 200, "Download error occured: %s" % r.text return self.filepath
{ "content_hash": "e26d76676790a146d6df1e5dffbe46a0", "timestamp": "", "source": "github", "line_count": 241, "max_line_length": 119, "avg_line_length": 33.30705394190871, "alnum_prop": 0.5751837548274573, "repo_name": "rinocloud/rinocloud-python", "id": "892dd658dfffb0799dfed9b447e082aac7913f2c", "size": "8027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rinocloud/object.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "24332" } ], "symlink_target": "" }
from sqlalchemy import Table, Column, Integer, String, BigInteger, Boolean, ForeignKeyConstraint from cassiopeia.data import Platform from cassiopeia.dto.spectator import CurrentGameInfoDto from cassiopeia.dto.common import DtoObject from .common import metadata, SQLBaseObject, map_object, foreignkey_options class CurrentGameParticipantDto(DtoObject): pass class SQLCurrentGameParticipant(SQLBaseObject): _dto_type = CurrentGameParticipantDto _table = Table("current_game_participant", metadata, Column("current_game_platformId", String(7), primary_key=True), Column("current_game_gameId", BigInteger, primary_key=True), Column("participantId", Integer, primary_key=True), Column("teamId", Integer), Column("spell1Id", Integer), Column("spell2Id", Integer), Column("championId", Integer), Column("profileIconId", Integer), Column("summonerName", String(30)), Column("bot", Boolean), Column("summonerId", String(63)), ForeignKeyConstraint( ["current_game_platformId", "current_game_gameId"], ["current_game.platformId", "current_game.gameId"] )) map_object(SQLCurrentGameParticipant) class CurrentGameBanDto(DtoObject): pass class SQLCurrentGameBan(SQLBaseObject): _dto_type = CurrentGameBanDto _table = Table("current_game_ban", metadata, Column("current_game_platformId", String(7), primary_key=True), Column("current_game_gameId", BigInteger, primary_key=True), Column("pickTurn", Integer, primary_key=True), Column("teamId", Integer), Column("championId", Integer), ForeignKeyConstraint( ["current_game_platformId", "current_game_gameId"], ["current_game.platformId", "current_game.gameId"], **foreignkey_options )) map_object(SQLCurrentGameBan) class SQLCurrentGameInfo(SQLBaseObject): _dto_type = CurrentGameInfoDto _table = Table("current_game", metadata, Column("platformId", String(7), primary_key=True), Column("gameId", BigInteger, primary_key=True), Column("gameStartTime", BigInteger), Column("gameMode", String(10)), Column("mapId", Integer), Column("gameType", String(12)), Column("gameQueueConfigId", Integer), Column("gameLength", Integer), Column("encryptionKey", String(32)), Column("featured", Boolean), Column("lastUpdate", BigInteger)) _relationships = {"bannedChampions": (SQLCurrentGameBan, {}), "participants": (SQLCurrentGameParticipant, {})} def __init__(self, featured=False, **kwargs): i = 1 for participant in kwargs["participants"]: participant["participantId"] = i i += 1 kwargs["encryptionKey"] = kwargs["observers"]["encryptionKey"] kwargs["featured"] = featured super().__init__(**kwargs) def to_dto(self): dto = super().to_dto() dto["observers"] = {"encryptionKey": dto["encryptionKey"]} dto["region"] = Platform(dto.pop("platformId")).region.value return dto map_object(SQLCurrentGameInfo)
{ "content_hash": "bc10f88eb984b9b2d6e27ea016ee8696", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 114, "avg_line_length": 39.472527472527474, "alnum_prop": 0.5807349665924276, "repo_name": "meraki-analytics/cassiopeia-datastores", "id": "943addc0d0b92b2ef3dba7cda8a15daa2d3b9bb7", "size": "3592", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cassiopeia-sqlstore/cassiopeia_sqlstore/spectator.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "136302" } ], "symlink_target": "" }
''' Created on May 20, 2013 @author: aryaveer ''' from django import forms import pickle from django.forms.util import ErrorList from django.utils import timezone from django.forms import widgets from utils.archives import Archive from utils.filetypes import is_valid, VALID_EXTENSIONS_COMPILERS, VALID_EXTENSIONS_INTERPRETERS, LANGUAGES, get_extension, get_compiler_name, get_interpreter_name, compile_required, execution_command_required from assignments.models import Assignment class DivErrorList(ErrorList): def __unicode__(self): return self.as_divs() def as_divs(self): if not self: return u'' return u'<div class="alert alert-error">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self]) # IMPORTANT: make sure all form fields are exactly the same as corresponding model fields. # TODO: May be try writing a method to do the above check. class AssignmentForm(forms.Form): name = forms.CharField(label="Assignment Name") deadline = forms.DateTimeField( input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%Y/%m/%d %H:%M'], label="Soft Deadline", help_text="Students can submit after this date if late submission is allowed." ) hard_deadline = forms.DateTimeField( input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%Y/%m/%d %H:%M'], label="Hard Deadline", help_text="Students can not submit after this date, if late submission is allowed." ) late_submission_allowed = forms.BooleanField( required=False, label="Late Submission Allowed?", help_text="If checked, students will be able to submit until hard deadline", ) choices = [(a, a) for a in LANGUAGES] program_language = forms.ChoiceField( choices=choices, label="Choose programming language", ) student_program_files = forms.CharField( label="List of files name that student must submit", help_text="File names separated by space.\ (File name shouldn't have space.)" ) document = forms.FileField( required=False, label="Documents", help_text="e.g. Some tutorial." ) helper_code = forms.FileField( required=False, label="Helper Code", help_text="Provide students with code template or libraries." ) model_solution = forms.FileField( error_messages={'invalid': 'File was not a valid tar file.'}, required=False, label="Solution Code(if any)", help_text="Accepted archives are tar, tar.gz, tar.bz2, zip." ) publish_on = forms.DateTimeField( label="Publish this assignment on", input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%Y/%m/%d %H:%M'] ) description = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): kwargs['error_class']=DivErrorList super(AssignmentForm, self).__init__(*args, **kwargs) def clean_name(self): if not hasattr(self, 'this_course'): return self.cleaned_data['name'] try: _ = Assignment.objects.get(name=self.cleaned_data['name'], course=self.this_course) raise forms.ValidationError('This assignment already exists in this course.') except Assignment.DoesNotExist: pass return self.cleaned_data['name'] def clean_deadline(self): deadline = self.cleaned_data['deadline'] if deadline and deadline < timezone.now(): raise forms.ValidationError('Deadline can not be in past.') return self.cleaned_data['deadline'] def check_model_solution(self, data): self._solution_file = [] if 'model_solution' in self.changed_data: if data.get('model_solution', ""): with Archive(fileobj=data['model_solution']) as archive: if not archive.is_archive(): if not is_valid(filename=data['model_solution'].name, lang=data['program_language']): self._errors['model_solution'] = self.error_class(["This file was not valid."]) del data['model_solution'] else: self._solution_file = [data['model_solution'].name] else: self._solution_file = [a.split("/")[-1] for a in archive.getfile_members()] else: # File is being deleted. pass else: # No change in file field. Check if file exist in database. if not hasattr(self, 'assignment_model'): return # Assignment is created without model solution. if not self.assignment_model.model_solution: return # no file in database. with Archive(fileobj=self.assignment_model.model_solution.file) as archive: if archive.is_archive(): self._solution_file = [a.split("/")[-1] for a in archive.getfile_members()] else: file_name = self.assignment_model.model_solution.name.split("/")[-1] self._solution_file = [file_name] def check_student_program_files(self, data): file_list = data.get('student_program_files').split() language = data.get('program_language') for afile in file_list: if not is_valid(afile, language): self._errors['student_program_files'] = self.error_class(["Only {1} files are accepted for {0} language.\ ".format(language, " ".join(get_extension(language)))]) del data['student_program_files'] break def clean(self): cleaned_data = super(AssignmentForm, self).clean() if self.errors: return cleaned_data self.check_student_program_files(cleaned_data) if self.errors: return cleaned_data self.check_model_solution(cleaned_data) if self._errors: return cleaned_data # file name to be compiled -- program files submitted by student should be in Teacher supplied tar. students_file_name = cleaned_data.get('student_program_files', "") students_file = set(students_file_name.split()) missing_file = students_file - set(self._solution_file) if missing_file and self._solution_file: self._errors['model_solution'] = self.error_class(["{0} was not found. Please upload {1}".format(" ".join(missing_file), students_file_name)]) del cleaned_data['model_solution'] if cleaned_data.get('deadline') > cleaned_data.get('hard_deadline'): self._errors['hard_deadline'] = self.error_class(['Hard deadline should be later than soft deadline']) return cleaned_data class CompilerCommandWidget(widgets.MultiWidget): def __init__(self, *args, **kwargs): widgets = [forms.TextInput(attrs={'readonly':'True'}), forms.TextInput, forms.TextInput] super(CompilerCommandWidget, self).__init__(widgets, *args, **kwargs) def decompress(self, value): if value: return pickle.loads(value) else: return ['', '', '',] class CompilerCommand(forms.fields.MultiValueField): widget = CompilerCommandWidget def __init__(self, *args, **kwargs): list_fields = [forms.fields.CharField(max_length=512, widget=forms.TextInput(attrs={'readonly':'True'}), required=False), forms.fields.CharField(max_length=512, required=False), forms.fields.CharField(max_length=512)] super(CompilerCommand, self).__init__(list_fields, *args, **kwargs) self.widget = CompilerCommandWidget() def compress(self, values): if values: if values[0] in forms.fields.EMPTY_VALUES: raise forms.fields.ValidationError("Please provide compiler name") if values[2] in forms.fields.EMPTY_VALUES: raise forms.fields.ValidationError("Please provide file names.") return pickle.dumps(values) class ExecutionCommandWidget(widgets.MultiWidget): def __init__(self, *args, **kwargs): widgets = [forms.TextInput(attrs={'readonly':'True'}), forms.TextInput, forms.TextInput] super(ExecutionCommandWidget, self).__init__(widgets, *args, **kwargs) def decompress(self, value): if value: return pickle.loads(value) else: return ['', '', '',] class ExecutionCommand(forms.fields.MultiValueField): widget = ExecutionCommandWidget def __init__(self, *args, **kwargs): list_fields = [forms.fields.CharField(max_length=512, widget=forms.TextInput(attrs={'readonly':'True'}), required=False), forms.fields.CharField(max_length=512, required=False), forms.fields.CharField(max_length=512)] super(ExecutionCommand, self).__init__(list_fields, *args, **kwargs) self.widget = ExecutionCommandWidget() def compress(self, values): if values: if values[0] in forms.fields.EMPTY_VALUES: raise forms.fields.ValidationError("Please provide name of the interpreter") if values[2] in forms.fields.EMPTY_VALUES: raise forms.fields.ValidationError("Please provide file names.") return pickle.dumps(values) class ProgramFormCNotE(forms.Form): #error_css_class = 'alert-error' #required_css_class = 'alert-error' PROGRAM_TYPES = ( ('Evaluate', 'Evaluate'), ('Practice', 'Practice'), ) name = forms.CharField() program_type = forms.ChoiceField(choices=PROGRAM_TYPES) compiler_command = CompilerCommand( help_text="Give compiler flags in second field and file names in third field. File names can be any of the files from student submission provided in assignment details.\ If you provide other file names, upload those files in additional files below.", required=False ) program_files = forms.FileField( error_messages={'invalid': 'File was not a valid tar file.',}, required = False, label="Additional Source Files", help_text="Provide additional source files here.\ Accepted archives are tar, tar.gz, tar.bz2, zip." ) makefile = forms.FileField( required=False, help_text="Must be a text file." ) description = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): kwargs['error_class']=DivErrorList super(ProgramFormCNotE, self).__init__(*args, **kwargs) def check_compiler_command(self, data): compiler_command = pickle.loads(data.get('compiler_command')) if get_compiler_name(self.assignment.program_language) != compiler_command[0]: self._errors['compiler_command'] = self.error_class(["Invalid compiler for {0} language .\ ".format(self.assignment.program_language)]) del data['compiler_command'] return for afile in compiler_command[2].split(): if not is_valid(filename=afile, compiler=compiler_command[0]): self._errors['compiler_command'] = self.error_class(["Only {1} files are accepted for {0} compiler.\ ".format(compiler_command[0], " ".join(get_extension(compiler_command[0])))]) del data['compiler_command'] def check_program_files(self, data): self.__teachers_file = [] if 'program_files' in self.changed_data: if data.get('program_files', ""): with Archive(fileobj=data['program_files']) as archive: if archive.is_archive(): self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()] else: if is_valid(filename=data['program_files'].name, compiler=pickle.loads(data['compiler_command'])[0]): self.__teachers_file = [data['program_files'].name] else: self._errors['program_files'] = self.error_class(["This file was not valid."]) del data['program_files'] else: # file is being deleted. pass else: # No change in file field. Check if file exist in database. if not hasattr(self, 'program_model'): return # Assignment is created without model solution. if not self.program_model.program_files: return # no file in database. with Archive(fileobj=self.program_model.program_files.file) as archive: if archive.is_archive(): self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()] else: if is_valid(filename=self.program_model.program_files.name, compiler=pickle.loads(data['compiler_command'])[0]): self.__teachers_file = [self.program_model.program_files.name.split("/")[-1]] else: file_name = self.program_model.program_files.name.split("/")[-1] self._errors['program_files'] = self.error_class(["File {0} is not valid. Please upload a valid file\ ".format(file_name)]) del data['program_files'] def clean(self): cleaned_data = super(ProgramFormCNotE, self).clean() if self.errors: return cleaned_data self.check_compiler_command(cleaned_data) if self._errors: return cleaned_data self.check_program_files(cleaned_data) if self._errors: return cleaned_data compiler_command = pickle.loads(cleaned_data.get('compiler_command')) # file name to be compiled -- program files submitted by student should be in Teacher supplied tar. file_to_compile = set(compiler_command[2].split()) students_file = cleaned_data.get('student_program_files', "") students_file = set(students_file.split()) missing_file = file_to_compile - set(self.__teachers_file) - set(self.assignment.student_program_files.split()) if missing_file: self._errors['program_files'] = self.error_class(["{0} is missing. It is one of the file in compilation command".format(" ".join(missing_file))]) del cleaned_data['program_files'] else: #Compile Program now. pass return cleaned_data class ProgramFormCandE(forms.Form): #error_css_class = 'alert-error' #required_css_class = 'alert-error' PROGRAM_TYPES = ( ('Evaluate', 'Evaluate'), ('Practice', 'Practice'), ) name = forms.CharField() program_type = forms.ChoiceField(choices=PROGRAM_TYPES) compiler_command = CompilerCommand(help_text="Give compiler flags in second field and file names in third field. File names can be any of the files from student submission provided in assignment details.\ If you provide other file names, upload those files in additional files below.", required=False ) execution_command = ExecutionCommand(help_text="Give the execution command in this textbox", required=False) program_files = forms.FileField( error_messages={'invalid': 'File was not a valid tar file.',}, required = False, label="Additional Source Files", help_text="Provide additional source files here.\ Accepted archives are tar, tar.gz, tar.bz2, zip." ) makefile = forms.FileField( required=False, help_text="Must be a text file." ) description = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): kwargs['error_class']=DivErrorList super(ProgramFormCandE, self).__init__(*args, **kwargs) def check_compiler_command(self, data): compiler_command = pickle.loads(data.get('compiler_command')) if get_compiler_name(self.assignment.program_language) != compiler_command[0]: self._errors['compiler_command'] = self.error_class(["Invalid compiler for {0} language .\ ".format(self.assignment.program_language)]) del data['compiler_command'] return for afile in compiler_command[2].split(): if not is_valid(filename=afile, compiler=compiler_command[0]): self._errors['compiler_command'] = self.error_class(["Only {1} files are accepted for {0} compiler.\ ".format(compiler_command[0], " ".join(get_extension(compiler_command[0])))]) del data['compiler_command'] def check_execution_command(self, data): execution_command = pickle.loads(data.get('execution_command')) if get_interpreter_name(self.assignment.program_language) != execution_command[0]: self._errors['execution_command'] = self.error_class(["Invalid interpreter for {0} language .\ ".format(self.assignment.program_language)]) del data['execution_command'] return for afile in execution_command[2].split(): if not is_valid(filename=afile, interpreter=execution_command[0]): self._errors['execution_command'] = self.error_class(["Only {1} files are accepted for {0} interpreter.\ ".format(execution_command[0], " ".join(get_extension(execution_command[0])))]) del data['execution_command'] def check_program_files(self, data): self.__teachers_file = [] if 'program_files' in self.changed_data: if data.get('program_files', ""): with Archive(fileobj=data['program_files']) as archive: if archive.is_archive(): self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()] else: if is_valid(filename=data['program_files'].name, compiler=pickle.loads(data['compiler_command'])[0]): self.__teachers_file = [data['program_files'].name] else: self._errors['program_files'] = self.error_class(["This file was not valid."]) del data['program_files'] else: # file is being deleted. pass else: # No change in file field. Check if file exist in database. if not hasattr(self, 'program_model'): return # Assignment is created without model solution. if not self.program_model.program_files: return # no file in database. with Archive(fileobj=self.program_model.program_files.file) as archive: if archive.is_archive(): self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()] else: if is_valid(filename=self.program_model.program_files.name, compiler=pickle.loads(data['compiler_command'])[0]): self.__teachers_file = [self.program_model.program_files.name.split("/")[-1]] else: file_name = self.program_model.program_files.name.split("/")[-1] self._errors['program_files'] = self.error_class(["File {0} is not valid. Please upload a valid file\ ".format(file_name)]) del data['program_files'] def clean(self): cleaned_data = super(ProgramFormCandE, self).clean() if self.errors: return cleaned_data self.check_compiler_command(cleaned_data) if self._errors: return cleaned_data self.check_execution_command(cleaned_data) if self._errors: return cleaned_data self.check_program_files(cleaned_data) if self._errors: return cleaned_data compiler_command = pickle.loads(cleaned_data.get('compiler_command')) execution_command = pickle.loads(cleaned_data.get('execution_command')) # file name to be compiled -- program files submitted by student should be in Teacher supplied tar. file_to_compile = set(compiler_command[2].split()) students_file = cleaned_data.get('student_program_files', "") students_file = set(students_file.split()) missing_file = file_to_compile - set(self.__teachers_file) - set(self.assignment.student_program_files.split()) if missing_file: self._errors['program_files'] = self.error_class(["{0} is missing. It is one of the file in compilation command".format(" ".join(missing_file))]) del cleaned_data['program_files'] else: #Compile Program now. pass return cleaned_data class ProgramFormE(forms.Form): #error_css_class = 'alert-error' #required_css_class = 'alert-error' PROGRAM_TYPES = ( ('Evaluate', 'Evaluate'), ('Practice', 'Practice'), ) name = forms.CharField() program_type = forms.ChoiceField(choices=PROGRAM_TYPES) execution_command = ExecutionCommand(help_text="Give the execution command in this textbox", required=False) program_files = forms.FileField( error_messages={'invalid': 'File was not a valid tar file.',}, required = False, label="Additional Source Files", help_text="Provide additional source files here.\ Accepted archives are tar, tar.gz, tar.bz2, zip." ) makefile = forms.FileField( required=False, help_text="Must be a text file." ) description = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): kwargs['error_class']=DivErrorList super(ProgramFormE, self).__init__(*args, **kwargs) def check_execution_command(self, data): execution_command = pickle.loads(data.get('execution_command')) if get_interpreter_name(self.assignment.program_language) != execution_command[0]: self._errors['execution_command'] = self.error_class(["Invalid interpreter for {0} language .\ ".format(self.assignment.program_language)]) del data['execution_command'] return for afile in execution_command[2].split(): if not is_valid(filename=afile, interpreter=execution_command[0]): self._errors['execution_command'] = self.error_class(["Only {1} files are accepted for {0} interpreter.\ ".format(execution_command[0], " ".join(get_extension(execution_command[0])))]) del data['execution_command'] def check_program_files(self, data): self.__teachers_file = [] if 'program_files' in self.changed_data: if data.get('program_files', ""): with Archive(fileobj=data['program_files']) as archive: if archive.is_archive(): self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()] else: if is_valid(filename=data['program_files'].name, interpreter=pickle.loads(data['execution_command'])[0]): self.__teachers_file = [data['program_files'].name] else: self._errors['program_files'] = self.error_class(["This file was not valid."]) del data['program_files'] else: # file is being deleted. pass else: # No change in file field. Check if file exist in database. if not hasattr(self, 'program_model'): return # Assignment is created without model solution. if not self.program_model.program_files: return # no file in database. with Archive(fileobj=self.program_model.program_files.file) as archive: if archive.is_archive(): self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()] else: if is_valid(filename=self.program_model.program_files.name, interpreter=pickle.loads(data['execution_command'])[0]): self.__teachers_file = [self.program_model.program_files.name.split("/")[-1]] else: file_name = self.program_model.program_files.name.split("/")[-1] self._errors['program_files'] = self.error_class(["File {0} is not valid. Please upload a valid file\ ".format(file_name)]) del data['program_files'] def clean(self): cleaned_data = super(ProgramFormE, self).clean() if self.errors: return cleaned_data self.check_execution_command(cleaned_data) if self._errors: return cleaned_data self.check_program_files(cleaned_data) if self._errors: return cleaned_data execution_command = pickle.loads(cleaned_data.get('execution_command')) # file name to be compiled -- program files submitted by student should be in Teacher supplied tar. file_to_execute = set(execution_command[2].split()) students_file = cleaned_data.get('student_program_files', "") students_file = set(students_file.split()) missing_file = file_to_execute - set(self.__teachers_file) - set(self.assignment.student_program_files.split()) if missing_file: self._errors['program_files'] = self.error_class(["{0} is missing. It is one of the file in execution command".format(" ".join(missing_file))]) del cleaned_data['program_files'] else: #Compile Program now. pass return cleaned_data class TestcaseForm(forms.Form): name = forms.CharField(label="Testcase Name") command_line_args = forms.CharField( label="Command Line Arguments", required=False ) marks = forms.IntegerField(label="Marks", required=False) input_files = forms.FileField( error_messages={'invalid': 'File was not a valid archive file.'}, required=False, label="Input Files", help_text="File used for program as input. Accepted archives are tar, tar.gz, tar.bz2, zip.", allow_empty_file=True, ) output_files = forms.FileField( error_messages={'invalid': 'File was not a valid tar file.'}, required=False, label="Output Files", help_text="Expected output files produced by program. Accepted archives are tar, tar.gz, tar.bz2, zip.", allow_empty_file=True, ) description = forms.CharField( widget=forms.Textarea, required=False ) def __init__(self, *args, **kwargs): kwargs['error_class'] = DivErrorList self.solution_ready = kwargs.pop('solution_ready', False) super(TestcaseForm, self).__init__(*args, **kwargs) def clean_input_files(self): data = self.cleaned_data # TODO: check if files are not tar it must be text file. return data['input_files'] def clean_output_files(self): # TODO: check if files are not tar it must be text file. data = self.cleaned_data return data['output_files'] def clean(self): cleaned_data = super(TestcaseForm, self).clean() if cleaned_data['marks'] is None: # cleaned_data['test_type'] == "Evaluate" and self._errors['marks'] = self.error_class(['This field is required.']) # if solution executable is not available make output file required. if (not self.solution_ready) and cleaned_data['output_files'] is None: self._errors['output_files'] = self.error_class(['Solution code for this assignment is not available/broken please upload output files.']) return cleaned_data class TestcaseForm2(forms.Form): std_in_file_name = forms.ChoiceField( label="Select File for Standard input", widget=forms.RadioSelect(), choices=((("None", "None"),)), help_text="Content will be supplied as standard input." ) std_out_file_name = forms.ChoiceField( label="Select File for Standard output", widget=forms.RadioSelect(), choices=((("None", "None"),)), help_text="File's content will used to compare standard output of program." ) def __init__(self, *args, **kwargs): in_file_name = kwargs.pop('in_file_choices', (("None", "None"),)) out_file_name = kwargs.pop('out_file_choices', (("None", "None"),)) kwargs['error_class'] = DivErrorList super(TestcaseForm2, self).__init__(*args, **kwargs) self.fields['std_in_file_name'].choices = in_file_name self.fields['std_out_file_name'].choices = out_file_name class SafeExecForm(forms.Form): cpu_time = forms.IntegerField(label="CPU time", help_text='Default is 10 seconds.') clock_time = forms.IntegerField(label="Clock time", help_text='Default is 60 seconds.') memory = forms.IntegerField(label="Memory limit", help_text='Default is 32768 kbytes.') stack_size = forms.IntegerField(label="Stack size limit", help_text='Default is 8192 kbytes.') child_processes = forms.IntegerField(label="Number of child processes", help_text='Number of child processes it can create. Default is 0.') open_files = forms.IntegerField( label="Number of open files", help_text='Number of files the program can open. Default value is 512. Do not set this too\ low otherwise program will not be able to open shared libraries.' ) file_size = forms.IntegerField(label="Max file size", help_text='Maximum size of file the program can write. Default size is 0 kbytes.') env_vars = forms.CharField(label="Environment variables", required=False)
{ "content_hash": "a64e4d9b4b3ac9f062bc77000d0d4e01", "timestamp": "", "source": "github", "line_count": 633, "max_line_length": 208, "avg_line_length": 50.23380726698262, "alnum_prop": 0.5727089754072583, "repo_name": "kartikshah1/Test", "id": "a694efb411a9a29e12bde8f04d639d1e6f56b4ca", "size": "31798", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assignments/forms.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "21691" }, { "name": "C++", "bytes": "3267" }, { "name": "CSS", "bytes": "355299" }, { "name": "Java", "bytes": "9833" }, { "name": "JavaScript", "bytes": "2844415" }, { "name": "Perl", "bytes": "4202" }, { "name": "Python", "bytes": "1703618" }, { "name": "Shell", "bytes": "6379" } ], "symlink_target": "" }
import csv import os """ Parsing model sate output file to csv with following headers: doc source pos typeindex type topic """ fread = open("out-state", "r+") fwrite = open("out-state.csv", "w+") # writer = csv.writer(fwrite, delimiter = ',', quotechar = '"') str = fread.readline() str = ','.join(str.replace("#", "").split()) fwrite.write(str+"\n") fread.readline() fread.readline() for line in fread: # if "#alpha" in line = ','.join(line.split()) fwrite.write(line+"\n") fread.close() fwrite.close()
{ "content_hash": "5ba64b210879531f761fa7d17e1f1b02", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 64, "avg_line_length": 20.92, "alnum_prop": 0.6367112810707457, "repo_name": "satybald/twitter-modeling-lda", "id": "66ed270fce2ce32315ff6cddf2efc0f1d316e024", "size": "523", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source code/twitter-lda/mode2csv.py", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1260137" }, { "name": "Perl", "bytes": "309902" }, { "name": "Python", "bytes": "9746" }, { "name": "Shell", "bytes": "511" } ], "symlink_target": "" }
from django.urls import path from django_cradmin.apps.cradmin_register_account.views import register_account urlpatterns = [ path('', register_account.RegisterAccountView.as_view(), name="cradmin-register-account"), ]
{ "content_hash": "d55f6b037e17c44004a16d6bcfc5ead6", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 79, "avg_line_length": 30.125, "alnum_prop": 0.7219917012448133, "repo_name": "appressoas/django_cradmin", "id": "2967c93a59d62969ff829872f978c9d2ebcedf9f", "size": "241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "django_cradmin/apps/cradmin_register_account/urls.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "192105" }, { "name": "JavaScript", "bytes": "1951677" }, { "name": "Python", "bytes": "771868" }, { "name": "SCSS", "bytes": "679114" } ], "symlink_target": "" }
from django import forms from django.conf import settings from flatpages.models import FlatPage from django.utils.translation import ugettext, ugettext_lazy as _ from ckeditor_uploader.widgets import CKEditorUploadingWidget class FlatpageForm(forms.ModelForm): url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/\.~]+$', help_text=_("Example: '/about/contact/'. Make sure to have leading" " and trailing slashes."), error_messages={ "invalid": _("This value must contain only letters, numbers," " dots, underscores, dashes, slashes or tildes."), }, ) content = forms.CharField(widget=CKEditorUploadingWidget()) class Meta: model = FlatPage fields = '__all__' def clean_url(self): url = self.cleaned_data['url'] if not url.startswith('/'): raise forms.ValidationError( ugettext("URL is missing a leading slash."), code='missing_leading_slash', ) if (settings.APPEND_SLASH and 'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLASSES and not url.endswith('/')): raise forms.ValidationError( ugettext("URL is missing a trailing slash."), code='missing_trailing_slash', ) return url def clean(self): url = self.cleaned_data.get('url') same_url = FlatPage.objects.filter(url=url) if self.instance.pk: same_url = same_url.exclude(pk=self.instance.pk) return super(FlatpageForm, self).clean()
{ "content_hash": "5a89a9a66ad244919fcc8f672a6c5e45", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 94, "avg_line_length": 37.08888888888889, "alnum_prop": 0.597363690832834, "repo_name": "rit-sailing/website", "id": "e52a4def019226ffc17c882db0d892333b65df54", "size": "1669", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flatpages/forms.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29508" }, { "name": "HTML", "bytes": "103215" }, { "name": "JavaScript", "bytes": "81277" }, { "name": "Python", "bytes": "66948" } ], "symlink_target": "" }
from selenium.webdriver.common.by import By class LearningCircleCreationPageLocators(object): FIRST_COURSE_BUTTON = (By.CSS_SELECTOR, ".course:nth-child(1) a.btn:nth-child(2)") FIRST_COURSE_TITLE = (By.CSS_SELECTOR, ".course:nth-child(1) .card-title") REMOVE_COURSE_SELECTION_LINK = (By.LINK_TEXT, "Remove selection") NEXT_TAB_BUTTON = (By.CSS_SELECTOR, ".action-bar button.next-tab") CITY_SELECT = (By.CSS_SELECTOR, ".city-select input") CITY_SELECT_INPUT = (By.CSS_SELECTOR, ".city-select input") CITY_SELECT_OPTION = (By.CSS_SELECTOR, ".city-select .place-select__option") TAB_1 = (By.CSS_SELECTOR, "#react-tabs-0") TAB_1_TITLE = (By.CSS_SELECTOR, "#react-tabs-1 h4") TAB_2 = (By.CSS_SELECTOR, "#react-tabs-2") TAB_2_TITLE = (By.CSS_SELECTOR, "#react-tabs-3 h4") TAB_3 = (By.CSS_SELECTOR, "#react-tabs-4") TAB_3_TITLE = (By.CSS_SELECTOR, "#react-tabs-5 h4") TAB_4 = (By.CSS_SELECTOR, "#react-tabs-6") TAB_4_TITLE = (By.CSS_SELECTOR, "#react-tabs-7 h4") TAB_5 = (By.CSS_SELECTOR, "#react-tabs-8") TAB_5_TITLE = (By.CSS_SELECTOR, "#react-tabs-9 h4") VENUE_NAME_FIELD = (By.ID, "venue_name") VENUE_DETAILS_FIELD = (By.ID, "venue_details") VENUE_ADDRESS_FIELD = (By.ID, "venue_address") START_DATE_FIELD = (By.ID, "start_date") MEETING_COUNT_FIELD = (By.ID, "meeting_count") MEETING_TIME_FIELD = (By.CSS_SELECTOR, "#meeting_time input") MEETING_END_TIME_FIELD = (By.CSS_SELECTOR, "#meeting_end_time input") TITLE_FIELD = (By.ID, "name") DESCRIPTION_FIELD = (By.ID, "description_ifr") COURSE_DESCRIPTION_FIELD = (By.ID, "course_description_ifr") SIGNUP_QUESTION_FIELD = (By.ID, "signup_question") VENUE_WEBSITE_FIELD = (By.ID, "venue_website") FACILITATOR_GOAL_FIELD = (By.ID, "facilitator_goal") FACILITATOR_CONCERNS_FIELD = (By.ID, "facilitator_concerns") SUCCESS_ALERT = (By.CSS_SELECTOR, ".alert.alert-success") DANGER_ALERT = (By.CSS_SELECTOR, ".alert.alert-danger") ALERT_CLOSE_BUTTON = (By.CSS_SELECTOR, ".alert.alert-dismissible .btn-close") COURSE_CARDS = (By.CSS_SELECTOR, "#react-tabs-1 .search-results .course") PUBLISH_BUTTON = (By.CSS_SELECTOR, ".action-bar button.publish") SAVE_BUTTON = (By.CSS_SELECTOR, ".action-bar button.save") MODAL_BUTTON = (By.ID, "recurrence-modal-btn") SCHEDULE_MEETINGS_BUTTON = (By.ID, "schedule-meetings-btn") ERROR_MESSAGE = (By.CSS_SELECTOR, ".error-message.minicaps") TINYMCE_FIELD = (By.ID, "tinymce") CALENDAR_TODAY = (By.CSS_SELECTOR, ".DayPicker-Day--today") ACCEPT_SUGGESTED_DATES_BUTTON = (By.ID, "accept-suggestions-btn") class RegistrationModalLocators(object): REGISTRATION_MODAL = (By.CSS_SELECTOR, ".registration-modal") REGISTRATION_MODAL_TITLE = (By.CSS_SELECTOR, ".registration-modal-content h4") MODAL_OVERLAY = (By.CSS_SELECTOR, ".modal-overlay") EMAIL_FIELD = (By.ID, "email") PASSWORD_FIELD = (By.ID, "password") SUBMIT_BUTTON = (By.CSS_SELECTOR, ".modal-actions button[type=submit]")
{ "content_hash": "76020ec8ea7bc121761008e6a7eeaee8", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 86, "avg_line_length": 53.50877192982456, "alnum_prop": 0.6675409836065573, "repo_name": "p2pu/learning-circles", "id": "f1fb574c988346213de0a240e5394ef31fad90bb", "size": "3050", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "e2e/tests/selenium/locators.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6537" }, { "name": "Dockerfile", "bytes": "2110" }, { "name": "HTML", "bytes": "222765" }, { "name": "JavaScript", "bytes": "202138" }, { "name": "Python", "bytes": "859945" }, { "name": "SCSS", "bytes": "122949" }, { "name": "Shell", "bytes": "808" } ], "symlink_target": "" }
import unittest from brew.utilities.efficiency import calculate_brew_house_yield from fixtures import recipe class TestEfficiencyUtilities(unittest.TestCase): def setUp(self): self.recipe = recipe def test_calculate_brew_house_yield(self): out = calculate_brew_house_yield( recipe.final_volume, recipe.og, recipe.grain_additions ) self.assertEquals(round(out, 3), self.recipe.brew_house_yield)
{ "content_hash": "72065142e4e727777da862cbe4057259", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 70, "avg_line_length": 30, "alnum_prop": 0.7111111111111111, "repo_name": "chrisgilmerproj/brewday", "id": "bd3169b772ecbfacb4278241d9c69a39bfe57166", "size": "474", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_utilities_efficiency.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "1528" }, { "name": "Python", "bytes": "313918" }, { "name": "Shell", "bytes": "213" } ], "symlink_target": "" }
""" Created on Wed Aug 28 11:04:48 2013 @author: Craig """ # standard modules import os.path import logging import zipfile from zipfile import ZipFile # site modules from boto.s3.connection import S3Connection from boto.s3.key import Key as S3Key # local modules # CONSTANTS class S3access(object): def __init__(self, aws_access, aws_secret): self.conn = S3Connection(aws_access, aws_secret) if self.conn is None: raise RuntimeError("AWS connection failed") logging.info ("Connected to AWS through %s."%(aws_access,)) def close(self): self.conn.close() def ship_file(self, fpath, bucketnm, s3name=None, public=None): if s3name is None: s3name = os.path.basename(fpath) # set access control if public is None or public == '': acl = 'private' elif public.upper() == 'R': acl = 'public-read' elif public.upper() == 'W': acl = 'public-read-write' else: logging.warn( "Unrecognized access code '%s'; setting private access." %(public,)) acl = 'private' try: bucket = self.conn.lookup(bucketnm) k = S3Key(bucket) k.key = s3name k.set_contents_from_filename(fpath, reduced_redundancy=True, policy=acl) k.set_acl(acl) except Exception: logging.error ( "S3 connection failed; check AWS access code and password") raise logging.info ("S3 file '%s' stored as %s."%(s3name, acl)) def zip_and_ship_file(self, fpath, bucketnm, s3name=None, public=None): zfpath = fpath + '.zip' zfile = ZipFile(zfpath, 'w', zipfile.ZIP_DEFLATED) try: zfile.write(fpath, os.path.basename(fpath)) finally: zfile.close() self.ship_file(zfpath, bucketnm, s3name, public)
{ "content_hash": "d7301cccd6a498f304779941b6a770c0", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 79, "avg_line_length": 27.64864864864865, "alnum_prop": 0.5498533724340176, "repo_name": "SkyTruth/scraper", "id": "88789d8043667d2bf70d9998c0904a43c14736ef", "size": "2070", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "utils/s3access.py", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "2968" }, { "name": "PLpgSQL", "bytes": "940465" }, { "name": "Python", "bytes": "502777" }, { "name": "Shell", "bytes": "4368" } ], "symlink_target": "" }
"""Contains private utilities used mainly by the base Layer class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import threading from tensorflow.python import tf2 from tensorflow.python.distribute import distribution_strategy_context from tensorflow.python.eager import context from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.keras import backend from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_util from tensorflow.python.ops import control_flow_v2_func_graphs from tensorflow.python.ops import init_ops from tensorflow.python.ops import init_ops_v2 from tensorflow.python.ops import variables as tf_variables from tensorflow.python.training.tracking import base as tracking from tensorflow.python.util import nest from tensorflow.python.util import tf_contextlib _call_context = threading.local() def create_mean_metric(value, name=None): # import keras will import base_layer and then this module, and metric relies # on base_layer, which result into a cyclic dependency. from tensorflow.python.keras import metrics as metrics_module # pylint: disable=g-import-not-at-top metric_obj = metrics_module.Mean(name=name, dtype=value.dtype) return metric_obj, metric_obj(value) def make_variable(name, shape=None, dtype=dtypes.float32, initializer=None, trainable=None, caching_device=None, validate_shape=True, constraint=None, use_resource=None, collections=None, synchronization=tf_variables.VariableSynchronization.AUTO, aggregation=tf_variables.VariableAggregation.NONE, partitioner=None): # pylint: disable=unused-argument """Temporary util to create a variable (relies on `variable_scope.variable`). Some reuse-related technicalities prevent us from using `variable_scope.get_variable()` directly, so we use a subcomponent that has fewer constraints (`variable_scope.variable()`). In the longer term, it seems like a similar "default variable creator" method should exist in `Trackable` instead. When this happens, we can get rid of this temporary solution. TODO(fchollet): remove this method when no longer needed. Arguments: name: Variable name. shape: Variable shape. dtype: The type of the variable. Defaults to `self.dtype` or `float32`. initializer: Initializer instance (callable). trainable: Whether the variable should be part of the layer's "trainable_variables" (e.g. variables, biases) or "non_trainable_variables" (e.g. BatchNorm mean, stddev). Note, if the current variable scope is marked as non-trainable then this parameter is ignored and any added variables are also marked as non-trainable. `trainable` defaults to `True` unless `synchronization` is set to `ON_READ`. caching_device: Passed to `tf.Variable`. validate_shape: Passed to `tf.Variable`. constraint: Constraint instance (callable). use_resource: Whether to use a `ResourceVariable`. collections: List of graph collections keys. The new variable is added to these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. synchronization: Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class `tf.VariableSynchronization`. By default the synchronization is set to `AUTO` and the current `DistributionStrategy` chooses when to synchronize. If `synchronization` is set to `ON_READ`, `trainable` must not be set to `True`. aggregation: Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class `tf.VariableAggregation`. partitioner: Not handled at this time. Returns: Variable instance. """ initializing_from_value = False if initializer is not None and not callable(initializer): initializing_from_value = True with ops.init_scope(): if initializing_from_value: init_val = initializer variable_dtype = None else: # Instantiate initializer if provided initializer is a type object. if isinstance( initializer, (type(init_ops.Initializer), type(init_ops_v2.Initializer))): initializer = initializer() init_val = lambda: initializer(shape, dtype=dtype) variable_dtype = dtype.base_dtype if use_resource is None: use_resource = True # TODO(apassos,rohanj) figure out how to remove collections from here so we # can remove the V1. variable_shape = tensor_shape.TensorShape(shape) return tf_variables.VariableV1( initial_value=init_val, name=name, trainable=trainable, caching_device=caching_device, dtype=variable_dtype, validate_shape=validate_shape, constraint=constraint, use_resource=use_resource, collections=collections, synchronization=synchronization, aggregation=aggregation, shape=variable_shape if variable_shape else None) def collect_previous_mask(input_tensors): """Retrieves the output mask(s) of the previous node. Arguments: input_tensors: An arbitrary structure of Tensors. Returns: A mask tensor or list of mask tensors. """ def _collect_previous_mask(x): return getattr(x, '_keras_mask', None) return nest.map_structure(_collect_previous_mask, input_tensors) def have_all_keras_metadata(tensors): return all(hasattr(x, '_keras_history') for x in nest.flatten(tensors)) def generate_placeholders_from_shape(shape): return array_ops.placeholder(shape=shape, dtype=backend.floatx()) def create_keras_history(tensors): """Wraps TensorFlow Operations for compatibility with the Functional API. This method checks to see if a Tensor in `tensors` is missing Keras metadata and has its origin in a Keras `Input` Layer. If so, this method will replace the raw TensorFlow Operations that created this tensor with `TensorFlowOpLayer` instances that create identical operations. Any Tensors not originating from a Keras `Input` Layer will be treated as constants when constructing `TensorFlowOpLayer` instances. Arguments: tensors: A structure of Tensors, some of which come from raw TensorFlow operations and need to have Keras metadata assigned to them. Returns: keras_tensors: The Tensors found that came from a Keras Layer. """ _, created_layers = _create_keras_history_helper(tensors, set(), []) return created_layers def _create_keras_history_helper(tensors, processed_ops, created_layers): """Helper method for `create_keras_history`. Arguments: tensors: A structure of Tensors for which to create Keras metadata. processed_ops: Set. TensorFlow operations that have already been wrapped in `TensorFlowOpLayer` instances. created_layers: List. The `TensorFlowOpLayer` instances created. Returns: Tuple. First element is the updated set of TensorFlow Operations that have been wrapped in `TensorFlowOpLayer` instances. Second element is a list of the `TensorFlowOpLayer` instances created. """ # Import of `base_layer` needed in order to create `TensorFlowOpLayer`. # Cannot be imported at top because of circular dependencies. # TODO(omalleyt): Resolve circular dependency. from tensorflow.python.keras.engine import base_layer # pylint: disable=g-import-not-at-top tensor_list = nest.flatten(tensors) for tensor in tensor_list: if getattr(tensor, '_keras_history', None) is not None: continue op = tensor.op # The Op that created this Tensor. if op not in processed_ops: if op.type.startswith('Sparse'): lambda_example = """ weights_mult = lambda x: tf.sparse.sparse_dense_matmul(x, weights) output = tf.keras.layers.Lambda(weights_mult)(input) """ raise ValueError( 'Sparse ops are not supported with functional models with built-in ' 'layer wrapping. Please wrap the sparse ops in a Lambda layer like' ': \n{lambda_example}\n'.format(lambda_example=lambda_example)) # Recursively set `_keras_history`. op_inputs = list(op.inputs) constants = {} layer_inputs = [] for i, op_input in enumerate(op_inputs): if uses_keras_history(op_input): layer_inputs.append(op_input) else: # Treat any value not originating from a `keras.Input` as # a constant. Variables cannot be supported. ds_with_session = ( distribution_strategy_context.in_cross_replica_context() and not ops.executing_eagerly_outside_functions()) using_xla = control_flow_util.GraphOrParentsInXlaContext( ops.get_default_graph()) if ds_with_session or using_xla: # In Legacy Graph mode, evaluating here makes Session be # configured improperly. The downside of this is that saving # via `get_config` breaks, but SavedModel still works. constants[i] = op_input else: with ops.init_scope(): constants[i] = backend.function([], op_input)([]) layer_inputs = unnest_if_single_tensor(layer_inputs) processed_ops, created_layers = _create_keras_history_helper( layer_inputs, processed_ops, created_layers) name = op.name node_def = op.node_def.SerializeToString() op_layer = base_layer.TensorFlowOpLayer( node_def, constants=constants, name=name) created_layers.append(op_layer) op_layer._add_inbound_node( # pylint: disable=protected-access layer_inputs, op.outputs) processed_ops.update([op]) return processed_ops, created_layers def unnest_if_single_tensor(input_tensors): # Preserve compatibility with older configs flat_input_tensors = nest.flatten(input_tensors) # If this is a single element but not a dict, unwrap. If this is a dict, # assume the first layer expects a dict (as is the case with a # DenseFeatures layer); pass through. if not isinstance(input_tensors, dict) and len(flat_input_tensors) == 1: input_tensors = flat_input_tensors[0] return input_tensors def needs_keras_history(tensors, ignore_call_context=False): """Check if any Tensors need to be wrapped in TensorFlowOpLayers. This will never return True inside a sublayer, because sublayers do not need to create Keras History. Otherwise, this returns True if one or more of `tensors` originates from a `keras.Input` and does not have `_keras_history` set. Arguments: tensors: An arbitrary nested structure of Tensors. ignore_call_context: Whether to ignore the check of if currently outside of a `call` context. This is `True` when creating KerasHistory inside `Node`, where we always know that Tensors are being used with the Functional API. Returns: Bool, whether at least one Tensor needs to be wrapped. """ input_tensors = nest.flatten(tensors) if call_context().in_call and not ignore_call_context: return False if all( getattr(tensor, '_keras_history', None) is not None for tensor in input_tensors): # KerasHistory already set. return False return uses_keras_history(tensors) def is_in_keras_graph(): """Returns if currently executing inside of a Keras graph.""" return call_context().in_keras_graph def is_in_eager_or_tf_function(): """Returns if in eager mode or inside of a tf.function.""" return context.executing_eagerly() or is_in_tf_function() def is_in_tf_function(): """Returns if inside of a tf.function.""" # Check if running in V1 graph mode. if not ops.executing_eagerly_outside_functions(): return False if not ops.inside_function(): return False # Check if inside Keras FuncGraph. if is_in_keras_graph(): return False # Check for a v1 `wrap_function` FuncGraph. graph = ops.get_default_graph() if (getattr(graph, 'name', False) and graph.name.startswith('wrapped_function')): return False return True def uses_keras_history(tensors): """Check if at least one Tensor originates from a `keras.Input`. This is `True` if at least one Tensor has its origin in a `keras.Input`. Any Tensor that originates from a `keras.Input` will have a dependency Tensor with a `_keras_history` attribute attached. Tensors that have already been checked to not originate from a `keras.Input` are marked as `_keras_history_checked`. Arguments: tensors: An arbitrary nested structure of Tensors. Returns: Bool, whether at least one Tensor originates from a `keras.Input`. """ checked_tensors = set() tensors_to_check = nest.flatten(tensors) while tensors_to_check: new_tensors_to_check = [] for tensor in tensors_to_check: if id(tensor) in checked_tensors: continue checked_tensors.add(id(tensor)) if getattr(tensor, '_keras_history_checked', None) is not None: continue if getattr(tensor, '_keras_history', None) is not None: return True try: new_tensors_to_check.extend(tensor.op.inputs) except AttributeError: # In case `tensor` is a Variable created in an Eager context. pass tensors_to_check = new_tensors_to_check # Mark that these Tensors have been checked once for `_keras_history`, # and should not be checked again for performance reasons. mark_checked(tensors) return False def mark_checked(tensors): """Marks that these Tensors should not be tracked. This prevents Layers from attempting to create TensorFlowOpLayers for these Tensors. Arguments: tensors: An arbitrary structure of Tensors. """ def _mark_checked(tensor): tensor._keras_history_checked = True # pylint: disable=protected-access nest.map_structure(_mark_checked, tensors) def call_context(): """Returns currently active `CallContext`.""" if getattr(_call_context, 'call_context', None) is None: _call_context.call_context = CallContext() return _call_context.call_context class CallContext(object): """Keeps track of properties currently inside a Layer/Model's `call`. Attributes: layer: The `Layer` whose `call` is currently active. inputs: The inputs to the currently active `Layer`. frozen: Whether currently executing inside a `Layer` with `trainable` set to `False`. in_call: Whether currently inside the `call` of a Layer. training: Whether currently executing in training or inference mode. in_keras_graph: Whether executing inside the Keras Graph. saving: Whether currently saving to SavedModel. """ def __init__(self): self.layer = None self.inputs = None self.frozen = False self.in_call = False self.training = None self._in_keras_graph = False self.saving = False @tf_contextlib.contextmanager def enter(self, layer, inputs, build_graph, training, saving=None): """Push a Layer and its inputs and state onto the current call context.""" prev_layer = self.layer prev_inputs = self.inputs prev_frozen = self.frozen prev_in_call = self.in_call prev_training = self.training prev_in_keras_graph = self._in_keras_graph prev_saving = self.saving self.layer = layer self.inputs = inputs self.frozen = self.frozen or not layer.trainable self.in_call = True self.training = training self._in_keras_graph = ( self._in_keras_graph or (build_graph and getattr(backend.get_graph(), 'name', None) == 'keras_graph')) self.saving = prev_saving if saving is None else saving try: yield finally: self.layer = prev_layer self.inputs = prev_inputs self.frozen = prev_frozen self.in_call = prev_in_call self.training = prev_training self._in_keras_graph = prev_in_keras_graph self.saving = prev_saving @property def in_keras_graph(self): # Returns True even if in a subgraph of the Keras graph, such as those # created by control flow ops. if context.executing_eagerly(): return False return (self._in_keras_graph or getattr(backend.get_graph(), 'name', None) == 'keras_graph') def training_arg_passed_to_call(argspec, args, kwargs): """Returns whether a user passed the `training` argument in `__call__`.""" # `argspec.args` starts with ['self', 'inputs'] full_args = dict(zip(argspec.args[2:], args)) full_args.update(kwargs) return 'training' in full_args and full_args['training'] is not None def autocast_context_manager(dtype): """Returns a context manager to autocast AutoCastVariables. Under this context manager, AutoCastVariables will be casted to `dtype` if `dtype` is floating-point. Otherwise, AutoCastVariables will not be casted. Args: dtype: The dtype to cast AutoCastVariables to, or None. Returns: A context manager to automatically cast AutoCastVariables. """ if dtype and not dtypes.as_dtype(dtype).is_floating: dtype = None return ops.get_default_graph()._enable_auto_casting_variables(dtype) # pylint: disable=protected-access def is_subclassed(layer): """Returns True if the object is a subclassed layer or subclassed model.""" return (layer.__module__.find('keras.engine') == -1 and layer.__module__.find('keras.layers') == -1) def from_saved_model(layer): """Returns whether the layer is loaded from a SavedModel.""" return layer.__module__.find('keras.saving.saved_model') != -1 def check_graph_consistency(tensor=None, method='add_loss', force_raise=False): """Checks that tensors passed to `add_*` method match the Keras graph. When one of the `add_*` method is called inside a V2 conditional branch, the underlying tensor gets created in a FuncGraph managed by control_flow_v2. We need to raise clear error messages in such cases. Arguments: tensor: Tensor to check, or `False` if it is known that an error should be raised. method: Caller method, one of {'add_metric', 'add_loss', 'add_update'}. force_raise: If an error should be raised regardless of `tensor`. Raises: RuntimeError: In case of an out-of-graph tensor. """ if (force_raise or (ops.executing_eagerly_outside_functions() and hasattr(tensor, 'graph') and isinstance(tensor.graph, (control_flow_v2_func_graphs.CondBranchFuncGraph, control_flow_v2_func_graphs.WhileCondFuncGraph, control_flow_v2_func_graphs.WhileBodyFuncGraph)))): if method == 'activity_regularizer': bad_example = """ class TestModel(tf.keras.Model): def __init__(self): super(TestModel, self).__init__(name='test_model') self.dense = tf.keras.layers.Dense(2, activity_regularizer='l2') def call(self, x, training=None): if training: return self.dense(x) else: return self.dense(x) """ correct_example = """ class TestModel(tf.keras.Model): def __init__(self): super(TestModel, self).__init__(name='test_model') self.dense = tf.keras.layers.Dense(2, activity_regularizer='l2') def call(self, x, training=None): return self.dense(x) """ raise RuntimeError( 'You are using a layer with `activity_regularizer` in a control flow ' 'branch, e.g.:\n{bad_example}\nThis is currently not supported. ' 'Please move your call to the layer with `activity_regularizer` out ' 'of the control flow branch, e.g.:\n{correct_example}\n' 'You can also resolve this by marking your outer model/layer dynamic' ' (eager-only) by passing `dynamic=True` to the layer constructor. ' 'Any kind of control flow is supported with dynamic layers. ' 'Note that using `dynamic=True` requires you to implement static ' 'shape inference in the `compute_output_shape(input_shape)` ' 'method.'.format( bad_example=bad_example, correct_example=correct_example)) if method == 'add_metric': bad_example = """ def call(self, inputs, training=None): if training: metric = compute_metric(inputs) self.add_metric(metric, name='my_metric', aggregation='mean') return inputs """ correct_example = """ def call(self, inputs, training=None): if training: metric = compute_metric(inputs) else: metric = 0. self.add_metric(metric, name='my_metric', aggregation='mean') return inputs """ elif method == 'add_loss': bad_example = """ def call(self, inputs, training=None): if training: loss = compute_loss(inputs) self.add_loss(loss) return inputs """ correct_example = """ def call(self, inputs, training=None): if training: loss = compute_loss(inputs) else: loss = 0. self.add_loss(loss) return inputs """ else: bad_example = """ def call(self, inputs, training=None): if training: self.add_update(self.w.assign_add(1)) return inputs """ correct_example = """ def call(self, inputs, training=None): if training: increment = 1 else: increment = 0 self.add_update(self.w.assign_add(increment)) return inputs """ raise RuntimeError( 'You are using the method `{method}` in a control flow branch ' 'in your layer, e.g.:\n{bad_example}\n' 'This is not currently supported. ' 'Please move your call to {method} out of the control flow branch, ' 'e.g.:\n{correct_example}\n' 'You can also resolve this by marking your layer ' 'as dynamic (eager-only) by passing ' '`dynamic=True` to the layer constructor. ' 'Any kind of control flow is supported with dynamic layers. ' 'Note that using `dynamic=True` requires you ' 'to implement static shape inference ' 'in the `compute_output_shape(input_shape)` method.'.format( method=method, bad_example=bad_example, correct_example=correct_example)) def mark_as_return(outputs, acd): """Marks `outputs` as the return values for automatic control deps.""" def _mark_as_return(tensor): """Marks `tensor` as the return value for automatic control deps.""" if not tensor_util.is_tensor(tensor): return tensor # pylint: disable=protected-access return_tensor = acd.mark_as_return(tensor) if getattr(tensor, '_keras_mask', None) is not None: return_tensor._keras_mask = acd.mark_as_return(tensor._keras_mask) else: return_tensor._keras_mask = None # Handle TensorFlow Probability attached metadata. # TODO(b/132076537): Remove this once TFP uses `CompositeTensor`. if getattr(tensor, '_tfp_distribution', None) is not None: return_tensor._tfp_distribution = tensor._tfp_distribution return return_tensor # pylint: enable=protected-access return nest.map_structure(_mark_as_return, outputs) def default(method): """Decorates a method to detect overrides in subclasses.""" method._is_default = True # pylint: disable=protected-access return method V2_DTYPE_BEHAVIOR = None # These two functions are not exported because we plan on removing them in the # future. def enable_v2_dtype_behavior(): """Enable the V2 dtype behavior for Keras layers. By default, the V2 dtype behavior is enabled in TensorFlow 2. When enabled, the dtype of Keras layers defaults to floatx (which is typically float32) instead of None. In addition, layers will automatically cast floating-point inputs to the layer's dtype. For example, once enabled, the following block will run a Conv2D layer in float32: ```python x = tf.ones((4, 4, 4, 4), dtype='float64') layer = tf.keras.layers.Conv2D(filters=4, kernel_size=2) print(layer.dtype) # Float32 when enabled. None when disabled. # When enabled, will cast inputs to the layer's dtype, which is float32. When # disabled, will do no casting, so the layer is done in float64. y = layer(x) ``` A layer author can opt-out their layer from the automatic input casting by passing `autocast=False` to the base Layer's constructor. This disables the autocasting part of the V2 behavior for that layer, but not the defaulting to floatx part of the V2 behavior. When a global `tf.keras.mixed_precision.experimental.Policy` is set, the layer's dtype will default to the global policy instead of floatx. Layers will automatically cast inputs to the policy's compute_dtype. """ global V2_DTYPE_BEHAVIOR V2_DTYPE_BEHAVIOR = True def disable_v2_dtype_behavior(): """Disables the V2 dtype behavior for Keras layers. See `enable_v2_dtype_behavior`. This function will be removed in the future. """ global V2_DTYPE_BEHAVIOR V2_DTYPE_BEHAVIOR = False def v2_dtype_behavior_enabled(): """Returns True if the V2 dtype behavior is enabled.""" if V2_DTYPE_BEHAVIOR is None: return tf2.enabled() return V2_DTYPE_BEHAVIOR class TrackableWeightHandler(object): """Keras wrapper for handling tracking.Trackable object saving and restoring. This class handles Trackables in both V1 and V2 modes, ensuring that they can be saved and restored with the correct data and without adding additional ops on every save. Attributes: trackable: The trackable to wrap. num_tensors: The number of tensors that this trackable requires for saving. """ def __init__(self, trackable): if not isinstance(trackable, tracking.Trackable): raise ValueError('%s is not a Trackable object.' % (trackable,)) self._trackable = trackable # TODO(b/141682913): Figure out why this is private and fix it. saveables = trackable._gather_saveables_for_checkpoint().values() # pylint: disable=protected-access if len(saveables) != 1: raise ValueError('Only Trackables with one Saveable are supported.') saveable = list(saveables)[0] if ops.executing_eagerly_outside_functions(): # If we're in eager mode, we need to defer calling the Trackable's # saveable() callable until data export time. # However, it is safe to call the saveable as many times as we want, so # we will call it now to figure out how many tensors this Trackable will # produce. self._saveable = saveable self._num_tensors = len(self._saveable().specs) self._setter = lambda weights: self._saveable().restore(weights, None) self._getter = lambda: [spec.tensor for spec in self._saveable().specs] else: # If we're in Graph mode, we need to evaluate the Saveable only once and # cache the resulting restore graph. Failing to do this will result in # new assignment ops being added to the graph each time set_weights() is # called. self._placeholder_tensors = [] self._saveable = saveable() self._num_tensors = len(self._saveable.specs) for spec in self._saveable.specs: tensor = spec.tensor self._placeholder_tensors.append( array_ops.placeholder(tensor.dtype, tensor.shape)) self._assign_op = self._saveable.restore(self._placeholder_tensors, None) self._setter = self._set_weights_v1 self._getter = lambda: [spec.tensor for spec in self._saveable.specs] @property def num_tensors(self): return self._num_tensors def set_weights(self, weights): if len(weights) != self._num_tensors: raise ValueError( ('Weight handler for trackable %s received the wrong number of ' + 'weights: expected %s, got %s.') % (self._trackable, self._num_tensors, len(weights))) self._setter(weights) def get_tensors(self): return self._getter() def _set_weights_v1(self, weights): feed_dict = {} for idx, tensor in enumerate(weights): feed_dict[self._placeholder_tensors[idx]] = tensor backend.get_session().run(self._assign_op, feed_dict) # TODO(kathywu): This is a temporary hack. When a network of layers is revived # from SavedModel, only the top-level layer will have losses. This causes issues # in eager mode because the child layers may have graph losses # (thus model.losses returns a mix of Eager and graph tensors). To fix this, # whenever eager losses are added to one layer, add eager losses to all # child layers. This causes `.losses` to only return eager losses. REVIVED_LOSS_PLACEHOLDER = ( 'This layer\'s losses have been added to the parent layer.')
{ "content_hash": "e2ae5a6b203ba1a5ddf7ac348b0d7972", "timestamp": "", "source": "github", "line_count": 781, "max_line_length": 106, "avg_line_length": 37.26888604353393, "alnum_prop": 0.6844401690315044, "repo_name": "jhseu/tensorflow", "id": "fc5c851426ca40f436dd5fcb70ff7d6a1efcdbe9", "size": "29796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow/python/keras/engine/base_layer_utils.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "27480" }, { "name": "Batchfile", "bytes": "49527" }, { "name": "C", "bytes": "875455" }, { "name": "C#", "bytes": "8562" }, { "name": "C++", "bytes": "80051513" }, { "name": "CMake", "bytes": "6500" }, { "name": "Dockerfile", "bytes": "112748" }, { "name": "Go", "bytes": "1853641" }, { "name": "HTML", "bytes": "4686483" }, { "name": "Java", "bytes": "961600" }, { "name": "Jupyter Notebook", "bytes": "549457" }, { "name": "LLVM", "bytes": "6536" }, { "name": "MLIR", "bytes": "1729057" }, { "name": "Makefile", "bytes": "62498" }, { "name": "Objective-C", "bytes": "116558" }, { "name": "Objective-C++", "bytes": "304661" }, { "name": "PHP", "bytes": "4236" }, { "name": "Pascal", "bytes": "318" }, { "name": "Pawn", "bytes": "19515" }, { "name": "Perl", "bytes": "7536" }, { "name": "Python", "bytes": "36791185" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Roff", "bytes": "2705" }, { "name": "Ruby", "bytes": "7464" }, { "name": "SWIG", "bytes": "56741" }, { "name": "Shell", "bytes": "685877" }, { "name": "Smarty", "bytes": "35147" }, { "name": "Starlark", "bytes": "3504187" }, { "name": "Swift", "bytes": "62814" }, { "name": "Vim Snippet", "bytes": "58" } ], "symlink_target": "" }
import os from flask import Flask, render_template, request from BSParser import wiki app = Flask(__name__) @app.route('/', methods=["GET", "POST"]) def login_page(): try: if request.method == "POST": page = request.form['page'] return wiki(page) else: error = "Invalid credentials. Try Again." return render_template("index.html") except: return render_template("index.html") if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
{ "content_hash": "c20f68555cc728c20caee8e1edc0b70e", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 53, "avg_line_length": 25.818181818181817, "alnum_prop": 0.5809859154929577, "repo_name": "jack-cast/HackPrinceton", "id": "f47fcaaf5296bf474b28242615c0221443aa0e88", "size": "568", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "127" }, { "name": "Python", "bytes": "3895" } ], "symlink_target": "" }
""" Get a notification ``email`` flavour """ # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import when, then from ipteller.mailer import Mailer @when('I want to send an email with the subject "{subject}" and body "{body}"') def step_impl(context, subject, body): context.subject = subject context.body = body context.message = Mailer.message({'user': 'test', 'pwd': 'pwd', 'subject': subject, 'body': body}) @then('I expect to get it with a proper format') def step_impl(context): assert context.subject in context.message assert context.body in context.message
{ "content_hash": "b0b1821b2b10ac7478d431381db2841d", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 102, "avg_line_length": 31.91304347826087, "alnum_prop": 0.5449591280653951, "repo_name": "Saphyel/ipteller", "id": "8be5d82bebe4502a924e2615e0864175ba1440ea", "size": "734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "features/steps/step_mailer.py", "mode": "33188", "license": "mit", "language": [ { "name": "Gherkin", "bytes": "535" }, { "name": "Python", "bytes": "5608" }, { "name": "Shell", "bytes": "362" } ], "symlink_target": "" }
from __future__ import with_statement import os from os import getcwd, chdir from os.path import join, exists, dirname from warnings import warn import atexit from logging import getLogger from threading import Lock logger = getLogger('pystacia.api') def dll_template(osname, abi): if osname == 'macos': return 'lib{name}.{abi}.dylib' if abi else 'lib{name}.dylib' elif osname == 'linux': return 'lib{name}.so.{abi}' if abi else 'lib{name}.so' elif osname == 'windows': return 'lib{name}-{abi}.dll' if abi else 'lib{name}.dll' return None def process_depends(depends_path, path, osname, factory): depends = open(depends_path) for line in depends: depname, depabi = line.split() template = formattable(dll_template(osname, depabi)) dll_path = join(path, template.format(name=depname, abi=depabi)) try: factory(dll_path) except: pass depends.close() def find_in_path(path, name, abis, osname, factory): depends_path = join(path, 'depends.txt') if exists(depends_path): process_depends(depends_path, path, osname, factory) for abi in abis: template = dll_template(osname, abi) if not template: continue template = formattable(template) dll_path = join(path, template.format(name=name, abi=abi)) logger.debug('Trying: ' + dll_path) if exists(dll_path): logger.debug('Found: ' + dll_path) if osname == 'windows': old_path = getcwd() chdir(path) try: factory(dll_path) except: from sys import exc_info msg = formattable('Caught exception while loading ' '{0}: {1}. Rolling back') logger.debug(msg.format(dll_path, exc_info()[1])) if osname == 'windows': chdir(old_path) else: if osname == 'windows': chdir(old_path) return dll_path def gather_paths(environ): paths = [] path = registry.get('library_path', environ.get('PYSTACIA_LIBRARY_PATH')) if path: paths.append(path) if not registry.get('skip_package', environ.get('PYSTACIA_SKIP_PACKAGE')): import pystacia path = dirname(pystacia.__file__) paths.append(join(path, 'cdll')) if not registry.get('skip_virtual_env', environ.get('PYSTACIA_SKIP_VIRTUAL_ENV')): try: path = environ['VIRTUAL_ENV'] except KeyError: pass else: paths.append(join(path, 'lib')) paths.append(join(path, 'dll')) if not registry.get('skip_cwd', environ.get('PYSTACIA_SKIP_CWD')): paths.append(getcwd()) return paths def find_library(name, abis, environ=None, osname=None, factory=None): logger.debug('Trying to find ImageMagick...') if not environ: environ = os.environ if not factory: factory = CDLL if not osname: osname = get_osname() paths = gather_paths(environ) logger.debug('Following paths will be searched: ' + ';'.join(paths)) for path in paths: if not exists(path): logger.debug('Path does not exist: ' + path) continue dll_path = find_in_path(path, name, abis, osname, factory) if dll_path: return dll_path # still nothing? let ctypes figure it out if not registry.get('skip_system', environ.get('PYSTACIA_SKIP_SYSTEM')): return ctypes_find_library(name) return None class library_path_transaction: def __init__(self, path): self.path = path def begin(self): self.old_path = getcwd() chdir(self.path) return self def commit(self): chdir(self.old_path) return self def rollback(self): chdir(self.old_path) __lock = Lock() def init_dll(dll): def shutdown(): logger.debug('Cleaning up traced instances') _cleanup() c_call(None, 'terminus') if jython: from java.lang import System # @UnresolvedImport System.exit(0) logger.debug('Critical section - init MagickWand') with __lock: if not dll.__inited: c_call(None, 'genesis', __init=False) logger.debug('Registering atexit handler') atexit.register(shutdown) dll.__inited = True version = magick.get_version() if version < min_version: msg = formattable('Unsupported version of MagickWand {0}') warn(msg.format(version)) def get_dll(init=True, environ=None, isolated=False): """Find ImageMagick DLL and initialize it. Searches available paths with :func:`find_library` and then fallbacks to standard :func:`ctypes.util.find_liblrary`. Loads the DLL into memory, initializes it and warns if it has unsupported API and ABI versions. """ if not hasattr(get_dll, '__dll') or isolated: logger.debug('Critical section - load MagickWand') with __lock: if not hasattr(get_dll, '__dll') or isolated: if not environ: environ = os.environ path = find_library(name, abis, environ=environ) if not path: msg = 'Could not find or load MagickWand' raise PystaciaException(msg) msg = formattable('Loading MagickWand from {0}') logger.debug(msg.format(path)) dll = CDLL(path) if not isolated: get_dll.__dll = dll get_dll.__dll.__inited = False else: return dll dll = get_dll.__dll if init and not dll.__inited: init_dll(dll) return dll from pystacia import registry from pystacia.util import get_osname, PystaciaException from pystacia.compat import formattable, jython from pystacia.common import _cleanup from pystacia import magick from pystacia.api.func import c_call from pystacia.api.compat import CDLL, find_library as ctypes_find_library min_version = (6, 5, 9, 0) name = 'MagickWand' abis = (5, 4, 3, None)
{ "content_hash": "1e57f7b70bfd5be4750bce8fc8aabd3a", "timestamp": "", "source": "github", "line_count": 238, "max_line_length": 78, "avg_line_length": 26.95798319327731, "alnum_prop": 0.5743453865336658, "repo_name": "squeaky-pl/pystacia", "id": "dca33982ff8934badf09f13de4dde70d5dcd15e9", "size": "6643", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pystacia/api/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "268831" }, { "name": "Shell", "bytes": "5109" } ], "symlink_target": "" }
from __future__ import print_function import argparse import collections import os import shutil import subprocess import sys import tempfile from oslo_utils import fileutils import os_client_config import pkg_resources as pkg import six import yaml from sahara_tests.scenario import utils from sahara_tests.scenario import validation from sahara_tests import version def set_defaults(config): # set up credentials config['credentials'] = config.get('credentials', {}) creds = config['credentials'] creds.setdefault('sahara_service_type', 'data-processing') creds['sahara_url'] = creds.get('sahara_url', None) creds['ssl_verify'] = creds.get('ssl_verify', False) creds['ssl_cert'] = creds.get('ssl_cert', None) # set up network config['network'] = config.get('network', {}) net = config['network'] net['private_network'] = net.get('private_network', 'private') net['auto_assignment_floating_ip'] = net.get('auto_assignment_floating_ip', False) net['public_network'] = net.get('public_network', '') default_scenario = ['run_jobs', 'scale', 'run_jobs'] # set up tests parameters for testcase in config['clusters']: testcase['class_name'] = "".join([ testcase['plugin_name'], testcase['plugin_version'].replace('.', '_')]) testcase['retain_resources'] = testcase.get('retain_resources', False) testcase['scenario'] = testcase.get('scenario', default_scenario) if isinstance(testcase.get('edp_jobs_flow'), six.string_types): testcase['edp_jobs_flow'] = [testcase['edp_jobs_flow']] edp_jobs_flow = [] for edp_flow in testcase.get('edp_jobs_flow', []): edp_jobs_flow.extend(config.get('edp_jobs_flow', {}).get(edp_flow)) testcase['edp_jobs_flow'] = edp_jobs_flow def recursive_walk(directory): list_of_files = [] for file in os.listdir(directory): path = os.path.join(directory, file) if os.path.isfile(path): list_of_files.append(path) else: list_of_files += recursive_walk(path) return list_of_files def valid_count(value): try: ivalue = int(value) if ivalue <= 0: raise ValueError except ValueError: raise argparse.ArgumentTypeError("%s is an invalid value of count. " "Value must be int and > 0. " % value) return ivalue def parse_args(array): args = collections.OrderedDict() for pair in array: arg_dict = pair.split(':') if len(arg_dict) < 2: return args args[arg_dict[0]] = "\'%s\'" % arg_dict[1] return args def get_base_parser(): parser = argparse.ArgumentParser(description="Scenario tests runner.") parser.add_argument('scenario_arguments', help="Path to scenario files", nargs='*', default=[]) parser.add_argument('--variable_file', '-V', default='', nargs='?', help='Path to the file with template variables') parser.add_argument('--verbose', default=False, action='store_true', help='Increase output verbosity') parser.add_argument('--validate', default=False, action='store_true', help='Validate yaml-files, tests will not be runned') parser.add_argument('--args', default='', nargs='+', help='Pairs of arguments key:value') parser.add_argument('--plugin', '-p', default=None, nargs='?', help='Specify plugin name') parser.add_argument('--plugin_version', '-v', default=None, nargs='?', help='Specify plugin version') parser.add_argument('--release', '-r', default=None, nargs='?', help='Specify Sahara release') parser.add_argument('--report', default=False, action='store_true', help='Write results of test to file') parser.add_argument('--feature', '-f', default=[], action='append', help='Set of features to enable') parser.add_argument('--count', default=1, nargs='?', type=valid_count, help='Specify count of runs current cases.') parser.add_argument('--v2', '-2', default=False, action='store_true', help='Use APIv2') return parser def get_scenario_files(scenario_arguments): files = [] for scenario_argument in scenario_arguments: if os.path.isdir(scenario_argument): files += recursive_walk(scenario_argument) if os.path.isfile(scenario_argument): files.append(scenario_argument) return files def main(): # parse args cloud_config = os_client_config.OpenStackConfig() parser = get_base_parser() cloud_config.register_argparse_arguments(parser, sys.argv) args = parser.parse_args() scenario_arguments = args.scenario_arguments variable_file = args.variable_file verbose_run = args.verbose scenario_args = parse_args(args.args) plugin = args.plugin version = args.plugin_version release = args.release report = args.report features = args.feature count = args.count use_api_v2 = args.v2 auth_values = utils.get_auth_values(cloud_config, args) scenario_arguments = utils.get_default_templates(plugin, version, release, scenario_arguments, features) files = get_scenario_files(scenario_arguments) template_variables = utils.get_templates_variables(files, variable_file, verbose_run, scenario_args, auth_values) params_for_login = {'credentials': auth_values} config = utils.generate_config(files, template_variables, params_for_login, verbose_run, features) # validate config validation.validate(config) if args.validate: return set_defaults(config) credentials = config['credentials'] network = config['network'] testcases = config['clusters'] for case in range(count - 1): testcases.extend(config['clusters']) test_dir_path = utils.create_testcase_file(testcases, credentials, network, report, use_api_v2=use_api_v2) # run tests concurrency = config.get('concurrency') testr_runner_exit_code = utils.run_tests(concurrency, test_dir_path) sys.exit(testr_runner_exit_code) if __name__ == '__main__': main()
{ "content_hash": "9230d49c24c2f78b71f498d29a07bd30", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 79, "avg_line_length": 36.475935828877006, "alnum_prop": 0.5874505204515467, "repo_name": "openstack/sahara-scenario", "id": "a9ffa745e17a8bc3ca08658a88ca784192562ebb", "size": "7427", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sahara_tests/scenario/runner.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3609" }, { "name": "Mako", "bytes": "52267" }, { "name": "PigLatin", "bytes": "792" }, { "name": "Python", "bytes": "128069" }, { "name": "Shell", "bytes": "47" } ], "symlink_target": "" }