output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Create a new instance of Selenium Webdriver.
Given the following Python 3 function, write the documentation def new_driver(self, testname=None): ''' Used at a start of a test to get a new instance of WebDriver. If the 'resuebrowser' setting is true, it will use a recycled WebDriver instance with delete_all_cookies() called. ...
You are a Python code analyst, evaluating scripts for potential improvements.
def __register_driver(self, channel, webdriver): "Register webdriver to a channel." # Add to list of webdrivers to cleanup. if not self.__registered_drivers.has_key(channel): self.__registered_drivers[channel] = [] # set to new empty array self.__registered_drivers[channel...
Write a Python 3 script to register webdriver to a channel.
You are a Python code generator, capable of creating scripts from specifications.
Get the channel to register webdriver to.
Here you have a function in Python 3, explain what it does def __get_channel(self): "Get the channel to register webdriver to." if self.__config.get(WebDriverManager.ENABLE_THREADING_SUPPORT, False): channel = current_thread().ident else: channel = 0 return chann...
As a Python code composer, you craft elegant and concise scripts.
Captures a screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as.
Make a summary of the following Python 3 code def take_screenshot(webdriver, file_name): folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_l...
You are a Python code generator, capable of creating scripts from specifications.
Takes a screenshot as a reference screenshot.
Make a summary of the following Python 3 code def take_reference_screenshot(webdriver, file_name): folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( ...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the project root directory.
How would you explain what the following Python 3 function does def get_project_root(cls): ''' Return path of the project directory. Use this method for getting paths relative to the project. However, for data, it's recommended you use WTF_DATA_MANAGER and for assets it's recommended t...
As a Python code composer, you craft elegant and concise scripts.
A retry wrapper that will keep performing the action until the function evaluates True.
Explain what the following Python 3 code does def do_until(lambda_expr, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, message=None): ''' A retry wrapper that'll keep performing the action until it succeeds. (main differnce between do_until and wait_until is do_until will keep trying until a value is r...
As a Python code composer, you craft elegant and concise scripts.
def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): ''' Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: time...
Can you write a function in Python 3 where it waits until condition is met and returns the result.
As a Python code analyst, you investigate and solve complex coding mysteries
def wait_until(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, pass_exceptions=False, message=None): ''' Waits wrapper that'll wait for the condition to become true. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will w...
How would you implement a function in Python 3 that waits until a condition is true.
You are a Python code architect, reviewing and designing scalable and efficient code
def check_email_exists_by_subject(self, subject, match_recipient=None): """ Searches for Email by Subject. Returns True or False. Args: subject (str): Subject to search for. Kwargs: match_recipient (str) : Recipient to match exactly. (don't care if not specifie...
How would you code a function in Python 3 to search for an email by Subject. Returns True or False.
As a Python code translator, you convert algorithms and pseudocode into Python.
def find_emails_by_subject(self, subject, limit=50, match_recipient=None): """ Searches for Email by Subject. Returns email's imap message IDs as a list if matching subjects is found. Args: subject (str) - Subject to search for. Kwargs: limit (int) - L...
Write a Python 3 function that can search for Email by Subject. Returns a list of Integers representing the email s UIDs if matching subjects is found.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_email_message(self, message_uid, message_type="text/plain"): """ Fetch contents of email. Args: message_uid (int): IMAP Message UID number. Kwargs: message_type: Can be 'text' or 'html' """ self._mail.select("inbox") result = sel...
How would you implement a function in Python 3 that fetches contents of an email.
As a Python code composer, you craft elegant and concise scripts.
def raw_search(self, *args, **kwargs): """ Find the a set of emails matching each regular expression passed in against the (RFC822) content. Args: *args: list of regular expressions. Kwargs: limit (int) - Limit to how many of the most resent emails to search thr...
Write a Python 3 function for finding the a set of emails matching each regular expression passed in against the (RFC822) content. Args: *args: list of regular expressions. Kwargs: limit (int) - Limit to how many of the most resent emails to search through. date (datetime) - If specified, it will filter avoid checking ...
You are a Python code analyst, evaluating scripts for potential improvements.
def __search_email_by_subject(self, subject, match_recipient): "Get a list of message numbers" if match_recipient is None: _, data = self._mail.uid('search', None, '(HEADER SUBJECT "{subject}")' ...
Implement a Python 3 function for getting a list of message numbers
As a Python code analyst, you investigate and solve complex coding mysteries
def get(self, key, default_value=__NoDefaultSpecified__): ''' Gets the value from the yaml config based on the key. No type casting is performed, any type casting should be performed by the caller. Args: key (str) - Config setting key. Kwargs: ...
Implement a Python 3 function for getting the value from the yaml config file based on the key.
As a python code expert, you are capable of creating scripts from specifications.
Generate page object from URL
How would you explain what the following Python 3 function does def generate_page_object(page_name, url): "Generate page object from URL" # Attempt to extract partial URL for verification. url_with_path = u('^.*//[^/]+([^?]+)?|$') try: match = re.match(url_with_path, url) partial_url = ...
You are a Python code generator, capable of creating scripts from specifications.
def get_data_path(self, filename, env_prefix=None): """ Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: ...
Can you write a function in Python 3 where it gets data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAGER.get_data_path('testdata.csv') Note:...
You are a Python code generator, capable of creating scripts from specifications.
Gets next entry as a dictionary.
Here you have a function in Python 3, explain what it does def next(self): try: entry = {} row = self._csv_reader.next() for i in range(0, len(row)): entry[self._headers[i]] = row[i] return entry except Exception as e: # close ...
You are a Python code analyst, evaluating scripts for potential improvements.
Utility method makes it easier to find an element using multiple selectors. This method will return a new element if the element is found.
Explain what the following Python 3 code does def find_element_by_selectors(webdriver, *selectors): # perform initial check to verify selectors are valid by statements. for selector in selectors: (by_method, value) = selector if not WebElementSelector.__is_valid_by_type(by_method...
You are a Python code analyst, evaluating scripts for potential improvements.
Wait until an element is not visible.
Here you have a function in Python 3, explain what it does def wait_until_element_not_visible(webdriver, locator_lambda_expression, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): """ Wait for a WebElement to disappear. Args: webdriver (Webdriv...
As a Python code translator, you convert algorithms and pseudocode into Python.
Check if an image is loaded.
Can you generate a brief explanation for the following Python 3 code def is_image_loaded(webdriver, webelement): ''' Check if an image (in an image tag) is loaded. Note: This call will not work against background images. Only Images in <img> tags. Args: webelement (WebEleme...
You are a Python code architect, reviewing and designing scalable and efficient code
def generate_timestamped_string(subject="test", number_of_random_chars=4): """ Generate time-stamped string. Format as follows... `2013-01-31_14:12:23_SubjectString_a3Zg` Kwargs: subject (str): String to use as subject. number_of_random_chars (int) : Number of random characters to app...
Implement a Python 3 function for generating a time - stamped string.
You are a Python code generator, capable of creating scripts from specifications.
Generates a series of random characters.
Explain what the following Python 3 code does def generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters): return u('').join(random.choice(character_set) for _ in range(number_of_random_chars))
You are a Python code architect, reviewing and designing scalable and efficient code
def convert_weka_to_py_date_pattern(p): """ Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime(). """ # https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior # https://www.cs.waikato.ac.nz/ml/weka/arff.html p = p.repla...
Write a Python 3 function for converting the date format pattern used by Weka to the date format pattern used by Python s datetime. strftime.
As a Python code composer, you craft elegant and concise scripts.
Returns the value associated with the given value index.
How would you explain what the following Python 3 function does def get_attribute_value(self, name, index): if index == MISSING: return elif self.attribute_types[name] in NUMERIC_TYPES: at = self.attribute_types[name] if at == TYPE_INTEGER: return int(...
As a Python code analyst, you investigate and solve complex coding mysteries
def load(cls, filename, schema_only=False): """ Load an ARFF File from a file. """ o = open(filename) s = o.read() a = cls.parse(s, schema_only=schema_only) if not schema_only: a._filename = filename o.close() return a
Implement a Python 3 function for loading an ARFF File from a file.
You are a Python code generator, capable of creating scripts from specifications.
def parse(cls, s, schema_only=False): """ Parse an ARFF File already loaded into a string. """ a = cls() a.state = 'comment' a.lineno = 1 for l in s.splitlines(): a.parseline(l) a.lineno += 1 if schema_only and a.state == 'data'...
Can you write a function in Python 3 where it parses an ARFF File already loaded into a string.
You are a Python code analyst, evaluating scripts for potential improvements.
def copy(self, schema_only=False): """ Creates a deepcopy of the instance. If schema_only is True, the data will be excluded from the copy. """ o = type(self)() o.relation = self.relation o.attributes = list(self.attributes) o.attribute_types = self.attrib...
Write a Python 3 function that can create a deep copy of the instance.
As a Python code composer, you craft elegant and concise scripts.
def open_stream(self, class_attr_name=None, fn=None): """ Save an arff structure to a file, leaving the file object open for writing of new data samples. This prevents you from directly accessing the data via Python, but when generating a huge file, this prevents all your data ...
How would you code a function in Python 3 to open the arff structure to a file.
You are a Python code analyst, evaluating scripts for potential improvements.
def close_stream(self): """ Terminates an open stream and returns the filename of the file containing the streamed data. """ if self.fout: fout = self.fout fout_fn = self.fout_fn self.fout.flush() self.fout.close() self....
Can you create a Python 3 function that terminates an open stream and returns the filename of the file containing the streamed data.
You are a Python code architect, reviewing and designing scalable and efficient code
def save(self, filename=None): """ Save an arff structure to a file. """ filename = filename or self._filename o = open(filename, 'w') o.write(self.write()) o.close()
Create a Python 3 function for saving an arff structure to a file.
You are a Python code analyst, evaluating scripts for potential improvements.
def write_line(self, d, fmt=SPARSE): """ Converts a single data line to a string. """ def smart_quote(s): if isinstance(s, basestring) and ' ' in s and s[0] != '"': s = '"%s"' % s return s if fmt == DENSE: #TOD...
Write a Python 3 script for converting a single data line into a string.
You are a Python code architect, reviewing and designing scalable and efficient code
Write an arff structure to a string.
Make a summary of the following Python 3 code def write(self, fout=None, fmt=SPARSE, schema_only=False, data_only=False): """ Write an arff structure to a string. """ assert not (schema_only and data_only), 'Make up your mind.' assert fmt in FORMAT...
As a Python code translator, you convert algorithms and pseudocode into Python.
def define_attribute(self, name, atype, data=None): """ Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'. For nominal attributes, pass the possible values as data. For date attributes, pass the format as data. """ ...
Create a Python 3 function to define a new attribute. atype has to be one of integer real numeric string date nominal or date. data can be a dictionary of data type and value.
As a python code expert, you are capable of creating scripts from specifications.
def dump(self): """Print an overview of the ARFF file.""" print("Relation " + self.relation) print(" With attributes") for n in self.attributes: if self.attribute_types[n] != TYPE_NOMINAL: print(" %s of type %s" % (n, self.attribute_types[n])) ...
How would you code a function in Python 3 to print an overview of the ARFF file.
You are a Python code generator, capable of creating scripts from specifications.
def alphabetize_attributes(self): """ Orders attributes names alphabetically, except for the class attribute, which is kept last. """ self.attributes.sort(key=lambda name: (name == self.class_attr_name, name))
Can you create a Python 3 function that sorts the attributes names alphabetically except for the class attribute which is kept last.
You are a Python code analyst, evaluating scripts for potential improvements.
Convert the color from RGB coordinates to HSL.
How would you explain what the following Python 3 function does def rgb_to_hsl(r, g=None, b=None): if type(r) in [list,tuple]: r, g, b = r minVal = min(r, g, b) # min RGB value maxVal = max(r, g, b) # max RGB value l = (maxVal + minVal) / 2.0 if minVal==maxVal: return (0.0, 0.0, l) # ...
As a Python code composer, you craft elegant and concise scripts.
Convert the color from HSL coordinates to RGB.
Can you tell what is the following Python 3 function doing def hsl_to_rgb(h, s=None, l=None): if type(h) in [list,tuple]: h, s, l = h if s==0: return (l, l, l) # achromatic (gray) if l<0.5: n2 = l * (1.0 + s) else: n2 = l+s - (l*s) n1 = (2.0 * l) - n2 h /= 60.0 hueToRgb = _hue_to_rgb r = hueTo...
As a Python code analyst, you investigate and solve complex coding mysteries
Convert the color from RGB coordinates to HSV.
Can you tell what is the following Python 3 function doing def rgb_to_hsv(r, g=None, b=None): if type(r) in [list,tuple]: r, g, b = r v = float(max(r, g, b)) d = v - min(r, g, b) if d==0: return (0.0, 0.0, v) s = d / v dr, dg, db = [(v - val) / d for val in (r, g, b)] if r==v: h = db - dg ...
You are a Python code analyst, evaluating scripts for potential improvements.
Convert the color from RGB coordinates to HSV.
How would you explain what the following Python 3 function does def hsv_to_rgb(h, s=None, v=None): if type(h) in [list,tuple]: h, s, v = h if s==0: return (v, v, v) # achromatic (gray) h /= 60.0 h = h % 6.0 i = int(h) f = h - i if not(i&1): f = 1-f # if i is even m = v * (1.0 - s) n = v ...
You are a Python code architect, reviewing and designing scalable and efficient code
Convert the color from RGB to YIQ.
How would you explain what the following Python 3 function does def rgb_to_yiq(r, g=None, b=None): if type(r) in [list,tuple]: r, g, b = r y = (r * 0.29895808) + (g * 0.58660979) + (b *0.11443213) i = (r * 0.59590296) - (g * 0.27405705) - (b *0.32184591) q = (r * 0.21133576) - (g * 0.52263517) + (b *0.3112...
You are a Python code architect, reviewing and designing scalable and efficient code
def yiq_to_rgb(y, i=None, q=None): """Convert the color from YIQ coordinates to RGB. Parameters: :y: Tte Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0......
Can you create a Python 3 function that converts the color from YIQ coordinates to RGB.
You are a Python code generator, capable of creating scripts from specifications.
Convert the color from RGB coordinates to YUV.
Can you generate a brief explanation for the following Python 3 code def rgb_to_yuv(r, g=None, b=None): if type(r) in [list,tuple]: r, g, b = r y = (r * 0.29900) + (g * 0.58700) + (b * 0.11400) u = -(r * 0.14713) - (g * 0.28886) + (b * 0.43600) v = (r * 0.61500) - (g * 0.51499) - (b * 0.10001) return (...
As a python code expert, you are capable of creating scripts from specifications.
def yuv_to_rgb(y, u=None, v=None): """Convert the color from YUV coordinates to RGB. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] Returns: The color as an (r, g, b) tuple in the range: r[...
Write a Python 3 script to convert the color from YUV coordinates to RGB.
You are a Python code generator, capable of creating scripts from specifications.
Convert the color from sRGB to XYZ.
Explain what the following Python 3 code does def rgb_to_xyz(r, g=None, b=None): if type(r) in [list,tuple]: r, g, b = r r, g, b = [((v <= 0.03928) and [v / 12.92] or [((v+0.055) / 1.055) **2.4])[0] for v in (r, g, b)] x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805) y = (r * 0.2126) + (g * 0.7152) + (b * 0...
As a Python code translator, you convert algorithms and pseudocode into Python.
Converts the color from CIE XYZ coordinates to sRGB.
Can you generate a brief explanation for the following Python 3 code def xyz_to_rgb(x, y=None, z=None): if type(x) in [list,tuple]: x, y, z = x r = (x * 3.2406255) - (y * 1.5372080) - (z * 0.4986286) g = -(x * 0.9689307) + (y * 1.8757561) + (z * 0.0415175) b = (x * 0.0557101) - (y * 0.2040211) + (z * 1.05...
As a Python code translator, you convert algorithms and pseudocode into Python.
def xyz_to_lab(x, y=None, z=None, wref=_DEFAULT_WREF): """Convert the color from CIE XYZ to CIE L*a*b*. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] :wref: The whitepoint reference, default is 2° D65. Re...
How would you implement a function in Python 3 that converts the color from CIE XYZ to lab.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert the color from CIE L a * b * to CIE 1931 XYZ.
Here you have a function in Python 3, explain what it does def lab_to_xyz(l, a=None, b=None, wref=_DEFAULT_WREF): if type(l) in [list,tuple]: l, a, b = l y = (l + 16) / 116 x = (a / 5.0) + y z = y - (b / 2.0) return tuple((((v > 0.206893) and [v**3] or [(v - _sixteenHundredsixteenth) / 7.787])[0] * w for ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert the color from CMYK coordinates to CMY.
Make a summary of the following Python 3 code def cmyk_to_cmy(c, m=None, y=None, k=None): if type(c) in [list,tuple]: c, m, y, k = c mk = 1-k return ((c*mk + k), (m*mk + k), (y*mk + k))
As a Python code composer, you craft elegant and concise scripts.
def cmy_to_cmyk(c, m=None, y=None): """Convert the color from CMY coordinates to CMYK. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (c, m, y, k) tuple in the range: c...
Can you create a Python 3 function that converts the color from CMY coordinates to CMYK.
You are a Python code architect, reviewing and designing scalable and efficient code
def rgb_to_cmy(r, g=None, b=None): """Convert the color from RGB coordinates to CMY. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (c, m, y) tuple in the range: c[0...1], ...
Implement a function in Python 3 to convert the color from RGB coordinates to CMY.
You are a Python code analyst, evaluating scripts for potential improvements.
Convert the color from CMY coordinates to RGB.
Make a summary of the following Python 3 code def cmy_to_rgb(c, m=None, y=None): if type(c) in [list,tuple]: c, m, y = c return (1-c, 1-m, 1-y)
You are a Python code analyst, evaluating scripts for potential improvements.
Convert the color in the standard [ 0... 255 ] range to ints in the [ 0... 255 ] range.
Make a summary of the following Python 3 code def rgb_to_ints(r, g=None, b=None): if type(r) in [list,tuple]: r, g, b = r return tuple(int(round(v*255)) for v in (r, g, b))
As a Python code analyst, you investigate and solve complex coding mysteries
def ints_to_rgb(r, g=None, b=None): """Convert ints in the [0...255] range to the standard [0...1] range. Parameters: :r: The Red component value [0...255] :g: The Green component value [0...255] :b: The Blue component value [0...255] Returns: The color as an (r, g, b) tuple in...
How would you code a function in Python 3 to convert ints in the 0... 255 range to the standard [ 0... 1 ] range.
You are a Python code analyst, evaluating scripts for potential improvements.
Convert the color from rgb to html.
Can you tell what is the following Python 3 function doing def rgb_to_html(r, g=None, b=None): if type(r) in [list,tuple]: r, g, b = r return '#%02x%02x%02x' % tuple((min(round(v*255), 255) for v in (r, g, b)))
You are a Python code analyst, evaluating scripts for potential improvements.
def html_to_rgb(html): """Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither...
How would you code a function in Python 3 to convert the HTML color to RGB.
You are a Python code architect, reviewing and designing scalable and efficient code
Convert the color from RGB to PIL - compatible integer.
Here you have a function in Python 3, explain what it does def rgb_to_pil(r, g=None, b=None): if type(r) in [list,tuple]: r, g, b = r r, g, b = [min(int(round(v*255)), 255) for v in (r, g, b)] return (b << 16) + (g << 8) + r
You are a Python code analyst, evaluating scripts for potential improvements.
def pil_to_rgb(pil): """Convert the color from a PIL-compatible integer to RGB. Parameters: pil: a PIL compatible color representation (0xBBGGRR) Returns: The color as an (r, g, b) tuple in the range: the range: r: [0...1] g: [0...1] b: [0...1] >>> '(%g, %g, %g)' % pil_to_rgb(0x0080ff)...
Implement a Python 3 function for converting the color from a PIL - compatible integer to RGB.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert a color component to its web safe equivalent.
Can you generate a brief explanation for the following Python 3 code def _websafe_component(c, alt=False): # This sucks, but floating point between 0 and 1 is quite fuzzy... # So we just change the scale a while to make the equality tests # work, otherwise it gets wrong at some decimal far to the right. sc = c ...
You are a Python code generator, capable of creating scripts from specifications.
def rgb_to_websafe(r, g=None, b=None, alt=False): """Convert the color from RGB to 'web safe' RGB Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alt: If True, use the alternative color instead of th...
Create a Python 3 function for converting the color from RGB to web safe RGB
As a python code expert, you are capable of creating scripts from specifications.
def rgb_to_greyscale(r, g=None, b=None): """Convert the color from RGB to its greyscale equivalent Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: ...
Write a Python 3 script to convert the color from RGB to its greyscale equivalent.
As a Python code composer, you craft elegant and concise scripts.
def rgb_to_ryb(hue): """Maps a hue on the RGB color wheel to Itten's RYB wheel. Parameters: :hue: The hue on the RGB color wheel [0...360] Returns: An approximation of the corresponding hue on Itten's RYB wheel. >>> rgb_to_ryb(15) 26.0 """ d = hue % 15 i = int(hue / 15) x0 = _RybWhee...
Implement a function in Python 3 to map a hue on the RGB color wheel to Itten s RYB wheel.
As a Python code analyst, you investigate and solve complex coding mysteries
Maps a hue on Itten s RYB color wheel to the standard RGB wheel.
Make a summary of the following Python 3 code def ryb_to_rgb(hue): d = hue % 15 i = int(hue / 15) x0 = _RgbWheel[i] x1 = _RgbWheel[i+1] return x0 + (x1-x0) * d / 15
You are a Python code generator, capable of creating scripts from specifications.
Create a new instance based on the specifed RGB values.
Here you have a function in Python 3, explain what it does def from_rgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF): return Color((r, g, b), 'rgb', alpha, wref)
You are a Python code analyst, evaluating scripts for potential improvements.
Create a new instance based on the specifed HSL values.
Can you generate the documentation for the following Python 3 function def from_hsl(h, s, l, alpha=1.0, wref=_DEFAULT_WREF): return Color((h, s, l), 'hsl', alpha, wref)
You are a Python code architect, reviewing and designing scalable and efficient code
def from_hsv(h, s, v, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed HSV values. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] :alpha: The color t...
Create a Python 3 function for creating a new instance based on the specifed HSV values.
As a Python code analyst, you investigate and solve complex coding mysteries
def from_yiq(y, i, q, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed YIQ values. Parameters: :y: The Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] :alpha: The color transparen...
Can you write a function in Python 3 where it creates a new instance based on the specifed YIQ values.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a new instance based on the specifed YUV values.
Given the following Python 3 function, write the documentation def from_yuv(y, u, v, alpha=1.0, wref=_DEFAULT_WREF): return Color(yuv_to_rgb(y, u, v), 'rgb', alpha, wref)
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a new Color instance based on the specifed CIE - XYZ values.
Explain what the following Python 3 code does def from_xyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF): return Color(xyz_to_rgb(x, y, z), 'rgb', alpha, wref)
As a Python code translator, you convert algorithms and pseudocode into Python.
def from_lab(l, a, b, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0...1]...
Write a Python 3 function for creating a new Color instance based on the specifed CIE - LAB values.
You are a Python code generator, capable of creating scripts from specifications.
Create a new instance based on the specifed CMY values.
Here you have a function in Python 3, explain what it does def from_cmy(c, m, y, alpha=1.0, wref=_DEFAULT_WREF): return Color(cmy_to_rgb(c, m, y), 'rgb', alpha, wref)
As a Python code composer, you craft elegant and concise scripts.
def from_cmyk(c, m, y, k, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CMYK values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The B...
Can you create a Python 3 function that creates a new instance based on the specifed CMYK values.
You are a Python code generator, capable of creating scripts from specifications.
Create a new instance based on the specifed HTML color definition.
Given the following Python 3 function, write the documentation def from_html(html, alpha=1.0, wref=_DEFAULT_WREF): return Color(html_to_rgb(html), 'rgb', alpha, wref)
You are a Python code analyst, evaluating scripts for potential improvements.
def from_pil(pil, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed PIL color. Parameters: :pil: A PIL compatible color representation (0xBBGGRR) :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, def...
Can you create a Python 3 function that creates a new instance based on the specified PIL color representation.
As a Python code analyst, you investigate and solve complex coding mysteries
Create a new instance based on this one with a new white reference.
Given the following Python 3 function, write the documentation def with_white_ref(self, wref, labAsRef=False): if labAsRef: l, a, b = self.lab return Color.from_lab(l, a, b, self.__a, wref) else: return Color(self.__rgb, 'rgb', self.__a, wref)
You are a Python code analyst, evaluating scripts for potential improvements.
Create a new instance based on this one but less saturated.
Can you generate the documentation for the following Python 3 function def desaturate(self, level): h, s, l = self.__hsl return Color((h, max(s - level, 0), l), 'hsl', self.__a, self.__wref)
You are a Python code generator, capable of creating scripts from specifications.
Return the two websafe colors nearest to this one.
Here you have a function in Python 3, explain what it does def websafe_dither(self): return ( Color(rgb_to_websafe(*self.__rgb), 'rgb', self.__a, self.__wref), Color(rgb_to_websafe(alt=True, *self.__rgb), 'rgb', self.__a, self.__wref))
As a Python code translator, you convert algorithms and pseudocode into Python.
def complementary_color(self, mode='ryb'): """Create a new instance which is the complementary color of this one. Parameters: :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 1, 0.5).complementary_co...
Write a Python 3 script to create a new instance which is the complementary color of this one.
You are a Python code analyst, evaluating scripts for potential improvements.
Return two colors analogous to this one.
Make a summary of the following Python 3 code def make_analogous_scheme(self, angle=30, mode='ryb'): h, s, l = self.__hsl if mode == 'ryb': h = rgb_to_ryb(h) h += 360 h1 = (h - angle) % 360 h2 = (h + angle) % 360 if mode == 'ryb': h1 = ryb_to_rgb(h1) h2 = ryb_to_rgb(h2) return ...
As a Python code translator, you convert algorithms and pseudocode into Python.
blends this color with the other one.
How would you explain what the following Python 3 function does def blend(self, other, percent=0.5): dest = 1.0 - percent rgb = tuple(((u * percent) + (v * dest) for u, v in zip(self.__rgb, other.__rgb))) a = (self.__a * percent) + (other.__a * dest) return Color(rgb, 'rgb', a, self.__wref)
As a Python code analyst, you investigate and solve complex coding mysteries
Parse command - line arguments.
Make a summary of the following Python 3 code def get_parser(): parser = ArgumentParser(description='a command-line web scraping tool') parser.add_argument('query', metavar='QUERY', type=str, nargs='*', help='URLs/files to scrape') parser.add_argument('-a', '--attributes', type=str, ...
As a python code expert, you are capable of creating scripts from specifications.
def write_files(args, infilenames, outfilename): """Write scraped or local file(s) in desired format. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- name of output file (str) Remove PART(#).html files afte...
How would you code a function in Python 3 to write scraped or local file(s ) in desired format.
You are a Python code analyst, evaluating scripts for potential improvements.
def write_single_file(args, base_dir, crawler): """Write to a single output file and/or subdirectory.""" if args['urls'] and args['html']: # Create a directory to save PART.html files in domain = utils.get_domain(args['urls'][0]) if not args['quiet']: print('Storing html file...
Write a Python 3 script to write to a single output file and or a subdirectory.
You are a Python code analyst, evaluating scripts for potential improvements.
def write_multiple_files(args, base_dir, crawler): """Write to multiple output files and/or subdirectories.""" for i, query in enumerate(args['query']): if query in args['files']: # Write files if args['out'] and i < len(args['out']): outfilename = args['out'][i] ...
Write a Python 3 function for writing to multiple output files and or subdirectories.
You are a Python code architect, reviewing and designing scalable and efficient code
def split_input(args): """Split query input into local files and URLs.""" args['files'] = [] args['urls'] = [] for arg in args['query']: if os.path.isfile(arg): args['files'].append(arg) else: args['urls'].append(arg.strip('/'))
Write a Python 3 function that can split query input into local files and URLs.
As a Python code composer, you craft elegant and concise scripts.
Detect whether to save to a single or multiple files.
Make a summary of the following Python 3 code def detect_output_type(args): if not args['single'] and not args['multiple']: # Save to multiple files if multiple files/URLs entered if len(args['query']) > 1 or len(args['out']) > 1: args['multiple'] = True else: args['s...
You are a Python code generator, capable of creating scripts from specifications.
def prompt_filetype(args): """Prompt user for filetype if none specified.""" valid_types = ('print', 'text', 'csv', 'pdf', 'html') if not any(args[x] for x in valid_types): try: filetype = input('Print or save output as ({0}): ' .format(', '.join(valid_types)...
Write a Python 3 script for prompting user for filetype if none specified.
As a Python code composer, you craft elegant and concise scripts.
Prompt user to save images when crawling.
Can you generate a brief explanation for the following Python 3 code def prompt_save_images(args): if args['images'] or args['no_images']: return if (args['pdf'] or args['html']) and (args['crawl'] or args['crawl_all']): save_msg = ('Choosing to save images will greatly slow the' ...
As a Python code analyst, you investigate and solve complex coding mysteries
Handle command - line interaction.
How would you explain what the following Python 3 function does def command_line_runner(): parser = get_parser() args = vars(parser.parse_args()) if args['version']: print(__version__) return if args['clear_cache']: utils.clear_cache() print('Cleared {0}.'.format(utils.CA...
You are a Python code generator, capable of creating scripts from specifications.
def load_raw(cls, model_fn, schema, *args, **kwargs): """ Loads a trained classifier from the raw Weka model format. Must specify the model schema and classifier name, since these aren't currently deduced from the model format. """ c = cls(*args, **kwargs) c.schem...
Write a Python 3 function for loading a trained classifier from the raw Weka model format.
You are a Python code analyst, evaluating scripts for potential improvements.
def train(self, training_data, testing_data=None, verbose=False): """ Updates the classifier with new data. """ model_fn = None training_fn = None clean_training = False testing_fn = None clean_testing = False try: # Valida...
Can you write a function in Python 3 where it trains the classifier with new training data and test data.
As a python code expert, you are capable of creating scripts from specifications.
Predict the value of a class by running a Weka model and predicting it.
How would you explain what the following Python 3 function does def predict(self, query_data, verbose=False, distribution=False, cleanup=True): model_fn = None query_fn = None clean_query = False stdout = None try: # Validate query data. if is...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_training_coverage(self): """ Returns a ratio of classifiers that were able to be trained successfully. """ total = len(self.training_results) i = sum(1 for data in self.training_results.values() if not isinstance(data, basestring)) return i/float(total)
Write a Python 3 function for returning a ratio of classifiers that were able to be trained successfully.
As a python code expert, you are capable of creating scripts from specifications.
Get new links from a URL and filter them.
Given the following Python 3 function, write the documentation def get_new_links(self, url, resp): links_on_page = resp.xpath('//a/@href') links = [utils.clean_url(u, url) for u in links_on_page] # Remove non-links through filtering by protocol links = [x for x in links if utils.check_p...
As a Python code translator, you convert algorithms and pseudocode into Python.
Check if a page has been crawled by hashing its text content.
Given the following Python 3 function, write the documentation def page_crawled(self, page_resp): page_text = utils.parse_text(page_resp) page_hash = utils.hash_text(''.join(page_text)) if page_hash not in self.page_cache: utils.cache_page(self.page_cache, page_hash, self.args['cache...
You are a Python code architect, reviewing and designing scalable and efficient code
def crawl_links(self, seed_url=None): """Find new links given a seed URL and follow them breadth-first. Save page responses as PART.html files. Return the PART.html filenames created during crawling. """ if seed_url is not None: self.seed_url = seed_url if s...
How would you implement a function in Python 3 that crawls the page responses and creates PART. html files.
As a Python code composer, you craft elegant and concise scripts.
def get_proxies(): """Get available proxies to use with requests library.""" proxies = getproxies() filtered_proxies = {} for key, value in proxies.items(): if key.startswith('http://'): if not value.startswith('http://'): filtered_proxies[key] = 'http://{0}'.format(v...
Write a Python 3 script to get available proxies to use with requests library.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_resp(url): """Get webpage response as an lxml.html.HtmlElement object.""" try: headers = {'User-Agent': random.choice(USER_AGENTS)} try: request = requests.get(url, headers=headers, proxies=get_proxies()) except MissingSchema: url = add_protocol(url) ...
Write a Python 3 script to get webpage response as an lxml. html. HtmlElement object.
As a Python code translator, you convert algorithms and pseudocode into Python.
def enable_cache(): """Enable requests library cache.""" try: import requests_cache except ImportError as err: sys.stderr.write('Failed to enable cache: {0}\n'.format(str(err))) return if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR) requests_cache.install_cac...
Create a Python 3 function to enable requests library cache.
You are a Python code architect, reviewing and designing scalable and efficient code
def hash_text(text): """Return MD5 hash of a string.""" md5 = hashlib.md5() md5.update(text) return md5.hexdigest()
Create a Python 3 function to return MD5 hash of a string.
You are a Python code generator, capable of creating scripts from specifications.