_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q34800
_unhash
train
def _unhash(hashed, alphabet): """Restores a number tuple from hashed using the given `alphabet` index.""" number = 0 len_alphabet = len(alphabet) for character in hashed: position = alphabet.index(character) number *= len_alphabet number += position return number
python
{ "resource": "" }
q34801
_reorder
train
def _reorder(string, salt): """Reorders `string` according to `salt`.""" len_salt = len(salt) if len_salt != 0: string = list(string) index, integer_sum = 0, 0 for i in range(len(string) - 1, 0, -1): integer = ord(salt[index]) integer_sum += integer ...
python
{ "resource": "" }
q34802
_ensure_length
train
def _ensure_length(encoded, min_length, alphabet, guards, values_hash): """Ensures the minimal hash length""" len_guards = len(guards) guard_index = (values_hash + ord(encoded[0])) % len_guards encoded = guards[guard_index] + encoded if len(encoded) < min_length: guard_index = (values_hash ...
python
{ "resource": "" }
q34803
_encode
train
def _encode(values, salt, min_length, alphabet, separators, guards): """Helper function that does the hash building without argument checks.""" len_alphabet = len(alphabet) len_separators = len(separators) values_hash = sum(x % (i + 100) for i, x in enumerate(values)) encoded = lottery = alphabet[v...
python
{ "resource": "" }
q34804
_decode
train
def _decode(hashid, salt, alphabet, separators, guards): """Helper method that restores the values encoded in a hashid without argument checks.""" parts = tuple(_split(hashid, guards)) hashid = parts[1] if 2 <= len(parts) <= 3 else parts[0] if not hashid: return lottery_char = hashid[0...
python
{ "resource": "" }
q34805
_deprecated
train
def _deprecated(func): """A decorator that warns about deprecation when the passed-in function is invoked.""" @wraps(func) def with_warning(*args, **kwargs): warnings.warn( ('The %s method is deprecated and will be removed in v2.*.*' % func.__name__), Depreca...
python
{ "resource": "" }
q34806
Hashids.encode
train
def encode(self, *values): """Builds a hash from the passed `values`. :param values The values to transform into a hashid >>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456') >>> hashids.encode(1, 23, 456) '1d6216i30h53elk3' """ if not (values and ...
python
{ "resource": "" }
q34807
Hashids.decode
train
def decode(self, hashid): """Restore a tuple of numbers from the passed `hashid`. :param hashid The hashid to decode >>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456') >>> hashids.decode('1d6216i30h53elk3') (1, 23, 456) """ if not hashid or not _...
python
{ "resource": "" }
q34808
get_suppressions
train
def get_suppressions(relative_filepaths, root, messages): """ Given every message which was emitted by the tools, and the list of files to inspect, create a list of files to ignore, and a map of filepath -> line-number -> codes to ignore """ paths_to_ignore = set() lines_to_ignore = defaultd...
python
{ "resource": "" }
q34809
get_parser
train
def get_parser(): """ This is a helper method to return an argparse parser, to be used with the Sphinx argparse plugin for documentation. """ manager = cfg.build_manager() source = cfg.build_command_line_source(prog='prospector', description=None) return source.build_parser(manager.settings,...
python
{ "resource": "" }
q34810
PylintTool._combine_w0614
train
def _combine_w0614(self, messages): """ For the "unused import from wildcard import" messages, we want to combine all warnings about the same line into a single message. """ by_loc = defaultdict(list) out = [] for message in messages: if messa...
python
{ "resource": "" }
q34811
ProspectorLinter.config_from_file
train
def config_from_file(self, config_file=None): """Will return `True` if plugins have been loaded. For pylint>=1.5. Else `False`.""" if PYLINT_VERSION >= (1, 5): self.read_config_file(config_file) if self.cfgfile_parser.has_option('MASTER', 'load-plugins'): # pylint...
python
{ "resource": "" }
q34812
filter_messages
train
def filter_messages(relative_filepaths, root, messages): """ This method post-processes all messages output by all tools, in order to filter out any based on the overall output. The main aim currently is to use information about messages suppressed by pylint due to inline comments, and use that to ...
python
{ "resource": "" }
q34813
FoundFiles.get_minimal_syspath
train
def get_minimal_syspath(self, absolute_paths=True): """ Provide a list of directories that, when added to sys.path, would enable any of the discovered python modules to be found """ # firstly, gather a list of the minimum path to each package package_list = set() ...
python
{ "resource": "" }
q34814
blend_line
train
def blend_line(messages, blend_combos=None): """ Given a list of messages on the same line, blend them together so that we end up with one message per actual problem. Note that we can still return more than one message here if there are two or more different errors for the line. """ blend_co...
python
{ "resource": "" }
q34815
draw_boundary_images
train
def draw_boundary_images(glf, glb, v, f, vpe, fpe, camera): """Assumes camera is set up correctly, and that glf has any texmapping on necessary.""" glf.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glb.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); # Figure out which edges are on pairs of differ...
python
{ "resource": "" }
q34816
UTF8ToUTF16BE
train
def UTF8ToUTF16BE(instr, setbom=True): "Converts UTF-8 strings to UTF16-BE." outstr = "".encode() if (setbom): outstr += "\xFE\xFF".encode("latin1") if not isinstance(instr, unicode): instr = instr.decode('UTF-8') outstr += instr.encode('UTF-16BE') # convert bytes back to fake un...
python
{ "resource": "" }
q34817
Template.load_elements
train
def load_elements(self, elements): "Initialize the internal element structures" self.pg_no = 0 self.elements = elements self.keys = [v['name'].lower() for v in self.elements]
python
{ "resource": "" }
q34818
Template.parse_csv
train
def parse_csv(self, infile, delimiter=",", decimal_sep="."): "Parse template format csv file and create elements dict" keys = ('name','type','x1','y1','x2','y2','font','size', 'bold','italic','underline','foreground','background', 'align','text','priority', 'multiline') s...
python
{ "resource": "" }
q34819
HTMLMixin.write_html
train
def write_html(self, text, image_map=None): "Parse HTML and convert it to PDF" h2p = HTML2FPDF(self, image_map) text = h2p.unescape(text) # To deal with HTML entities h2p.feed(text)
python
{ "resource": "" }
q34820
FPDF.check_page
train
def check_page(fn): "Decorator to protect drawing methods" @wraps(fn) def wrapper(self, *args, **kwargs): if not self.page and not kwargs.get('split_only'): self.error("No page open, you need to call add_page() first") else: return fn(self,...
python
{ "resource": "" }
q34821
FPDF.set_margins
train
def set_margins(self, left,top,right=-1): "Set left, top and right margins" self.l_margin=left self.t_margin=top if(right==-1): right=left self.r_margin=right
python
{ "resource": "" }
q34822
FPDF.set_left_margin
train
def set_left_margin(self, margin): "Set left margin" self.l_margin=margin if(self.page>0 and self.x<margin): self.x=margin
python
{ "resource": "" }
q34823
FPDF.set_auto_page_break
train
def set_auto_page_break(self, auto,margin=0): "Set auto page break mode and triggering margin" self.auto_page_break=auto self.b_margin=margin self.page_break_trigger=self.h-margin
python
{ "resource": "" }
q34824
FPDF.set_display_mode
train
def set_display_mode(self, zoom,layout='continuous'): """Set display mode in viewer The "zoom" argument may be 'fullpage', 'fullwidth', 'real', 'default', or a number, interpreted as a percentage.""" if(zoom=='fullpage' or zoom=='fullwidth' or zoom=='real' or zoom=='def...
python
{ "resource": "" }
q34825
FPDF.add_page
train
def add_page(self, orientation=''): "Start a new page" if(self.state==0): self.open() family=self.font_family if self.underline: style = self.font_style + 'U' else: style = self.font_style size=self.font_size_pt lw=self.line_wid...
python
{ "resource": "" }
q34826
FPDF.set_draw_color
train
def set_draw_color(self, r,g=-1,b=-1): "Set color for all stroking operations" if((r==0 and g==0 and b==0) or g==-1): self.draw_color=sprintf('%.3f G',r/255.0) else: self.draw_color=sprintf('%.3f %.3f %.3f RG',r/255.0,g/255.0,b/255.0) if(self.page>0): ...
python
{ "resource": "" }
q34827
FPDF.set_fill_color
train
def set_fill_color(self,r,g=-1,b=-1): "Set color for all filling operations" if((r==0 and g==0 and b==0) or g==-1): self.fill_color=sprintf('%.3f g',r/255.0) else: self.fill_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0) self.color_flag=(self.fill_colo...
python
{ "resource": "" }
q34828
FPDF.set_text_color
train
def set_text_color(self, r,g=-1,b=-1): "Set color for text" if((r==0 and g==0 and b==0) or g==-1): self.text_color=sprintf('%.3f g',r/255.0) else: self.text_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0) self.color_flag=(self.fill_color!=self.text_colo...
python
{ "resource": "" }
q34829
FPDF.get_string_width
train
def get_string_width(self, s): "Get width of a string in the current font" s = self.normalize_text(s) cw=self.current_font['cw'] w=0 l=len(s) if self.unifontsubset: for char in s: char = ord(char) if len(cw) > char: ...
python
{ "resource": "" }
q34830
FPDF.set_line_width
train
def set_line_width(self, width): "Set line width" self.line_width=width if(self.page>0): self._out(sprintf('%.2f w',width*self.k))
python
{ "resource": "" }
q34831
FPDF.ellipse
train
def ellipse(self, x,y,w,h,style=''): "Draw a ellipse" if(style=='F'): op='f' elif(style=='FD' or style=='DF'): op='B' else: op='S' cx = x + w/2.0 cy = y + h/2.0 rx = w/2.0 ry = h/2.0 lx = 4.0/3.0*(math.sqrt(2)-...
python
{ "resource": "" }
q34832
FPDF.set_font
train
def set_font(self, family,style='',size=0): "Select a font; size given in points" family=family.lower() if(family==''): family=self.font_family if(family=='arial'): family='helvetica' elif(family=='symbol' or family=='zapfdingbats'): style='' ...
python
{ "resource": "" }
q34833
FPDF.set_font_size
train
def set_font_size(self, size): "Set font size in points" if(self.font_size_pt==size): return self.font_size_pt=size self.font_size=size/self.k if(self.page>0): self._out(sprintf('BT /F%d %.2f Tf ET',self.current_font['i'],self.font_size_pt))
python
{ "resource": "" }
q34834
FPDF.add_link
train
def add_link(self): "Create a new internal link" n=len(self.links)+1 self.links[n]=(0,0) return n
python
{ "resource": "" }
q34835
FPDF.set_link
train
def set_link(self, link,y=0,page=-1): "Set destination of internal link" if(y==-1): y=self.y if(page==-1): page=self.page self.links[link]=[page,y]
python
{ "resource": "" }
q34836
FPDF.link
train
def link(self, x,y,w,h,link): "Put a link on the page" if not self.page in self.page_links: self.page_links[self.page] = [] self.page_links[self.page] += [(x*self.k,self.h_pt-y*self.k,w*self.k,h*self.k,link),]
python
{ "resource": "" }
q34837
FPDF.text
train
def text(self, x, y, txt=''): "Output a string" txt = self.normalize_text(txt) if (self.unifontsubset): txt2 = self._escape(UTF8ToUTF16BE(txt, False)) for uni in UTF8StringToArray(txt): self.current_font['subset'].append(uni) else: txt2...
python
{ "resource": "" }
q34838
FPDF.write
train
def write(self, h, txt='', link=''): "Output text in flowing mode" txt = self.normalize_text(txt) cw=self.current_font['cw'] w=self.w-self.r_margin-self.x wmax=(w-2*self.c_margin)*1000.0/self.font_size s=txt.replace("\r",'') nb=len(s) sep=-1 i=0 ...
python
{ "resource": "" }
q34839
FPDF.image
train
def image(self, name, x=None, y=None, w=0,h=0,type='',link=''): "Put an image on the page" if not name in self.images: #First use of image, get info if(type==''): pos=name.rfind('.') if(not pos): self.error('image file has no ex...
python
{ "resource": "" }
q34840
FPDF.ln
train
def ln(self, h=''): "Line Feed; default value is last cell height" self.x=self.l_margin if(isinstance(h, basestring)): self.y+=self.lasth else: self.y+=h
python
{ "resource": "" }
q34841
FPDF.set_x
train
def set_x(self, x): "Set x position" if(x>=0): self.x=x else: self.x=self.w+x
python
{ "resource": "" }
q34842
FPDF.set_y
train
def set_y(self, y): "Set y position and reset x" self.x=self.l_margin if(y>=0): self.y=y else: self.y=self.h+y
python
{ "resource": "" }
q34843
FPDF.output
train
def output(self, name='',dest=''): "Output PDF to some destination" #Finish document if necessary if(self.state<3): self.close() dest=dest.upper() if(dest==''): if(name==''): name='doc.pdf' dest='I' else: ...
python
{ "resource": "" }
q34844
JSONPDecoder.decode
train
def decode(self, json_string): """ json_string is basicly string that you give to json.loads method """ default_obj = super(JSONPDecoder, self).decode(json_string) return list(self._iterdecode(default_obj))[0]
python
{ "resource": "" }
q34845
Highmap.add_data_set
train
def add_data_set(self, data, series_type="map", name=None, is_coordinate = False, **kwargs): """set data for series option in highmaps """ self.data_set_count += 1 if not name: name = "Series %d" % self.data_set_count kwargs.update({'name':name}) if is_coord...
python
{ "resource": "" }
q34846
Highmap.add_drilldown_data_set
train
def add_drilldown_data_set(self, data, series_type, id, **kwargs): """set data for drilldown option in highmaps id must be input and corresponding to drilldown arguments in data series """ self.drilldown_data_set_count += 1 if self.drilldown_flag == False: self.dril...
python
{ "resource": "" }
q34847
Highmap.add_data_from_jsonp
train
def add_data_from_jsonp(self, data_src, data_name = 'json_data', series_type="map", name=None, **kwargs): """add data directly from a https source the data_src is the https link for data using jsonp """ self.jsonp_data_flag = True self.jsonp_data_url = json.dumps(data_src) ...
python
{ "resource": "" }
q34848
Highmap._get_jsmap_name
train
def _get_jsmap_name(self, url): """return 'name' of the map in .js format""" ret = urlopen(url) return ret.read().decode('utf-8').split('=')[0].replace(" ", "")
python
{ "resource": "" }
q34849
Highmap.buildcontainer
train
def buildcontainer(self): """generate HTML div""" if self.container: return # Create HTML div with style if self.options['chart'].width: if str(self.options['chart'].width)[-1] != '%': self.div_style += 'width:%spx;' % self.options['chart'].width ...
python
{ "resource": "" }
q34850
Highchart.add_data_set
train
def add_data_set(self, data, series_type="line", name=None, **kwargs): """set data for series option in highcharts""" self.data_set_count += 1 if not name: name = "Series %d" % self.data_set_count kwargs.update({'name':name}) if series_type == 'treemap': ...
python
{ "resource": "" }
q34851
JSONPDecoder.json2datetime
train
def json2datetime(json): """Convert JSON representation to date or datetime object depending on the argument count. Requires UTC datetime representation. Raises ValueError if the string cannot be parsed. """ json_m = re.search(r'([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9...
python
{ "resource": "" }
q34852
Highstock.set_options
train
def set_options(self, option_type, option_dict, force_options=False): """set plot options """ if force_options: self.options[option_type].update(option_dict) elif (option_type == 'yAxis' or option_type == 'xAxis') and isinstance(option_dict, list): # For multi-Axis ...
python
{ "resource": "" }
q34853
Highstock.save_file
train
def save_file(self, filename = 'StockChart'): """ save htmlcontent as .html file """ filename = filename + '.html' with open(filename, 'w') as f: #self.buildhtml() f.write(self.htmlcontent) f.closed
python
{ "resource": "" }
q34854
WebPage.acceptNavigationRequest
train
def acceptNavigationRequest(self, url, kind, is_main_frame): """Open external links in browser and internal links in the webview""" ready_url = url.toEncoded().data().decode() is_clicked = kind == self.NavigationTypeLinkClicked if is_clicked and self.root_url not in ready_url: ...
python
{ "resource": "" }
q34855
_safe_attr
train
def _safe_attr(attr, camel_killer=False, replacement_char='x'): """Convert a key into something that is accessible as an attribute""" allowed = string.ascii_letters + string.digits + '_' attr = _safe_key(attr) if camel_killer: attr = _camel_killer(attr) attr = attr.replace(' ', '_') ...
python
{ "resource": "" }
q34856
_camel_killer
train
def _camel_killer(attr): """ CamelKiller, qu'est-ce que c'est? Taken from http://stackoverflow.com/a/1176023/3244542 """ try: attr = str(attr) except UnicodeEncodeError: attr = attr.encode("utf-8", "ignore") s1 = _first_cap_re.sub(r'\1_\2', attr) s2 = _all_cap_re.sub(r'...
python
{ "resource": "" }
q34857
_conversion_checks
train
def _conversion_checks(item, keys, box_config, check_only=False, pre_check=False): """ Internal use for checking if a duplicate safe attribute already exists :param item: Item to see if a dup exists :param keys: Keys to check against :param box_config: Easier to pass in than ...
python
{ "resource": "" }
q34858
Box.box_it_up
train
def box_it_up(self): """ Perform value lookup for all items in current dictionary, generating all sub Box objects, while also running `box_it_up` on any of those sub box objects. """ for k in self: _conversion_checks(k, self.keys(), self._box_config, ...
python
{ "resource": "" }
q34859
Box.to_dict
train
def to_dict(self): """ Turn the Box and sub Boxes back into a native python dictionary. :return: python dictionary of this Box """ out_dict = dict(self) for k, v in out_dict.items(): if v is self: out_dict[k] = out_dict eli...
python
{ "resource": "" }
q34860
Box.to_json
train
def to_json(self, filename=None, encoding="utf-8", errors="strict", **json_kwargs): """ Transform the Box object into a JSON string. :param filename: If provided will save to file :param encoding: File encoding :param errors: How to handle encoding errors ...
python
{ "resource": "" }
q34861
Box.from_json
train
def from_json(cls, json_string=None, filename=None, encoding="utf-8", errors="strict", **kwargs): """ Transform a json object string into a Box object. If the incoming json is a list, you must use BoxList.from_json. :param json_string: string to pass to `json.loads` ...
python
{ "resource": "" }
q34862
BoxList.to_json
train
def to_json(self, filename=None, encoding="utf-8", errors="strict", multiline=False, **json_kwargs): """ Transform the BoxList object into a JSON string. :param filename: If provided will save to file :param encoding: File encoding :param errors: ...
python
{ "resource": "" }
q34863
ConfigBox.bool
train
def bool(self, item, default=None): """ Return value of key as a boolean :param item: key of value to transform :param default: value to return if item does not exist :return: approximated bool of value """ try: item = self.__getattr__(item) except At...
python
{ "resource": "" }
q34864
ConfigBox.int
train
def int(self, item, default=None): """ Return value of key as an int :param item: key of value to transform :param default: value to return if item does not exist :return: int of value """ try: item = self.__getattr__(item) except AttributeError as er...
python
{ "resource": "" }
q34865
ConfigBox.float
train
def float(self, item, default=None): """ Return value of key as a float :param item: key of value to transform :param default: value to return if item does not exist :return: float of value """ try: item = self.__getattr__(item) except AttributeError ...
python
{ "resource": "" }
q34866
Module.load_from_file
train
def load_from_file(filepath): """ Return user-written class object from given path. """ class_inst = None expected_class = "Py3status" module_name, file_ext = os.path.splitext(os.path.split(filepath)[-1]) if file_ext.lower() == ".py": py_mod = imp.load...
python
{ "resource": "" }
q34867
Module.load_from_namespace
train
def load_from_namespace(module_name): """ Load a py3status bundled module. """ class_inst = None name = "py3status.modules.{}".format(module_name) py_mod = __import__(name) components = name.split(".") for comp in components[1:]: py_mod = getat...
python
{ "resource": "" }
q34868
Module.prepare_module
train
def prepare_module(self): """ Ready the module to get it ready to start. """ # Modules can define a post_config_hook() method which will be run # after the module has had it config settings applied and before it has # its main method(s) called for the first time. This al...
python
{ "resource": "" }
q34869
Module.runtime_error
train
def runtime_error(self, msg, method): """ Show the error in the bar """ if self.testing: self._py3_wrapper.report_exception(msg) raise KeyboardInterrupt if self.error_hide: self.hide_errors() return # only show first line ...
python
{ "resource": "" }
q34870
Module.error_output
train
def error_output(self, message, method_affected=None): """ Something is wrong with the module so we want to output the error to the i3bar """ color_fn = self._py3_wrapper.get_config_attribute color = color_fn(self.module_full_name, "color_error") if hasattr(color,...
python
{ "resource": "" }
q34871
Module.hide_errors
train
def hide_errors(self): """ hide the module in the i3bar """ for method in self.methods.values(): method["last_output"] = {} self.allow_config_clicks = False self.error_hide = True self.set_updated()
python
{ "resource": "" }
q34872
Module.start_module
train
def start_module(self): """ Start the module running. """ self.prepare_module() if not (self.disabled or self.terminated): # Start the module and call its output method(s) self._py3_wrapper.log("starting module %s" % self.module_full_name) self...
python
{ "resource": "" }
q34873
Module.force_update
train
def force_update(self): """ Forces an update of the module. """ if self.disabled or self.terminated or not self.enabled: return # clear cached_until for each method to allow update for meth in self.methods: self.methods[meth]["cached_until"] = time...
python
{ "resource": "" }
q34874
Module.set_updated
train
def set_updated(self): """ Mark the module as updated. We check if the actual content has changed and if so we trigger an update in py3status. """ # get latest output output = [] for method in self.methods.values(): data = method["last_output"]...
python
{ "resource": "" }
q34875
Module._params_type
train
def _params_type(self, method_name, instance): """ Check to see if this is a legacy method or shiny new one legacy update method: def update(self, i3s_output_list, i3s_config): ... new update method: def update(self): ... ...
python
{ "resource": "" }
q34876
Module.click_event
train
def click_event(self, event): """ Execute the 'on_click' method of this module with the given event. """ # we can prevent request that a refresh after the event has happened # by setting this to True. Modules should do this via # py3.prevent_refresh() self.preven...
python
{ "resource": "" }
q34877
Module.add_udev_trigger
train
def add_udev_trigger(self, trigger_action, subsystem): """ Subscribe to the requested udev subsystem and apply the given action. """ if self._py3_wrapper.udev_monitor.subscribe(self, trigger_action, subsystem): if trigger_action == "refresh_and_freeze": # FIXM...
python
{ "resource": "" }
q34878
Py3status._get_events
train
def _get_events(self): """ Fetches events from the calendar into a list. Returns: The list of events. """ self.last_update = datetime.datetime.now() time_min = datetime.datetime.utcnow() time_max = time_min + datetime.timedelta(hours=self.events_within_hours) ...
python
{ "resource": "" }
q34879
Py3status._check_warn_threshold
train
def _check_warn_threshold(self, time_to, event_dict): """ Checks if the time until an event starts is less than or equal to the warn_threshold. If True, issue a warning with self.py3.notify_user. """ if time_to["total_minutes"] <= self.warn_threshold: warn_message = s...
python
{ "resource": "" }
q34880
Py3status._build_response
train
def _build_response(self): """ Builds the composite reponse to be output by the module by looping through all events and formatting the necessary strings. Returns: A composite containing the individual response for each event. """ responses = [] self.event_urls =...
python
{ "resource": "" }
q34881
Py3status.google_calendar
train
def google_calendar(self): """ The method that outputs the response. First, we check credential authorization. If no authorization, we display an error message, and try authorizing again in 5 seconds. Otherwise, we fetch the events, build the response, and output the re...
python
{ "resource": "" }
q34882
parse_list_or_docstring
train
def parse_list_or_docstring(options, sps): """ Handle py3-cmd list and docstring options. """ import py3status.docstrings as docstrings # HARDCODE: make include path to search for user modules home_path = os.path.expanduser("~") xdg_home_path = os.environ.get("XDG_CONFIG_HOME", "{}/.config"...
python
{ "resource": "" }
q34883
send_command
train
def send_command(): """ Run a remote command. This is called via py3-cmd utility. We look for any uds sockets with the correct name prefix and send our command to all that we find. This allows us to communicate with multiple py3status instances. """ def verbose(msg): """ p...
python
{ "resource": "" }
q34884
CommandRunner.run_command
train
def run_command(self, data): """ check the given command and send to the correct dispatcher """ command = data.get("command") if self.debug: self.py3_wrapper.log("Running remote command %s" % command) if command == "refresh": self.refresh(data) ...
python
{ "resource": "" }
q34885
CommandServer.kill
train
def kill(self): """ Remove the socket as it is no longer needed. """ try: os.unlink(self.server_address) except OSError: if os.path.exists(self.server_address): raise
python
{ "resource": "" }
q34886
CommandServer.run
train
def run(self): """ Main thread listen to socket and send any commands to the CommandRunner. """ while True: try: data = None # Wait for a connection if self.debug: self.py3_wrapper.log("waiting for a ...
python
{ "resource": "" }
q34887
Py3status._change_volume
train
def _change_volume(self, increase): """Change volume using amixer """ sign = "+" if increase else "-" delta = "%d%%%s" % (self.volume_tick, sign) self._run(["amixer", "-q", "sset", "Master", delta])
python
{ "resource": "" }
q34888
Py3status._detect_running_player
train
def _detect_running_player(self): """Detect running player process, if any """ supported_players = self.supported_players.split(",") running_players = [] for pid in os.listdir("/proc"): if not pid.isdigit(): continue fn = os.path.join("/pr...
python
{ "resource": "" }
q34889
Py3status._set_cycle_time
train
def _set_cycle_time(self): """ Set next cycle update time synced to nearest second or 0.1 of second. """ now = time() try: cycle_time = now - self._cycle_time if cycle_time < 0: cycle_time = 0 except AttributeError: cycl...
python
{ "resource": "" }
q34890
Py3status._get_current_output
train
def _get_current_output(self): """ Get child modules output. """ output = [] for item in self.items: out = self.py3.get_output(item) if out and "separator" not in out[-1]: out[-1]["separator"] = True output += out return...
python
{ "resource": "" }
q34891
Py3status.rainbow
train
def rainbow(self): """ Make a rainbow! """ if not self.items: return {"full_text": "", "cached_until": self.py3.CACHE_FOREVER} if time() >= self._cycle_time - (self.cycle_time / 10): self.active_color = (self.active_color + 1) % len(self.colors) ...
python
{ "resource": "" }
q34892
get_color_for_name
train
def get_color_for_name(module_name): """ Create a custom color for a given string. This allows the screenshots to each have a unique color but also for that color to be consistent. """ # all screenshots of the same module should be a uniform color module_name = module_name.split("-")[0] ...
python
{ "resource": "" }
q34893
contains_bad_glyph
train
def contains_bad_glyph(glyph_data, data): """ Pillow only looks for glyphs in the font used so we need to make sure our font has the glygh. Although we could substitute a glyph from another font eg symbola but this adds more complexity and is of limited value. """ def check_glyph(char): ...
python
{ "resource": "" }
q34894
create_screenshot
train
def create_screenshot(name, data, path, font, is_module): """ Create screenshot of py3status output and save to path """ desktop_color = get_color_for_name(name) # if this screenshot is for a module then add modules name etc if is_module: data.append( {"full_text": name.spli...
python
{ "resource": "" }
q34895
create_screenshots
train
def create_screenshots(quiet=False): """ create screenshots for all core modules. The screenshots directory will have all .png files deleted before new shots are created. """ if os.environ.get("READTHEDOCS") == "True": path = "../doc/screenshots" else: path = os.path.join( ...
python
{ "resource": "" }
q34896
ConfigParser.check_child_friendly
train
def check_child_friendly(self, name): """ Check if a module is a container and so can have children """ name = name.split()[0] if name in self.container_modules: return root = os.path.dirname(os.path.realpath(__file__)) module_path = os.path.join(root,...
python
{ "resource": "" }
q34897
ConfigParser.check_module_name
train
def check_module_name(self, name, offset=0): """ Checks a module name eg. some i3status modules cannot have an instance name. """ if name in ["general"]: return split_name = name.split() if len(split_name) > 1 and split_name[0] in I3S_SINGLE_NAMES: ...
python
{ "resource": "" }
q34898
ConfigParser.error
train
def error(self, msg, previous=False): """ Raise a ParseException. We provide information to help locate the error in the config to allow easy config debugging for users. previous indicates that the error actually occurred at the end of the previous line. """ toke...
python
{ "resource": "" }
q34899
ConfigParser.tokenize
train
def tokenize(self, config): """ Break the config into a series of tokens """ tokens = [] reg_ex = re.compile(self.TOKENS[0], re.M | re.I) for token in re.finditer(reg_ex, config): value = token.group(0) if token.group("operator"): ...
python
{ "resource": "" }