├── tests ├── __init__.py ├── context.py └── test_person.py ├── requirements.txt ├── pyge ├── __init__.py ├── citydb.py ├── person.py ├── persondb.py └── __main__.py ├── jazz.csv ├── setup.py ├── .gitignore ├── README.md └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | coverage==4.5.4 2 | -------------------------------------------------------------------------------- /pyge/__init__.py: -------------------------------------------------------------------------------- 1 | from .citydb import load_cities 2 | from .citydb import lookup_city 3 | from .person import Person 4 | -------------------------------------------------------------------------------- /tests/context.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) 5 | 6 | import pyge 7 | -------------------------------------------------------------------------------- /pyge/citydb.py: -------------------------------------------------------------------------------- 1 | import csv 2 | 3 | DB = {} 4 | 5 | 6 | def load_cities(path): 7 | global DB 8 | 9 | with open(path) as f: 10 | reader = csv.reader(f) 11 | 12 | for row in reader: 13 | DB[f'{row[0].upper()}, {row[1]}'] = [float(n) for n in row[2:]] 14 | 15 | 16 | def lookup_city(city): 17 | global DB 18 | 19 | if len(DB) == 0: 20 | raise Exception('City database is not loaded. Call load_db') 21 | 22 | return DB[city.upper()] 23 | -------------------------------------------------------------------------------- /jazz.csv: -------------------------------------------------------------------------------- 1 | Miles Davis, 05/26/1926, M, "Alton, IL" 2 | Charlie Parker, 08/29/1920, M, "Kansas City, KS" 3 | John Coltrane, 09/23/1926, M, "Hamlet, NC" 4 | Herbie Hancock, 04/12/1940, M, "Chicago, IL" 5 | Louis Armstrong, 08/04/1901, M, "New Orleans, LA" 6 | Dizzy Gillespie, 10/21/1917, M, "Cheraw, SC" 7 | Duke Ellington, 04/29/1899, M, "Washington, DC" 8 | Bill Evans, 08/16/1929, M, "Plainfield, NJ" 9 | Billie Holiday, 04/07/1915, F, "Philadelphia, PA" 10 | Ella Fitzgerald, 04/25/1917, F, "Newport News, VA" 11 | Sarah Vaughan, 03/27/1924, F, "Newark, NJ" 12 | Nina Simone, 02/21/1933, F, "Tryon, NC" -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from setuptools import setup 4 | 5 | 6 | with open('README.md') as f: 7 | readme = f.read() 8 | 9 | setup( 10 | name='pyge', 11 | version='1.0.2', 12 | description='Python Gift Exchange Picker', 13 | long_description_content_type='text/markdown', 14 | long_description=readme, 15 | author='Seth Black', 16 | author_email='sblack@sethserver.com', 17 | url='https://github.com/sethblack/python-gift-exchange', 18 | license='Apache Software License', 19 | packages=['pyge'], 20 | keywords=['ai', 'unsupervised learning', 'random', 'artificial intelligence', 'secret santa', 'gift exchange',], 21 | package_data={'pyge': ['uscities.csv',]}, 22 | include_package_data=True, 23 | entry_points={ 24 | 'console_scripts': [ 25 | 'pyge=pyge.__main__:main', 26 | ], 27 | }, 28 | classifiers=[ 29 | 'License :: OSI Approved :: Apache Software License', 30 | 'Environment :: Console', 31 | 'Development Status :: 5 - Production/Stable', 32 | 'Programming Language :: Python', 33 | 'Programming Language :: Python :: 3', 34 | 'Programming Language :: Python :: 3.6', 35 | 'Programming Language :: Python :: 3.7', 36 | 'Programming Language :: Python :: 3.8', 37 | 'Programming Language :: Python :: Implementation :: CPython', 38 | 'Programming Language :: Python :: Implementation :: PyPy' 39 | ], 40 | zip_safe=False, 41 | ) 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | venv3/ 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # pyenv 79 | .python-version 80 | 81 | # celery beat schedule file 82 | celerybeat-schedule 83 | 84 | # SageMath parsed files 85 | *.sage.py 86 | 87 | # Environments 88 | .env 89 | .venv 90 | env/ 91 | venv/ 92 | ENV/ 93 | env.bak/ 94 | venv.bak/ 95 | 96 | # Spyder project settings 97 | .spyderproject 98 | .spyproject 99 | 100 | # Rope project settings 101 | .ropeproject 102 | 103 | # mkdocs documentation 104 | /site 105 | 106 | # mypy 107 | .mypy_cache/ 108 | -------------------------------------------------------------------------------- /pyge/person.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | from datetime import datetime 4 | from .citydb import lookup_city 5 | 6 | 7 | SEX_MAPPING = {'M': 0., 'F': 1., 'N': .5,} 8 | 9 | 10 | class Person(): 11 | def __init__(self, name, dob, sex, city_state, exchange_history=None): 12 | self.name = name 13 | self.dob = datetime.strptime(dob, '%m/%d/%Y') 14 | self.sex = sex 15 | self.lat_lng = lookup_city(city_state) 16 | self.exchange_history = exchange_history or list() 17 | 18 | def add_history(self, other): 19 | self.exchange_history.append(hash(other)) 20 | 21 | def has_history(self, other): 22 | return hash(other) in self.exchange_history 23 | 24 | def vector(self): 25 | age_point = self.age_in_days / 43830. # C = 43830 or approx 120 years 26 | sex_point = SEX_MAPPING[self.sex] 27 | 28 | return (age_point, sex_point, self.lat_lng[0], self.lat_lng[1]) 29 | 30 | def euclidean_distance(self, other): 31 | x_vector = self.vector() 32 | y_vector = other.vector() 33 | 34 | return sum([(x - y) ** 2 for x, y in zip(x_vector, y_vector)]) ** .5 35 | 36 | def l1_distance(self, other): 37 | x_vector = self.vector() 38 | y_vector = other.vector() 39 | 40 | return sum([abs(x - y) for x, y in zip(x_vector, y_vector)]) 41 | 42 | def coefficient(self, other): 43 | if self.has_history(other): 44 | return 0. 45 | 46 | return 1000. 47 | 48 | @property 49 | def age_in_days(self): 50 | return (datetime.now() - self.dob).days 51 | 52 | def __str__(self): 53 | return f'{self.name}: {self.__hash__()}' 54 | 55 | def __hash__(self): 56 | return int(hashlib.md5( 57 | f'{self.name}:{self.dob}:{self.sex}:{self.lat_lng}'.encode('utf-8') 58 | ).hexdigest()[:8], 16) 59 | 60 | def __eq__(self, other): 61 | return type(self) == type(other) and self.__hash__() == other.__hash__() 62 | -------------------------------------------------------------------------------- /pyge/persondb.py: -------------------------------------------------------------------------------- 1 | from .person import Person 2 | 3 | import collections 4 | import time 5 | import csv 6 | import os 7 | import struct 8 | import sys 9 | 10 | 11 | def load_people(path, history_length=3): 12 | people = [] 13 | 14 | history = load_history(path, history_length=3) 15 | 16 | with open(path) as f: 17 | reader = csv.reader(f, skipinitialspace=True) 18 | 19 | for row in reader: 20 | if len(row) != 4: 21 | print(f"{row} has incorrect format: expecting name, dob, sex, city and state.", file=sys.stderr) 22 | continue 23 | 24 | name, dob, sex, city_state = row 25 | person = Person(name, dob, sex, city_state) 26 | person.exchange_history = history.get(hash(person), []) 27 | 28 | people.append(person) 29 | 30 | return people 31 | 32 | 33 | def load_history(path, history_length=3): 34 | file_name, file_extension = os.path.splitext(path) 35 | 36 | history_file = f'{file_name}-history.bin' 37 | history_cycles = collections.defaultdict(list) 38 | 39 | try: 40 | with open(history_file, 'rb') as f: 41 | p = f.read(24) 42 | 43 | while p: 44 | cycle, person_a, person_b = struct.unpack('QQQ', p) 45 | 46 | history_cycles[cycle].append((person_a, person_b)) 47 | 48 | p = f.read(24) 49 | except FileNotFoundError: 50 | return {} 51 | 52 | history = collections.defaultdict(list) 53 | 54 | for cycle_no in sorted(history_cycles.keys())[(history_length * -1):]: 55 | for pairing in history_cycles[cycle_no]: 56 | history[pairing[0]].append(pairing[1]) 57 | 58 | return dict(history) 59 | 60 | 61 | def save_history(path, pairings): 62 | file_name, file_extension = os.path.splitext(path) 63 | 64 | history_file = f'{file_name}-history.bin' 65 | 66 | cycle = int(time.time()) 67 | 68 | with open(history_file, 'a+b') as f: 69 | for (a, b) in pairings: 70 | f.write(struct.pack('QQQ', cycle, hash(a), hash(b))) 71 | -------------------------------------------------------------------------------- /pyge/__main__.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import inspect 3 | import pyge 4 | import os 5 | import random 6 | 7 | from .citydb import load_cities 8 | from .persondb import load_people 9 | from .persondb import save_history, load_history 10 | 11 | def main(): 12 | arg_parser = argparse.ArgumentParser(description='Generates a list of people pairings for a holiday gift exchange.') 13 | 14 | arg_parser.add_argument('file', help='path to the csv containing a list of people who want to be part of the celebration') 15 | arg_parser.add_argument( 16 | '-s', '--save-history', 17 | help='save a history file of matches', 18 | dest='save_history', 19 | action='store_true' 20 | ) 21 | arg_parser.add_argument( 22 | '-n', '--no-history', 23 | help='do not save a history file of matches', 24 | dest='save_history', 25 | action='store_false' 26 | ) 27 | arg_parser.add_argument( 28 | '-c', '--citydb', 29 | help='path to city csv for distance calculations', 30 | default=None, 31 | metavar='citydb', 32 | dest='citydb' 33 | ) 34 | arg_parser.add_argument( 35 | '-l', '--history-length', 36 | help='number of cycles before people can be paired again', 37 | default=3, 38 | type=int, 39 | metavar='historylength', 40 | dest='history_length' 41 | ) 42 | 43 | arg_parser.set_defaults(save_history=True) 44 | 45 | args = arg_parser.parse_args() 46 | 47 | if args.citydb: 48 | load_cities(args.citydb) 49 | else: 50 | module_path = os.path.dirname(inspect.getfile(pyge)) 51 | load_cities(os.path.join(module_path, 'uscities.csv')) 52 | 53 | people_static = load_people(args.file, args.history_length) 54 | people_a = list(people_static) 55 | people_b = list(people_static) 56 | 57 | pairs = [] 58 | 59 | while len(people_a) > 0: 60 | gifter = random.choice(people_a) 61 | 62 | weights = [(p, gifter.euclidean_distance(p), gifter.coefficient(p)) for p in people_b] 63 | weighted_list = [] 64 | 65 | for w in weights: 66 | weighted_list.extend([w[0]] * int(w[1] * w[2])) 67 | 68 | if len(weighted_list) == 0: 69 | if len(pairs) == 0: 70 | raise Exception('Could not match set.') 71 | 72 | (prev_a, prev_b) = pairs.pop() 73 | 74 | people_a.append(prev_a) 75 | people_b.append(prev_b) 76 | 77 | continue 78 | 79 | giftee = random.choice(weighted_list) 80 | 81 | people_a.remove(gifter) 82 | people_b.remove(giftee) 83 | 84 | pairs.append((gifter, giftee)) 85 | 86 | for (gifter, giftee) in pairs: 87 | print(f"{gifter.name}, {giftee.name}") 88 | 89 | if args.save_history: 90 | save_history(args.file, pairs) 91 | 92 | 93 | if __name__ == '__main__': 94 | main() 95 | -------------------------------------------------------------------------------- /tests/test_person.py: -------------------------------------------------------------------------------- 1 | from .context import pyge 2 | 3 | from unittest import TestCase 4 | 5 | import datetime 6 | 7 | class PersonTests(TestCase): 8 | def setUp(self): 9 | pyge.citydb.load_cities('pyge/uscities.csv') 10 | 11 | def test_init(self): 12 | person = pyge.person.Person('Miles Davis', '05/26/1926', 'M', 'Alton, IL') 13 | 14 | self.assertEqual(person.name, 'Miles Davis') 15 | self.assertEqual(person.dob, datetime.datetime(1926, 5, 26)) 16 | self.assertEqual(person.sex, 'M') 17 | self.assertEqual(person.lat_lng, [0.216129444, -0.500846111]) 18 | 19 | self.assertEqual(f'{person}', 'Miles Davis: 4224271779') 20 | self.assertEqual(hash(person), 4224271779) 21 | self.assertEqual(person, person) 22 | 23 | def test_vector(self): 24 | today = datetime.datetime.now() 25 | yesterday = today - datetime.timedelta(days=3650) 26 | 27 | person = pyge.person.Person( 28 | 'Miles Davis', 29 | yesterday.strftime('%m/%d/%Y'), 30 | 'M', 31 | 'Alton, IL' 32 | ) 33 | 34 | self.assertEqual(person.vector(), (0.08327629477526809, 0.0, 0.216129444, -0.500846111)) 35 | 36 | def test_euclidean_distance(self): 37 | today = datetime.datetime.now() 38 | yesterday = today - datetime.timedelta(days=3650) 39 | 40 | person_x = pyge.person.Person('Miles Davis', yesterday.strftime('%m/%d/%Y'), 'M', 'Alton, IL') 41 | person_y = pyge.person.Person('Charlie Parker', yesterday.strftime('%m/%d/%Y'), 'M', 'Kansas City, KS') 42 | 43 | ed = person_x.euclidean_distance(person_y) 44 | 45 | self.assertEqual(ed, 0.025540398792728482) 46 | 47 | def test_l1_distance(self): 48 | today = datetime.datetime.now() 49 | yesterday = today - datetime.timedelta(days=3650) 50 | 51 | person_x = pyge.person.Person('Miles Davis', yesterday.strftime('%m/%d/%Y'), 'M', 'Alton, IL') 52 | person_y = pyge.person.Person('Charlie Parker', yesterday.strftime('%m/%d/%Y'), 'M', 'Kansas City, KS') 53 | 54 | ld = person_x.l1_distance(person_y) 55 | 56 | self.assertEqual(ld, 0.02673388900000004) 57 | 58 | def test_coefficient(self): 59 | person_x = pyge.person.Person('Miles Davis', '05/26/1926', 'M', 'Alton, IL') 60 | person_y = pyge.person.Person('Charlie Parker', '08/29/1920', 'M', 'Kansas City, KS') 61 | person_z = pyge.person.Person('John Coltrane', '09/23/1926', 'M', 'Hamlet, NC') 62 | 63 | person_x.add_history(person_y) 64 | person_y.add_history(person_z) 65 | 66 | self.assertTrue(person_x.has_history(person_y)) 67 | self.assertFalse(person_x.has_history(person_z)) 68 | 69 | c1 = person_x.coefficient(person_y) 70 | self.assertEqual(c1, 0.) 71 | 72 | c2 = person_y.coefficient(person_x) 73 | self.assertEqual(c1, 0.) 74 | 75 | c3 = person_x.coefficient(person_z) 76 | self.assertEqual(c3, 1000.) 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Gift Exchange Picker 2 | 3 | [![The Rest by taleas.com](https://www.taleascomic.com/static/images/comics/the-rest-of-my-presents.jpg "The Rest by taleas.com")](https://www.taleascomic.com/comics/the-rest-of-the-christmas-presents.html) 4 | 5 | My wife is in charge of our families' annual Secret Santa Gift Exchange. Because she, unfortunately, knows about my background in math and computer science her requirements have become more extreme. A hat containing folded pieces of paper with hand-written names is no longer sufficient. Python Gift Exchange Picker (pyge) is my third and best implementation of my wife's requirements: 6 | 7 | - It must match each person to a different person. 8 | - The match should not be in the same household. 9 | - The match should not be the same gender. 10 | - The match should not be in the same age group. 11 | - The match must not happen again for at least three years. 12 | 13 | To accomplish this, pyge imports a list of participants along with their feature sets and transforms each participant's feature set into numerical values. Each value is then vectorized and a pairwise euclidean distance between each participant is computed; this can be represented as either a graph or a matrix - I chose a matrix. The distances are then multiplied by a per-participant "qualifier" coefficient and the results are used to build a weighted distribution. The pairs of participants are then randomly matched using the weighted distribution until either all participants have been matched or no matches can be made. If no matches can be made and there are still participants pyge will backtrack until all participants can be successfully matched or it is discovered that it is impossible to match the given set of participants. 14 | 15 | If you're interested, you can read a more detailed description [here](https://www.sethserver.com/python/secret-santa-gift-exchange.html). 16 | 17 | ## Installation 18 | 19 | ```sh 20 | pip install pyge 21 | ``` 22 | 23 | ## Basic Usage 24 | 25 | Pyge has only one required argument: the path to a csv file containing the people who are participating in the gift exchange. An example csv file, [jazz.csv](https://github.com/sethblack/py-gift-exchange/blob/master/jazz.csv) has been provided. 26 | 27 | 28 | ```sh 29 | $ pyge /path/to/jazz.csv 30 | Herbie Hancock, Billie Holiday 31 | Ella Fitzgerald, Herbie Hancock 32 | Charlie Parker, Nina Simone 33 | Nina Simone, Bill Evans 34 | Miles Davis, Duke Ellington 35 | John Coltrane, Sarah Vaughan 36 | Sarah Vaughan, Louis Armstrong 37 | Louis Armstrong, Ella Fitzgerald 38 | Billie Holiday, Charlie Parker 39 | Duke Ellington, John Coltrane 40 | Dizzy Gillespie, Miles Davis 41 | Bill Evans, Dizzy Gillespie 42 | ``` 43 | 44 | ### Input CSV File Format 45 | 46 | ``` 47 | name, date of birth, sex, "city, state or province or territory" 48 | ``` 49 | 50 | Any column containing a comma should be quoted with double-quotes, for example, `"Austin, TX"`. 51 | 52 | The `Date of Birth` field is in `MM/DD/YYYY` format. 53 | 54 | `Sex` can be `M`, `F` or `N`. 55 | 56 | `City` by default only includes cities in the United States. See [Using Other Country Databases](https://github.com/sethblack/py-gift-exchange#using-other-country-databases) for more information on changing the country. 57 | 58 | ## Saving History 59 | 60 | Pyge saves a historical list of pairings which is used to ensure participants will not be paired for at a minimum of three exchanges. Saving history can be toggled with the `--save-history` and `--no-history` flags. The minimum number of exchanges can be modified with the `--history-length` argument. 61 | 62 | ## Using Other Country Databases 63 | 64 | You can pass a different city weight database file by using the `--citydb` argument. The city weight database is a csv file in the following format: 65 | 66 | ``` 67 | city, state or province or territory, normalized latitude, normalized longitude 68 | ``` 69 | 70 | Where normalized latitude and longitude are the values normalized between -1 and +1 (divided by 180). 71 | 72 | ## Full Usage 73 | 74 | ``` 75 | usage: pyge [-h] [-s] [-n] [-c citydb] [-l historylength] file 76 | 77 | Generates a list of people pairings for a holiday gift exchange. 78 | 79 | positional arguments: 80 | file path to the csv containing a list of people who want 81 | to be part of the celebration 82 | 83 | optional arguments: 84 | -h, --help show this help message and exit 85 | -s, --save-history save a history file of matches 86 | -n, --no-history do not save a history file of matches 87 | -c citydb, --citydb citydb 88 | path to city csv for distance calculations 89 | -l historylength, --history-length historylength 90 | number of cycles before people can be paired again 91 | ``` 92 | 93 | --- 94 | 95 | Cities database provided by [https://simplemaps.com/data/us-cities](https://simplemaps.com/data/us-cities). -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------