_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q226900
_ElementKeywords.element_text_should_be
train
def element_text_should_be(self, locator, expected, message=''): """Verifies element identified by ``locator`` exactly contains text ``expected``. In contrast to `Element Should Contain Text`, this keyword does not try a substring match but an exact match on the element identified by ``loca...
python
{ "resource": "" }
q226901
_ElementKeywords.get_element_location
train
def get_element_location(self, locator): """Get element location Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. """ element = self._element_find(locator, True, True) element_location = element.loc...
python
{ "resource": "" }
q226902
_ElementKeywords.get_element_size
train
def get_element_size(self, locator): """Get element size Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. """ element = self._element_find(locator, True, True) element_size = element.size s...
python
{ "resource": "" }
q226903
_ElementKeywords.text_should_be_visible
train
def text_should_be_visible(self, text, exact_match=False, loglevel='INFO'): """Verifies that element identified with text is visible. New in AppiumLibrary 1.4.5 """ if not self._element_find_by_text(text, exact_match).is_displayed(): self.log_source(loglevel) ...
python
{ "resource": "" }
q226904
_ApplicationManagementKeywords.close_application
train
def close_application(self): """Closes the current application and also close webdriver session.""" self._debug('Closing application with session id %s' % self._current_application().session_id) self._cache.close()
python
{ "resource": "" }
q226905
_ApplicationManagementKeywords.get_appium_sessionId
train
def get_appium_sessionId(self): """Returns the current session ID as a reference""" self._info("Appium Session ID: " + self._current_application().session_id) return self._current_application().session_id
python
{ "resource": "" }
q226906
_ApplicationManagementKeywords.lock
train
def lock(self, seconds=5): """ Lock the device for a certain period of time. iOS only. """ self._current_application().lock(robot.utils.timestr_to_secs(seconds))
python
{ "resource": "" }
q226907
_ApplicationManagementKeywords.get_capability
train
def get_capability(self, capability_name): """ Return the desired capability value by desired capability name """ try: capability = self._current_application().capabilities[capability_name] except Exception as e: raise e return capability
python
{ "resource": "" }
q226908
ElementFinder._find_by_android
train
def _find_by_android(self, browser, criteria, tag, constraints): """Find element matches by UI Automator.""" return self._filter_elements( browser.find_elements_by_android_uiautomator(criteria), tag, constraints)
python
{ "resource": "" }
q226909
ElementFinder._find_by_ios
train
def _find_by_ios(self, browser, criteria, tag, constraints): """Find element matches by UI Automation.""" return self._filter_elements( browser.find_elements_by_ios_uiautomation(criteria), tag, constraints)
python
{ "resource": "" }
q226910
ElementFinder._find_by_nsp
train
def _find_by_nsp(self, browser, criteria, tag, constraints): """Find element matches by iOSNsPredicateString.""" return self._filter_elements( browser.find_elements_by_ios_predicate(criteria), tag, constraints)
python
{ "resource": "" }
q226911
ElementFinder._find_by_chain
train
def _find_by_chain(self, browser, criteria, tag, constraints): """Find element matches by iOSChainString.""" return self._filter_elements( browser.find_elements_by_ios_class_chain(criteria), tag, constraints)
python
{ "resource": "" }
q226912
_KeyeventKeywords.press_keycode
train
def press_keycode(self, keycode, metastate=None): """Sends a press of keycode to the device. Android only. Possible keycodes & meta states can be found in http://developer.android.com/reference/android/view/KeyEvent.html Meta state describe the pressed state of key modifiers s...
python
{ "resource": "" }
q226913
_KeyeventKeywords.long_press_keycode
train
def long_press_keycode(self, keycode, metastate=None): """Sends a long press of keycode to the device. Android only. See `press keycode` for more details. """ driver = self._current_application() driver.long_press_keycode(int(keycode), metastate)
python
{ "resource": "" }
q226914
rapl_read
train
def rapl_read(): """ Read power stats and return dictionary""" basenames = glob.glob('/sys/class/powercap/intel-rapl:*/') basenames = sorted(set({x for x in basenames})) pjoin = os.path.join ret = list() for path in basenames: name = None try: name = cat(pjoin(path, ...
python
{ "resource": "" }
q226915
ScalableBarGraph.calculate_bar_widths
train
def calculate_bar_widths(self, size, bardata): """ Return a list of bar widths, one for each bar in data. If self.bar_width is None this implementation will stretch the bars across the available space specified by maxcol. """ (maxcol, _) = size if self.bar_width...
python
{ "resource": "" }
q226916
LabeledBarGraphVector.set_visible_graphs
train
def set_visible_graphs(self, visible_graph_list=None): """Show a column of the graph selected for display""" if visible_graph_list is None: visible_graph_list = self.visible_graph_list vline = urwid.AttrWrap(urwid.SolidFill(u'|'), 'line') graph_vector_column_list = [] ...
python
{ "resource": "" }
q226917
get_processor_name
train
def get_processor_name(): """ Returns the processor name in the system """ if platform.system() == "Linux": with open("/proc/cpuinfo", "rb") as cpuinfo: all_info = cpuinfo.readlines() for line in all_info: if b'model name' in line: return re.su...
python
{ "resource": "" }
q226918
kill_child_processes
train
def kill_child_processes(parent_proc): """ Kills a process and all its children """ logging.debug("Killing stress process") try: for proc in parent_proc.children(recursive=True): logging.debug('Killing %s', proc) proc.kill() parent_proc.kill() except AttributeErro...
python
{ "resource": "" }
q226919
output_to_csv
train
def output_to_csv(sources, csv_writeable_file): """Print statistics to csv file""" file_exists = os.path.isfile(csv_writeable_file) with open(csv_writeable_file, 'a') as csvfile: csv_dict = OrderedDict() csv_dict.update({'Time': time.strftime("%Y-%m-%d_%H:%M:%S")}) summaries = [val ...
python
{ "resource": "" }
q226920
output_to_terminal
train
def output_to_terminal(sources): """Print statistics to the terminal""" results = OrderedDict() for source in sources: if source.get_is_available(): source.update() results.update(source.get_summary()) for key, value in results.items(): sys.stdout.write(str(key) +...
python
{ "resource": "" }
q226921
output_to_json
train
def output_to_json(sources): """Print statistics to the terminal in Json format""" results = OrderedDict() for source in sources: if source.get_is_available(): source.update() source_name = source.get_source_name() results[source_name] = source.get_sensors_summary...
python
{ "resource": "" }
q226922
make_user_config_dir
train
def make_user_config_dir(): """ Create the user s-tui config directory if it doesn't exist """ config_path = get_user_config_dir() if not user_config_dir_exists(): try: os.mkdir(config_path) os.mkdir(os.path.join(config_path, 'hooks.d')) except OSError: ...
python
{ "resource": "" }
q226923
ScriptHookLoader.load_script
train
def load_script(self, source_name, timeoutMilliseconds=0): """ Return ScriptHook for source_name Source and with a ready timeout of timeoutMilliseconds """ script_path = os.path.join(self.scripts_dir_path, self._source_to_script_name(source_nam...
python
{ "resource": "" }
q226924
Source.get_sensors_summary
train
def get_sensors_summary(self): """ This returns a dict of sensor of the source and their values """ sub_title_list = self.get_sensor_list() graph_vector_summary = OrderedDict() for graph_idx, graph_data in enumerate(self.last_measurement): val_str = str(round(graph_data, 1))...
python
{ "resource": "" }
q226925
Source.get_summary
train
def get_summary(self): """ Returns a dict of source name and sensors with their values """ graph_vector_summary = OrderedDict() graph_vector_summary[self.get_source_name()] = ( '[' + self.measurement_unit + ']') graph_vector_summary.update(self.get_sensors_summary()) ...
python
{ "resource": "" }
q226926
Source.eval_hooks
train
def eval_hooks(self): """ Evaluate the current state of this Source and invoke any attached hooks if they've been triggered """ logging.debug("Evaluating hooks") if self.get_edge_triggered(): logging.debug("Hook triggered") for hook in [h for h in ...
python
{ "resource": "" }
q226927
Hook.invoke
train
def invoke(self): """ Run callback, optionally passing a variable number of arguments `callback_args` """ # Don't sleep a hook if it has never run if self.timeout_milliseconds > 0: self.ready_time = ( datetime.now() + timedelta...
python
{ "resource": "" }
q226928
radio_button
train
def radio_button(g, l, fn): """ Inheriting radio button of urwid """ w = urwid.RadioButton(g, l, False, on_state_change=fn) w = urwid.AttrWrap(w, 'button normal', 'button select') return w
python
{ "resource": "" }
q226929
StressController.start_stress
train
def start_stress(self, stress_cmd): """ Starts a new stress process with a given cmd """ with open(os.devnull, 'w') as dev_null: try: stress_proc = subprocess.Popen(stress_cmd, stdout=dev_null, stderr=dev_null) se...
python
{ "resource": "" }
q226930
GraphView.update_displayed_information
train
def update_displayed_information(self): """ Update all the graphs that are being displayed """ for source in self.controller.sources: source_name = source.get_source_name() if (any(self.graphs_menu.active_sensors[source_name]) or any(self.summary_menu.active_...
python
{ "resource": "" }
q226931
GraphView.on_reset_button
train
def on_reset_button(self, _): """Reset graph data and display empty graph""" for graph in self.visible_graphs.values(): graph.reset() for graph in self.graphs.values(): try: graph.source.reset() except NotImplementedError: pass ...
python
{ "resource": "" }
q226932
GraphView.on_stress_menu_open
train
def on_stress_menu_open(self, widget): """Open stress options""" self.original_widget = urwid.Overlay(self.stress_menu.main_window, self.original_widget, ('relative', self.left_margin), ...
python
{ "resource": "" }
q226933
GraphView.on_help_menu_open
train
def on_help_menu_open(self, widget): """Open Help menu""" self.original_widget = urwid.Overlay(self.help_menu.main_window, self.original_widget, ('relative', self.left_margin), ...
python
{ "resource": "" }
q226934
GraphView.on_about_menu_open
train
def on_about_menu_open(self, widget): """Open About menu""" self.original_widget = urwid.Overlay(self.about_menu.main_window, self.original_widget, ('relative', self.left_margin), ...
python
{ "resource": "" }
q226935
GraphView.on_mode_button
train
def on_mode_button(self, my_button, state): """Notify the controller of a new mode setting.""" if state: # The new mode is the label of the button self.controller.set_mode(my_button.get_label())
python
{ "resource": "" }
q226936
GraphView.on_unicode_checkbox
train
def on_unicode_checkbox(self, w=None, state=False): """Enable smooth edges if utf-8 is supported""" logging.debug("unicode State is %s", state) # Update the controller to the state of the checkbox self.controller.smooth_graph_mode = state if state: self.hline = urwid...
python
{ "resource": "" }
q226937
GraphView._generate_graph_controls
train
def _generate_graph_controls(self): """ Display sidebar controls. i.e. buttons, and controls""" # setup mode radio buttons stress_modes = self.controller.stress_conroller.get_modes() group = [] for mode in stress_modes: self.mode_buttons.append(radio_button(group, mod...
python
{ "resource": "" }
q226938
GraphView._generate_cpu_stats
train
def _generate_cpu_stats(): """Read and display processor name """ cpu_name = urwid.Text("CPU Name N/A", align="center") try: cpu_name = urwid.Text(get_processor_name().strip(), align="center") except OSError: logging.info("CPU name not available") return [...
python
{ "resource": "" }
q226939
GraphView.show_graphs
train
def show_graphs(self): """Show a pile of the graph selected for dislpay""" elements = itertools.chain.from_iterable( ([graph] for graph in self.visible_graphs.values())) self.graph_place_holder.original_widget = urwid.Pile(elements)
python
{ "resource": "" }
q226940
GraphController._load_config
train
def _load_config(self, t_thresh): """ Uses configurations defined by user to configure sources for display. This should be the only place where sources are initiated This returns a list of sources after configurations are applied """ # Load and configure user config dir ...
python
{ "resource": "" }
q226941
GraphController._config_stress
train
def _config_stress(self): """ Configures the possible stress processes and modes """ # Configure stress_process self.stress_exe = None stress_installed = False self.stress_exe = which('stress') if self.stress_exe: stress_installed = True else: ...
python
{ "resource": "" }
q226942
GraphController.main
train
def main(self): """ Starts the main loop and graph animation """ loop = MainLoop(self.view, DEFAULT_PALETTE, handle_mouse=self.handle_mouse) self.view.show_graphs() self.animate_graph(loop) try: loop.run() except (ZeroDivisionError) as ...
python
{ "resource": "" }
q226943
GraphController.update_stress_mode
train
def update_stress_mode(self): """ Updates stress mode according to radio buttons state """ self.stress_conroller.kill_stress_process() # Start a new clock upon starting a new stress test self.view.clock_view.set_text(ZERO_TIME) self.stress_start_time = timeit.default_timer() ...
python
{ "resource": "" }
q226944
GraphController.save_settings
train
def save_settings(self): """ Save the current configuration to a user config file """ def _save_displayed_setting(conf, submenu): for source, visible_sensors in \ self.view.graphs_menu.active_sensors.items(): section = source + "," + submenu ...
python
{ "resource": "" }
q226945
GraphController.animate_graph
train
def animate_graph(self, loop, user_data=None): """ Update the graph and schedule the next update This is where the magic happens """ self.view.update_displayed_information() # Save to CSV if configured if self.save_csv or self.csv_file is not None: ou...
python
{ "resource": "" }
q226946
obfuscation_machine
train
def obfuscation_machine(use_unicode=False, identifier_length=1): """ A generator that returns short sequential combinations of lower and upper-case letters that will never repeat. If *use_unicode* is ``True``, use nonlatin cryllic, arabic, and syriac letters instead of the usual ABCs. The *ide...
python
{ "resource": "" }
q226947
apply_obfuscation
train
def apply_obfuscation(source): """ Returns 'source' all obfuscated. """ global keyword_args global imported_modules tokens = token_utils.listified_tokenizer(source) keyword_args = analyze.enumerate_keyword_args(tokens) imported_modules = analyze.enumerate_imports(tokens) variables = ...
python
{ "resource": "" }
q226948
bz2_pack
train
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...
python
{ "resource": "" }
q226949
iso_register
train
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' ...
python
{ "resource": "" }
q226950
IsoRegistry.get_calendar_class
train
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)...
python
{ "resource": "" }
q226951
IsoRegistry.get_subregions
train
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...
python
{ "resource": "" }
q226952
IsoRegistry.items
train
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 ...
python
{ "resource": "" }
q226953
cleaned_date
train
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( ...
python
{ "resource": "" }
q226954
Calendar.get_fixed_holidays
train
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
python
{ "resource": "" }
q226955
Calendar.get_holiday_label
train
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)
python
{ "resource": "" }
q226956
Calendar.is_working_day
train
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....
python
{ "resource": "" }
q226957
Calendar.is_holiday
train
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). ...
python
{ "resource": "" }
q226958
Calendar.add_working_days
train
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. ...
python
{ "resource": "" }
q226959
Calendar.sub_working_days
train
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...
python
{ "resource": "" }
q226960
Calendar.find_following_working_day
train
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) ...
python
{ "resource": "" }
q226961
Calendar.get_first_weekday_after
train
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) ...
python
{ "resource": "" }
q226962
Calendar.get_working_days_delta
train
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...
python
{ "resource": "" }
q226963
ChristianMixin.get_holy_thursday
train
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)
python
{ "resource": "" }
q226964
ChristianMixin.get_good_friday
train
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)
python
{ "resource": "" }
q226965
ChristianMixin.get_clean_monday
train
def get_clean_monday(self, year): "Return the clean monday date" sunday = self.get_easter_sunday(year) return sunday - timedelta(days=48)
python
{ "resource": "" }
q226966
ChristianMixin.get_easter_saturday
train
def get_easter_saturday(self, year): "Return the Easter Saturday date" sunday = self.get_easter_sunday(year) return sunday - timedelta(days=1)
python
{ "resource": "" }
q226967
ChristianMixin.get_easter_monday
train
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)
python
{ "resource": "" }
q226968
ChristianMixin.get_variable_days
train
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...
python
{ "resource": "" }
q226969
ChineseNewYearCalendar.get_chinese_new_year
train
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`` (...
python
{ "resource": "" }
q226970
ChineseNewYearCalendar.get_shifted_holidays
train
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...
python
{ "resource": "" }
q226971
ChineseNewYearCalendar.get_calendar_holidays
train
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: ...
python
{ "resource": "" }
q226972
EphemMixin.calculate_equinoxes
train
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) ...
python
{ "resource": "" }
q226973
EphemMixin.solar_term
train
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...
python
{ "resource": "" }
q226974
Edinburgh.get_spring_holiday
train
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...
python
{ "resource": "" }
q226975
Edinburgh.get_victoria_day
train
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 ...
python
{ "resource": "" }
q226976
read_relative_file
train
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()
python
{ "resource": "" }
q226977
RoutingTable.lonely_buckets
train
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]
python
{ "resource": "" }
q226978
RoutingTable.get_bucket_for
train
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 ...
python
{ "resource": "" }
q226979
SpiderCrawl._find
train
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...
python
{ "resource": "" }
q226980
check_dht_value_type
train
def check_dht_value_type(value): """ Checks to see if the type of the value is a valid type for placing in the dht. """ typeset = [ int, float, bool, str, bytes ] return type(value) in typeset
python
{ "resource": "" }
q226981
Server.listen
train
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, ...
python
{ "resource": "" }
q226982
Server.bootstrap
train
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...
python
{ "resource": "" }
q226983
Server.get
train
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...
python
{ "resource": "" }
q226984
Server.set
train
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...
python
{ "resource": "" }
q226985
Server.save_state_regularly
train
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 ...
python
{ "resource": "" }
q226986
NodeHeap.push
train
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...
python
{ "resource": "" }
q226987
shared_prefix
train
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 ...
python
{ "resource": "" }
q226988
KademliaProtocol.get_refresh_ids
train
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
python
{ "resource": "" }
q226989
KademliaProtocol.handle_call_response
train
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) ...
python
{ "resource": "" }
q226990
NeoPixel.deinit
train
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()
python
{ "resource": "" }
q226991
NeoPixel.show
train
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...
python
{ "resource": "" }
q226992
_set_k8s_attribute
train
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...
python
{ "resource": "" }
q226993
merge_dictionaries
train
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): ...
python
{ "resource": "" }
q226994
make_pod_spec
train
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...
python
{ "resource": "" }
q226995
clean_pod_template
train
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...
python
{ "resource": "" }
q226996
_cleanup_pods
train
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...
python
{ "resource": "" }
q226997
format_labels
train
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 ''
python
{ "resource": "" }
q226998
_namespace_default
train
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...
python
{ "resource": "" }
q226999
select_workers_to_close
train
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) <...
python
{ "resource": "" }