INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Replaces the used methods of globally-imported modules with obfuscated equivalents. Updates *tokens* in-place. *module* must be the name of the module we're currently obfuscating If *table* is provided, replacements for import methods will be attempted to be looked up there before generating a new un...
def obfuscate_global_import_methods(module, tokens, name_generator, table=None): """ Replaces the used methods of globally-imported modules with obfuscated equivalents. Updates *tokens* in-place. *module* must be the name of the module we're currently obfuscating If *table* is provided, replaceme...
Obfuscates *tokens* in-place. *options* is expected to be the options variable passed through from pyminifier.py. *module* must be the name of the module we're currently obfuscating If *name_generator* is provided it will be used to obtain replacement values for identifiers. If not, a new instance o...
def obfuscate(module, tokens, options, name_generator=None, table=None): """ Obfuscates *tokens* in-place. *options* is expected to be the options variable passed through from pyminifier.py. *module* must be the name of the module we're currently obfuscating If *name_generator* is provided it wil...
Removes comments from *tokens* which is expected to be a list equivalent of tokenize.generate_tokens() (so we can update in-place). .. note:: * If the comment makes up the whole line, the newline will also be removed (so you don't end up with lots of blank lines). * Preserves shebangs and enco...
def remove_comments(tokens): """ Removes comments from *tokens* which is expected to be a list equivalent of tokenize.generate_tokens() (so we can update in-place). .. note:: * If the comment makes up the whole line, the newline will also be removed (so you don't end up with lots of blank line...
Returns *source* minus comments and docstrings. .. note:: Uses Python's built-in tokenize module to great effect. Example:: def noop(): # This is a comment ''' Does nothing. ''' pass # Don't do anything Will become:: def noop(): ...
def remove_comments_and_docstrings(source): """ Returns *source* minus comments and docstrings. .. note:: Uses Python's built-in tokenize module to great effect. Example:: def noop(): # This is a comment ''' Does nothing. ''' pass # Don't do any...
Removes docstrings from *tokens* which is expected to be a list equivalent of `tokenize.generate_tokens()` (so we can update in-place).
def remove_docstrings(tokens): """ Removes docstrings from *tokens* which is expected to be a list equivalent of `tokenize.generate_tokens()` (so we can update in-place). """ prev_tok_type = None for index, tok in enumerate(tokens): token_type = tok[0] if token_type == tokenize.S...
Remove spaces between operators in *source* and returns the result. Example:: def foo(foo, bar, blah): test = "This is a %s" % foo Will become:: def foo(foo,bar,blah): test="This is a %s"%foo .. note:: Also removes trailing commas and joins disjointed st...
def reduce_operators(source): """ Remove spaces between operators in *source* and returns the result. Example:: def foo(foo, bar, blah): test = "This is a %s" % foo Will become:: def foo(foo,bar,blah): test="This is a %s"%foo .. note:: Also remov...
Finds and removes newlines in multiline matching pairs of characters in *source*. By default it joins parens () but it will join any two characters given via the *pair* variable. .. note:: Doesn't remove extraneous whitespace that ends up between the pair. Use `reduce_operators()` for...
def join_multiline_pairs(source, pair="()"): """ Finds and removes newlines in multiline matching pairs of characters in *source*. By default it joins parens () but it will join any two characters given via the *pair* variable. .. note:: Doesn't remove extraneous whitespace that ends ...
Minimizes indentation to save precious bytes. Optionally, *use_tabs* may be specified if you want to use tabulators (\t) instead of spaces. Example:: def foo(bar): test = "This is a test" Will become:: def foo(bar): test = "This is a test"
def dedent(source, use_tabs=False): """ Minimizes indentation to save precious bytes. Optionally, *use_tabs* may be specified if you want to use tabulators (\t) instead of spaces. Example:: def foo(bar): test = "This is a test" Will become:: def foo(bar): te...
Appends 'pass' to empty methods/functions (i.e. where there was nothing but a docstring before we removed it =). Example:: # Note: This triple-single-quote inside a triple-double-quote is also a # pyminifier self-test def myfunc(): '''This is just a placeholder function.'''...
def fix_empty_methods(source): """ Appends 'pass' to empty methods/functions (i.e. where there was nothing but a docstring before we removed it =). Example:: # Note: This triple-single-quote inside a triple-double-quote is also a # pyminifier self-test def myfunc(): ...
Removes blank lines from *source* and returns the result. Example: .. code-block:: python test = "foo" test2 = "bar" Will become: .. code-block:: python test = "foo" test2 = "bar"
def remove_blank_lines(source): """ Removes blank lines from *source* and returns the result. Example: .. code-block:: python test = "foo" test2 = "bar" Will become: .. code-block:: python test = "foo" test2 = "bar" """ io_obj = io.StringIO(source) ...
Performs minification on *tokens* according to the values in *options*
def minify(tokens, options): """ Performs minification on *tokens* according to the values in *options* """ # Remove comments remove_comments(tokens) # Remove docstrings remove_docstrings(tokens) result = token_utils.untokenize(tokens) # Minify our input script result = multiline...
Returns `True` if *obj* is iterable but *not* if *obj* is a string, bytes, or a bytearray.
def is_iterable(obj): """ Returns `True` if *obj* is iterable but *not* if *obj* is a string, bytes, or a bytearray. """ if isinstance(obj, (str, bytes, bytearray)): return False return isinstance(obj, Iterable)
Given an *options* object (from `optparse.OptionParser` or similar), performs minification and/or obfuscation on the given *files* (any iterable containing file paths) based on said *options*. All accepted options can be listed by running ``python __main__.py -h`` or examining the :py:func:`__init__.ma...
def pyminify(options, files): """ Given an *options* object (from `optparse.OptionParser` or similar), performs minification and/or obfuscation on the given *files* (any iterable containing file paths) based on said *options*. All accepted options can be listed by running ``python __main__.py -h`` ...
Sets up our command line options, prints the usage/help (if warranted), and runs :py:func:`pyminifier.pyminify` with the given command line options.
def main(): """ Sets up our command line options, prints the usage/help (if warranted), and runs :py:func:`pyminifier.pyminify` with the given command line options. """ usage = '%prog [options] "<input file>"' if '__main__.py' in sys.argv[0]: # python -m pyminifier usage = 'pyminifier [o...
Converts the output of tokenize.generate_tokens back into a human-readable string (that doesn't contain oddly-placed whitespace everywhere). .. note:: Unlike :meth:`tokenize.untokenize`, this function requires the 3rd and 4th items in each token tuple (though we can use lists *or* tuples).
def untokenize(tokens): """ Converts the output of tokenize.generate_tokens back into a human-readable string (that doesn't contain oddly-placed whitespace everywhere). .. note:: Unlike :meth:`tokenize.untokenize`, this function requires the 3rd and 4th items in each token tuple (thoug...
Tokenizes *source* and returns the tokens as a list of lists.
def listified_tokenizer(source): """Tokenizes *source* and returns the tokens as a list of lists.""" io_obj = io.StringIO(source) return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]
Iterates over *tokens* and returns a dictionary with function names as the keys and lists of keyword arguments as the values.
def enumerate_keyword_args(tokens): """ Iterates over *tokens* and returns a dictionary with function names as the keys and lists of keyword arguments as the values. """ keyword_args = {} inside_function = False for index, tok in enumerate(tokens): token_type = tok[0] token_s...
Iterates over *tokens* and returns a list of all imported modules. .. note:: This ignores imports using the 'as' and 'from' keywords.
def enumerate_imports(tokens): """ Iterates over *tokens* and returns a list of all imported modules. .. note:: This ignores imports using the 'as' and 'from' keywords. """ imported_modules = [] import_line = False from_import = False for index, tok in enumerate(tokens): token_t...
Returns a list of all globally imported modules (skips modules imported inside of classes, methods, or functions). Example:: >>> enumerate_global_modules(tokens) ['sys', 'os', 'tokenize', 're'] .. note:: Does not enumerate imports using the 'from' or 'as' keywords.
def enumerate_global_imports(tokens): """ Returns a list of all globally imported modules (skips modules imported inside of classes, methods, or functions). Example:: >>> enumerate_global_modules(tokens) ['sys', 'os', 'tokenize', 're'] .. note:: Does not enumerate imports usi...
Returns a dictionary of all dynamically imported modules (those inside of classes or functions) in the form of {<func or class name>: [<modules>]} Example: >>> enumerate_dynamic_modules(tokens) {'myfunc': ['zlib', 'base64']}
def enumerate_dynamic_imports(tokens): """ Returns a dictionary of all dynamically imported modules (those inside of classes or functions) in the form of {<func or class name>: [<modules>]} Example: >>> enumerate_dynamic_modules(tokens) {'myfunc': ['zlib', 'base64']} """ importe...
Returns a list of all object (not module) method calls in the given tokens. *modules* is expected to be a list of all global modules imported into the source code we're working on. For example: >>> enumerate_method_calls(tokens) ['re.compile', 'sys.argv', 'f.write']
def enumerate_method_calls(tokens, modules): """ Returns a list of all object (not module) method calls in the given tokens. *modules* is expected to be a list of all global modules imported into the source code we're working on. For example: >>> enumerate_method_calls(tokens) ['re...
Returns a list of all the builtins being used in *tokens*.
def enumerate_builtins(tokens): """ Returns a list of all the builtins being used in *tokens*. """ out = [] for index, tok in enumerate(tokens): token_type = tok[0] token_string = tok[1] if token_string in builtins: # Note: I need to test if print can be replaced ...
Returns a list of imported module methods (such as re.compile) inside *tokens*.
def enumerate_import_methods(tokens): """ Returns a list of imported module methods (such as re.compile) inside *tokens*. """ global_imports = enumerate_global_imports(tokens) out = [] for item in global_imports: for index, tok in enumerate(tokens): try: n...
Returns a list of modules inside *tokens* that are local to *path*. **Note:** Will recursively look inside *path* for said modules.
def enumerate_local_modules(tokens, path): """ Returns a list of modules inside *tokens* that are local to *path*. **Note:** Will recursively look inside *path* for said modules. """ # Have to get a list of all modules before we can do anything else modules = enumerate_imports(tokens) loca...
Returns the shebang string in *tokens* if it exists. None if not.
def get_shebang(tokens): """ Returns the shebang string in *tokens* if it exists. None if not. """ # This (short) loop preserves shebangs and encoding strings: for tok in tokens[0:4]: # Will always be in the first four tokens line = tok[4] # Save the first comment line if it starts ...
Returns 'source' as a bzip2-compressed, self-extracting python script. .. note:: This method uses up more space than the zip_pack method but it has the advantage in that the resulting .py file can still be imported into a python program.
def bz2_pack(source): """ Returns 'source' as a bzip2-compressed, self-extracting python script. .. note:: This method uses up more space than the zip_pack method but it has the advantage in that the resulting .py file can still be imported into a python program. """ import...
Appends *line* to the _beginning_ of the file at the given *path*. If *line* doesn't end in a newline one will be appended to the end of it.
def prepend(line, path): """ Appends *line* to the _beginning_ of the file at the given *path*. If *line* doesn't end in a newline one will be appended to the end of it. """ if isinstance(line, str): line = line.encode('utf-8') if not line.endswith(b'\n'): line += b'\n' temp...
Creates a zip archive containing the script at *filepath* along with all imported modules that are local to *filepath* as a self-extracting python script. A shebang will be appended to the beginning of the resulting zip archive which will allow it to If being run inside Python 3 and the `lzma` module ...
def zip_pack(filepath, options): """ Creates a zip archive containing the script at *filepath* along with all imported modules that are local to *filepath* as a self-extracting python script. A shebang will be appended to the beginning of the resulting zip archive which will allow it to If bei...
Registers Calendar class as country or region in IsoRegistry. Registered country must set class variables ``iso`` using this decorator. >>> from workalendar.core import Calendar >>> @iso_register('MC-MR') >>> class MyRegion(Calendar): >>> 'My Region' Region calendar is then retrievable fr...
def iso_register(iso_code): """ Registers Calendar class as country or region in IsoRegistry. Registered country must set class variables ``iso`` using this decorator. >>> from workalendar.core import Calendar >>> @iso_register('MC-MR') >>> class MyRegion(Calendar): >>> 'My Region' ...
Add Late Summer holiday (First Monday of September)
def get_variable_days(self, year): """ Add Late Summer holiday (First Monday of September) """ days = super(LateSummer, self).get_variable_days(year) days.append(( self.get_nth_weekday_in_month(year, 9, MON), "Late Summer Holiday" )) return...
Retrieves calendar class associated with given ``iso_code``. If calendar of subdivision is not registered (for subdivision like ISO codes, e.g. GB-ENG) returns calendar of containing region (e.g. United Kingdom for ISO code GB) if it's available. :rtype: Calendar
def get_calendar_class(self, iso_code): """ Retrieves calendar class associated with given ``iso_code``. If calendar of subdivision is not registered (for subdivision like ISO codes, e.g. GB-ENG) returns calendar of containing region (e.g. United Kingdom for ISO code GB)...
Returns subregion calendar classes for given region iso_code. >>> registry = IsoRegistry() >>> # assuming calendars registered are: DE, DE-HH, DE-BE >>> registry.get_subregions('DE') {'DE-HH': <class 'workalendar.europe.germany.Hamburg'>, 'DE-BE': <class 'workalendar.europe.germ...
def get_subregions(self, iso_code): """ Returns subregion calendar classes for given region iso_code. >>> registry = IsoRegistry() >>> # assuming calendars registered are: DE, DE-HH, DE-BE >>> registry.get_subregions('DE') {'DE-HH': <class 'workalendar.europe.germany.Ham...
Returns calendar classes for regions :param region_codes list of ISO codes for selected regions :param include_subregions boolean if subregions of selected regions should be included in result :rtype dict :return dict where keys are ISO codes strings and values are calen...
def items(self, region_codes, include_subregions=False): """ Returns calendar classes for regions :param region_codes list of ISO codes for selected regions :param include_subregions boolean if subregions of selected regions should be included in result :rtype dict ...
Return a "clean" date type. * keep a `date` unchanged * convert a datetime into a date, * convert any "duck date" type into a date using its `date()` method.
def cleaned_date(day, keep_datetime=False): """ Return a "clean" date type. * keep a `date` unchanged * convert a datetime into a date, * convert any "duck date" type into a date using its `date()` method. """ if not isinstance(day, (date, datetime)): raise UnsupportedDateType( ...
Return the fixed days according to the FIXED_HOLIDAYS class property
def get_fixed_holidays(self, year): """Return the fixed days according to the FIXED_HOLIDAYS class property """ days = [] for month, day, label in self.FIXED_HOLIDAYS: days.append((date(year, month, day), label)) return days
Computes holidays (non-working days) for a given year. Return a 2-item tuple, composed of the date and a label.
def holidays(self, year=None): """Computes holidays (non-working days) for a given year. Return a 2-item tuple, composed of the date and a label.""" if not year: year = date.today().year if year in self._holidays: return self._holidays[year] # Here we pr...
Return the label of the holiday, if the date is a holiday
def get_holiday_label(self, day): """Return the label of the holiday, if the date is a holiday""" day = cleaned_date(day) return {day: label for day, label in self.holidays(day.year) }.get(day)
Return a quick date index (set)
def holidays_set(self, year=None): "Return a quick date index (set)" return set([day for day, label in self.holidays(year)])
Return True if it's a working day. In addition to the regular holidays, you can add exceptions. By providing ``extra_working_days``, you'll state that these dates **are** working days. By providing ``extra_holidays``, you'll state that these dates **are** holidays, even if not ...
def is_working_day(self, day, extra_working_days=None, extra_holidays=None): """Return True if it's a working day. In addition to the regular holidays, you can add exceptions. By providing ``extra_working_days``, you'll state that these dates **are** working days....
Return True if it's an holiday. In addition to the regular holidays, you can add exceptions. By providing ``extra_holidays``, you'll state that these dates **are** holidays, even if not in the regular calendar holidays (or weekends).
def is_holiday(self, day, extra_holidays=None): """Return True if it's an holiday. In addition to the regular holidays, you can add exceptions. By providing ``extra_holidays``, you'll state that these dates **are** holidays, even if not in the regular calendar holidays (or weekends). ...
Add `delta` working days to the date. You can provide either a date or a datetime to this function that will output a ``date`` result. You can alter this behaviour using the ``keep_datetime`` option set to ``True``. the ``delta`` parameter might be positive or negative. If it's ...
def add_working_days(self, day, delta, extra_working_days=None, extra_holidays=None, keep_datetime=False): """Add `delta` working days to the date. You can provide either a date or a datetime to this function that will output a ``date`` result. ...
Substract `delta` working days to the date. This method is a shortcut / helper. Users may want to use either:: cal.add_working_days(my_date, -7) cal.sub_working_days(my_date, 7) The other parameters are to be used exactly as in the ``add_working_days`` method. ...
def sub_working_days(self, day, delta, extra_working_days=None, extra_holidays=None, keep_datetime=False): """ Substract `delta` working days to the date. This method is a shortcut / helper. Users may want to use either:: cal.add_wo...
Looks for the following working day, if not already a working day. **WARNING**: this function doesn't take into account the calendar holidays, only the days of the week and the weekend days parameters.
def find_following_working_day(self, day): """Looks for the following working day, if not already a working day. **WARNING**: this function doesn't take into account the calendar holidays, only the days of the week and the weekend days parameters. """ day = cleaned_date(day) ...
Get the nth weekday in a given month. e.g: >>> # the 1st monday in Jan 2013 >>> Calendar.get_nth_weekday_in_month(2013, 1, MON) datetime.date(2013, 1, 7) >>> # The 2nd monday in Jan 2013 >>> Calendar.get_nth_weekday_in_month(2013, 1, MON, 2) datetime.date(2013, 1, 14)
def get_nth_weekday_in_month(year, month, weekday, n=1, start=None): """Get the nth weekday in a given month. e.g: >>> # the 1st monday in Jan 2013 >>> Calendar.get_nth_weekday_in_month(2013, 1, MON) datetime.date(2013, 1, 7) >>> # The 2nd monday in Jan 2013 >>> Calendar...
Get the last weekday in a given month. e.g: >>> # the last monday in Jan 2013 >>> Calendar.get_last_weekday_in_month(2013, 1, MON) datetime.date(2013, 1, 28)
def get_last_weekday_in_month(year, month, weekday): """Get the last weekday in a given month. e.g: >>> # the last monday in Jan 2013 >>> Calendar.get_last_weekday_in_month(2013, 1, MON) datetime.date(2013, 1, 28) """ day = date(year, month, monthrange(year, month)[1]) ...
Get the first weekday after a given day. If the day is the same weekday, the same day will be returned. >>> # the first monday after Apr 1 2015 >>> Calendar.get_first_weekday_after(date(2015, 4, 1), MON) datetime.date(2015, 4, 6) >>> # the first tuesday after Apr 14 2015 ...
def get_first_weekday_after(day, weekday): """Get the first weekday after a given day. If the day is the same weekday, the same day will be returned. >>> # the first monday after Apr 1 2015 >>> Calendar.get_first_weekday_after(date(2015, 4, 1), MON) datetime.date(2015, 4, 6) ...
Return the number of working day between two given dates. The order of the dates provided doesn't matter. In the following example, there are 5 days, because of the week-end: >>> cal = WesternCalendar() # does not include easter monday >>> day1 = date(2018, 3, 29) >>> day2 = d...
def get_working_days_delta(self, start, end): """ Return the number of working day between two given dates. The order of the dates provided doesn't matter. In the following example, there are 5 days, because of the week-end: >>> cal = WesternCalendar() # does not include easte...
Return the date of the last thursday before easter
def get_holy_thursday(self, year): "Return the date of the last thursday before easter" sunday = self.get_easter_sunday(year) return sunday - timedelta(days=3)
Return the date of the last friday before easter
def get_good_friday(self, year): "Return the date of the last friday before easter" sunday = self.get_easter_sunday(year) return sunday - timedelta(days=2)
Return the clean monday date
def get_clean_monday(self, year): "Return the clean monday date" sunday = self.get_easter_sunday(year) return sunday - timedelta(days=48)
Return the Easter Saturday date
def get_easter_saturday(self, year): "Return the Easter Saturday date" sunday = self.get_easter_sunday(year) return sunday - timedelta(days=1)
Return the date of the monday after easter
def get_easter_monday(self, year): "Return the date of the monday after easter" sunday = self.get_easter_sunday(year) return sunday + timedelta(days=1)
When Christmas and/or Boxing Day falls on a weekend, it is rolled forward to the next weekday.
def shift_christmas_boxing_days(self, year): """ When Christmas and/or Boxing Day falls on a weekend, it is rolled forward to the next weekday. """ christmas = date(year, 12, 25) boxing_day = date(year, 12, 26) boxing_day_label = "{} Shift".format(self.boxing_day_labe...
Return the christian holidays list according to the mixin
def get_variable_days(self, year): # noqa "Return the christian holidays list according to the mixin" days = super(ChristianMixin, self).get_variable_days(year) if self.include_epiphany: days.append((date(year, 1, 6), "Epiphany")) if self.include_clean_monday: da...
Compute Chinese New Year days. To return a list of holidays. By default, it'll at least return the Chinese New Year holidays chosen using the following options: * ``include_chinese_new_year_eve`` * ``include_chinese_new_year`` (on by default) * ``include_chinese_second_day`` ...
def get_chinese_new_year(self, year): """ Compute Chinese New Year days. To return a list of holidays. By default, it'll at least return the Chinese New Year holidays chosen using the following options: * ``include_chinese_new_year_eve`` * ``include_chinese_new_year`` (...
Taking a list of existing holidays, yield a list of 'shifted' days if the holiday falls on SUN.
def get_shifted_holidays(self, dates): """ Taking a list of existing holidays, yield a list of 'shifted' days if the holiday falls on SUN. """ for holiday, label in dates: if holiday.weekday() == SUN: yield ( holiday + timedelta(day...
Take into account the eventual shift to the next MON if any holiday falls on SUN.
def get_calendar_holidays(self, year): """ Take into account the eventual shift to the next MON if any holiday falls on SUN. """ # Unshifted days are here: days = super(ChineseNewYearCalendar, self).get_calendar_holidays(year) if self.shift_sunday_holidays: ...
calculate equinox with time zone
def calculate_equinoxes(self, year, timezone='UTC'): """ calculate equinox with time zone """ tz = pytz.timezone(timezone) d1 = ephem.next_equinox(str(year)) d = ephem.Date(str(d1)) equinox1 = d.datetime() + tz.utcoffset(d.datetime()) d2 = ephem.next_equinox(d1) ...
Returns the date of the solar term for the given longitude and the given year. Solar terms are used for Chinese and Taiwanese holidays (e.g. Qingming Festival in Taiwan). More information: - https://en.wikipedia.org/wiki/Solar_term - https://en.wikipedia.org/wiki/Qingmi...
def solar_term(self, year, degrees, timezone='UTC'): """ Returns the date of the solar term for the given longitude and the given year. Solar terms are used for Chinese and Taiwanese holidays (e.g. Qingming Festival in Taiwan). More information: - https://en.wik...
Return a list of Islamic (month, day, label) for islamic holidays. Please take note that these dates must be expressed using the Islamic Calendar
def get_islamic_holidays(self): """Return a list of Islamic (month, day, label) for islamic holidays. Please take note that these dates must be expressed using the Islamic Calendar""" days = list(super(IslamicMixin, self).get_islamic_holidays()) if self.include_islamic_new_year:...
Return Spring Holiday for Edinburgh. Set to the 3rd Monday of April, unless it falls on Easter Monday, then it's shifted to previous week.
def get_spring_holiday(self, year): """ Return Spring Holiday for Edinburgh. Set to the 3rd Monday of April, unless it falls on Easter Monday, then it's shifted to previous week. """ easter = self.get_easter_monday(year) spring_holiday = self.get_nth_weekday_in_m...
Return Victoria Day for Edinburgh. Set to the Monday strictly before May 24th. It means that if May 24th is a Monday, it's shifted to the week before.
def get_victoria_day(self, year): """ Return Victoria Day for Edinburgh. Set to the Monday strictly before May 24th. It means that if May 24th is a Monday, it's shifted to the week before. """ may_24th = date(year, 5, 24) # Since "MON(day) == 0", it's either the ...
Return the contents of the given file. Its path is supposed relative to this module.
def read_relative_file(filename): """ Return the contents of the given file. Its path is supposed relative to this module. """ path = join(dirname(abspath(__file__)), filename) with io.open(path, encoding='utf-8') as f: return f.read()
Add a C{Node} to the C{KBucket}. Return True if successful, False if the bucket is full. If the bucket is full, keep track of node in a replacement list, per section 4.1 of the paper.
def add_node(self, node): """ Add a C{Node} to the C{KBucket}. Return True if successful, False if the bucket is full. If the bucket is full, keep track of node in a replacement list, per section 4.1 of the paper. """ if node.id in self.nodes: del se...
Get all of the buckets that haven't been updated in over an hour.
def lonely_buckets(self): """ Get all of the buckets that haven't been updated in over an hour. """ hrago = time.monotonic() - 3600 return [b for b in self.buckets if b.last_updated < hrago]
Get the index of the bucket that the given node would fall into.
def get_bucket_for(self, node): """ Get the index of the bucket that the given node would fall into. """ for index, bucket in enumerate(self.buckets): if node.long_id < bucket.range[1]: return index # we should never be here, but make linter happy ...
Get either a value or list of nodes. Args: rpcmethod: The protocol's callfindValue or call_find_node. The process: 1. calls find_* to current ALPHA nearest not already queried nodes, adding results to current nearest list of k nodes. 2. current nearest list...
async def _find(self, rpcmethod): """ Get either a value or list of nodes. Args: rpcmethod: The protocol's callfindValue or call_find_node. The process: 1. calls find_* to current ALPHA nearest not already queried nodes, adding results to current near...
Handle the result of an iteration in _find.
async def _nodes_found(self, responses): """ Handle the result of an iteration in _find. """ toremove = [] found_values = [] for peerid, response in responses.items(): response = RPCFindResponse(response) if not response.happened(): ...
We got some values! Exciting. But let's make sure they're all the same or freak out a little bit. Also, make sure we tell the nearest node that *didn't* have the value to store it.
async def _handle_found_values(self, values): """ We got some values! Exciting. But let's make sure they're all the same or freak out a little bit. Also, make sure we tell the nearest node that *didn't* have the value to store it. """ value_counts = Counter(val...
Handle the result of an iteration in _find.
async def _nodes_found(self, responses): """ Handle the result of an iteration in _find. """ toremove = [] for peerid, response in responses.items(): response = RPCFindResponse(response) if not response.happened(): toremove.append(peerid) ...
Start listening on the given port. Provide interface="::" to accept ipv6 address
async def listen(self, port, interface='0.0.0.0'): """ Start listening on the given port. Provide interface="::" to accept ipv6 address """ loop = asyncio.get_event_loop() listen = loop.create_datagram_endpoint(self._create_protocol, ...
Refresh buckets that haven't had any lookups in the last hour (per section 2.3 of the paper).
async def _refresh_table(self): """ Refresh buckets that haven't had any lookups in the last hour (per section 2.3 of the paper). """ results = [] for node_id in self.protocol.get_refresh_ids(): node = Node(node_id) nearest = self.protocol.router.f...
Get a :class:`list` of (ip, port) :class:`tuple` pairs suitable for use as an argument to the bootstrap method. The server should have been bootstrapped already - this is just a utility for getting some neighbors and then storing them if this server is going down for a while. When it c...
def bootstrappable_neighbors(self): """ Get a :class:`list` of (ip, port) :class:`tuple` pairs suitable for use as an argument to the bootstrap method. The server should have been bootstrapped already - this is just a utility for getting some neighbors and then storing t...
Get a key if the network has it. Returns: :class:`None` if not found, the value otherwise.
async def get(self, key): """ Get a key if the network has it. Returns: :class:`None` if not found, the value otherwise. """ log.info("Looking up key %s", key) dkey = digest(key) # if this node has it, return it if self.storage.get(dkey) is no...
Bootstrap the server by connecting to other known nodes in the network. Args: addrs: A `list` of (ip, port) `tuple` pairs. Note that only IP addresses are acceptable - hostnames will cause an error.
async def bootstrap(self, addrs): """ Bootstrap the server by connecting to other known nodes in the network. Args: addrs: A `list` of (ip, port) `tuple` pairs. Note that only IP addresses are acceptable - hostnames will cause an error. """ log.de...
Set the given string key to the given value in the network.
async def set(self, key, value): """ Set the given string key to the given value in the network. """ if not check_dht_value_type(value): raise TypeError( "Value must be of type int, float, bool, str, or bytes" ) log.info("setting '%s' = '%s...
Set the given SHA1 digest key (bytes) to the given value in the network.
async def set_digest(self, dkey, value): """ Set the given SHA1 digest key (bytes) to the given value in the network. """ node = Node(dkey) nearest = self.protocol.router.find_neighbors(node) if not nearest: log.warning("There are no known neighbors t...
Save the state of this node (the alpha/ksize/id/immediate neighbors) to a cache file with the given fname.
def save_state(self, fname): """ Save the state of this node (the alpha/ksize/id/immediate neighbors) to a cache file with the given fname. """ log.info("Saving state to %s", fname) data = { 'ksize': self.ksize, 'alpha': self.alpha, 'id...
Load the state of this node (the alpha/ksize/id/immediate neighbors) from a cache file with the given fname.
def load_state(cls, fname): """ Load the state of this node (the alpha/ksize/id/immediate neighbors) from a cache file with the given fname. """ log.info("Loading state from %s", fname) with open(fname, 'rb') as file: data = pickle.load(file) svr = Ser...
Save the state of node with a given regularity to the given filename. Args: fname: File name to save retularly to frequency: Frequency in seconds that the state should be saved. By default, 10 minutes.
def save_state_regularly(self, fname, frequency=600): """ Save the state of node with a given regularity to the given filename. Args: fname: File name to save retularly to frequency: Frequency in seconds that the state should be saved. By ...
Remove a list of peer ids from this heap. Note that while this heap retains a constant visible size (based on the iterator), it's actual size may be quite a bit larger than what's exposed. Therefore, removal of nodes may not change the visible size as previously added nodes suddenly be...
def remove(self, peers): """ Remove a list of peer ids from this heap. Note that while this heap retains a constant visible size (based on the iterator), it's actual size may be quite a bit larger than what's exposed. Therefore, removal of nodes may not change the visible size ...
Push nodes onto heap. @param nodes: This can be a single item or a C{list}.
def push(self, nodes): """ Push nodes onto heap. @param nodes: This can be a single item or a C{list}. """ if not isinstance(nodes, list): nodes = [nodes] for node in nodes: if node not in self: distance = self.node.distance_to(no...
Find the shared prefix between the strings. For instance: sharedPrefix(['blahblah', 'blahwhat']) returns 'blah'.
def shared_prefix(args): """ Find the shared prefix between the strings. For instance: sharedPrefix(['blahblah', 'blahwhat']) returns 'blah'. """ i = 0 while i < min(map(len, args)): if len(set(map(operator.itemgetter(i), args))) != 1: break i += 1 ...
Get ids to search for to keep old buckets up to date.
def get_refresh_ids(self): """ Get ids to search for to keep old buckets up to date. """ ids = [] for bucket in self.router.lonely_buckets(): rid = random.randint(*bucket.range).to_bytes(20, byteorder='big') ids.append(rid) return ids
Given a new node, send it all the keys/values it should be storing, then add it to the routing table. @param node: A new node that just joined (or that we just found out about). Process: For each key in storage, get k closest nodes. If newnode is closer than the furthe...
def welcome_if_new(self, node): """ Given a new node, send it all the keys/values it should be storing, then add it to the routing table. @param node: A new node that just joined (or that we just found out about). Process: For each key in storage, get k closest ...
If we get a response, add the node to the routing table. If we get no response, make sure it's removed from the routing table.
def handle_call_response(self, result, node): """ If we get a response, add the node to the routing table. If we get no response, make sure it's removed from the routing table. """ if not result[0]: log.warning("no response from %s, removing from router", node) ...
Blank out the NeoPixels and release the pin.
def deinit(self): """Blank out the NeoPixels and release the pin.""" for i in range(len(self.buf)): self.buf[i] = 0 neopixel_write(self.pin, self.buf) self.pin.deinit()
Colors all pixels the given ***color***.
def fill(self, color): """Colors all pixels the given ***color***.""" auto_write = self.auto_write self.auto_write = False for i, _ in enumerate(self): self[i] = color if auto_write: self.show() self.auto_write = auto_write
Shows the new colors on the pixels themselves if they haven't already been autowritten. The colors may or may not be showing after this function returns because it may be done asynchronously.
def show(self): """Shows the new colors on the pixels themselves if they haven't already been autowritten. The colors may or may not be showing after this function returns because it may be done asynchronously.""" if self.brightness > 0.99: neopixel_write(self.pin, s...
Set a specific value on a kubernetes object's attribute obj an object from Kubernetes Python API client attribute Should be a Kubernetes API style attribute (with camelCase) value Can be anything (string, list, dict, k8s objects) that can be accepted by the k8s python client
def _set_k8s_attribute(obj, attribute, value): """ Set a specific value on a kubernetes object's attribute obj an object from Kubernetes Python API client attribute Should be a Kubernetes API style attribute (with camelCase) value Can be anything (string, list, dict, k8s obj...
Merge two dictionaries recursively. From https://stackoverflow.com/a/25270947
def merge_dictionaries(a, b, path=None, update=True): """ Merge two dictionaries recursively. From https://stackoverflow.com/a/25270947 """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): ...
Create generic pod template from input parameters Examples -------- >>> make_pod_spec(image='daskdev/dask:latest', memory_limit='4G', memory_request='4G')
def make_pod_spec( image, labels={}, threads_per_worker=1, env={}, extra_container_config={}, extra_pod_config={}, memory_limit=None, memory_request=None, cpu_limit=None, cpu_request=None, ): """ Create generic pod template from inp...
Normalize pod template and check for type errors
def clean_pod_template(pod_template): """ Normalize pod template and check for type errors """ if isinstance(pod_template, str): msg = ('Expected a kubernetes.client.V1Pod object, got %s' 'If trying to pass a yaml filename then use ' 'KubeCluster.from_yaml') raise T...
Load the first valid configuration in the list *auth*. A single configuration method can be passed. Parameters ---------- auth: List[ClusterAuth] (optional) Configuration methods to attempt in order. Defaults to ``[InCluster(), KubeConfig()]``.
def load_first(auth=None): """ Load the first valid configuration in the list *auth*. A single configuration method can be passed. Parameters ---------- auth: List[ClusterAuth] (optional) Configuration methods to attempt in order. Defaults to ``...
Remove all pods with these labels in this namespace
def _cleanup_pods(namespace, labels): """ Remove all pods with these labels in this namespace """ api = kubernetes.client.CoreV1Api() pods = api.list_namespaced_pod(namespace, label_selector=format_labels(labels)) for pod in pods.items: try: api.delete_namespaced_pod(pod.metadata.nam...
Convert a dictionary of labels into a comma separated string
def format_labels(labels): """ Convert a dictionary of labels into a comma separated string """ if labels: return ','.join(['{}={}'.format(k, v) for k, v in labels.items()]) else: return ''
Get current namespace if running in a k8s cluster If not in a k8s cluster with service accounts enabled, default to 'default' Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125
def _namespace_default(): """ Get current namespace if running in a k8s cluster If not in a k8s cluster with service accounts enabled, default to 'default' Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125 """ ns_path = '/var/run/secrets/kubernete...
Select n workers to close from scheduler
def select_workers_to_close(scheduler, n_to_close): """ Select n workers to close from scheduler """ workers = list(scheduler.workers.values()) assert n_to_close <= len(workers) key = lambda ws: ws.metrics['memory'] to_close = set(sorted(scheduler.idle, key=key)[:n_to_close]) if len(to_close) <...
Create cluster with worker pod spec defined by a YAML file We can start a cluster with pods defined in an accompanying YAML file like the following: .. code-block:: yaml kind: Pod metadata: labels: foo: bar baz: quux ...
def from_yaml(cls, yaml_path, **kwargs): """ Create cluster with worker pod spec defined by a YAML file We can start a cluster with pods defined in an accompanying YAML file like the following: .. code-block:: yaml kind: Pod metadata: labels: ...
A list of kubernetes pods corresponding to current workers See Also -------- KubeCluster.logs
def pods(self): """ A list of kubernetes pods corresponding to current workers See Also -------- KubeCluster.logs """ return self.core_api.list_namespaced_pod( self.namespace, label_selector=format_labels(self.pod_template.metadata.labels) ...