text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self, *args, **kwargs): """Start the task. This is: * not threadsave * assumed to be called in the gtk mainloop """
args = (self.counter,) + args thread = threading.Thread( target=self._work_callback, args=args, kwargs=kwargs ) thread.setDaemon(self.daemon) thread.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_image_to_rgb_mode(image, fill_color=(255, 255, 255)): """ Convert the specified image instance to RGB mode. @param image: a Python Library Image (PIL) instance to convert its pixel format to RGB, discarding the alpha channel. @param fill_color: color to be used to fill transparent pixels when discaring the alpha channel. By default, the white color. @return: a Python Library Image instance with pixel format of RGB. """
if image.mode not in ('RGBA', 'LA'): return image # In most cases simply discarding the alpha channel will give # undesirable result, because transparent pixels also have some # unpredictable colors. It is much better to fill transparent pixels # with a specified color. background_image = Image.new(image.mode[:-1], image.size, fill_color) background_image.paste(image, image.split()[-1]) return background_image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_multiple_pixel_resolutions(image, pixel_resolutions, filter=Filter.NearestNeighbor, does_crop=False, crop_aligment=CropAlignment.center, match_orientation=False): """ Generate multiple resolution images of the given image. @param image: a Python Library Image (PIL) instance to generate multiple pixel resolutions from. @param pixel_resolutions: a list of tuples ``(logical_size, width, height)`` where: * ``logical_size``: string representation of the image size, such as, for instance, "thumbnail", "small", "medium", "large". * ``width``: positive integer corresponding to the number of pixel columns of the image. * ``height``: positive integer corresponding to the number of pixel rows. @param filter: indicate the filter to use when resizing the image. @param does_crop: indicate whether to crop each generated images. @param crop_alignment: if the image needs to be cropped, select which alignment to use when cropping. @param match_orientation: indicate whether the given canvas size should be inverted to match the orientation of the image. @return: an iterator, known as a generator, that returns a Python Library Image (PIL) instance each the generator is called. """
for (logical_size, width, height) in \ sorted(pixel_resolutions, key=lambda (l, w, h): w, reverse=True): yield (logical_size, resize_image(image, (width, height), filter=filter, does_crop=does_crop, crop_aligment=crop_aligment, match_orientation=match_orientation))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_exposure(image, filters=None): """ Determine the exposure of a photo, which can be under-exposed, normally exposed or over-exposed. @param image: a Python Library Image (PIL) object to determine the exposure. @param filters: a list of ``ColorComponentFilter`` filter or ``None`` to use all the filters. @return: an ``ExposureStatus`` instance that represents the exposure of the given PIL object. """
def _get_exposure(histogram): total = sum(histogram) range_offset = len(histogram) / 4 dark = float(sum(histogram[0:range_offset])) / total #normal = float(sum(histogram[range_offset:-range_offset])) / total light = float(sum(histogram[-range_offset:])) / total return PictureExposure.UnderExposed if dark > 0.5 and light < 0.5 \ else PictureExposure.OverExposed if dark < 0.5 and light > 0.5 \ else PictureExposure.NormallyExposed FILTER_SETTINGS = { ColorComponentFilter.Red: ('RGB', 0, 256), ColorComponentFilter.Green: ('RGB', 256, 512), ColorComponentFilter.Blue: ('RGB', 512, 768), ColorComponentFilter.Grey: ('L', 0, 256) } exposures = collections.defaultdict(int) for exposure in [ _get_exposure(image.convert(mode).histogram()[start_index:end_index]) for (mode, start_index, end_index) in [ FILTER_SETTINGS[filtr] for filtr in filters or [ ColorComponentFilter.Red, ColorComponentFilter.Green, ColorComponentFilter.Blue, ColorComponentFilter.Grey ] ] ]: exposures[exposure] += 1 return sorted(exposures.iterkeys(), key=lambda k: exposures[k], reverse=True)[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_image_file_valid(file_path_name): """ Indicate whether the specified image file is valid or not. @param file_path_name: absolute path and file name of an image. @return: ``True`` if the image file is valid, ``False`` if the file is truncated or does not correspond to a supported image. """
# Image.verify is only implemented for PNG images, and it only verifies # the CRC checksum in the image. The only way to check from within # Pillow is to load the image in a try/except and check the error. If # as much info as possible is from the image is needed, # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it # will attempt to parse as much as possible. try: with Image.open(file_path_name) as image: image.load() except IOError: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_and_reorient_image(handle): """ Load the image from the specified file and orient the image accordingly to the Exif tag that the file might embed, which would indicate the orientation of the camera relative to the captured scene. @param handle: a Python file object. @return: an instance returned by the Python Library Image library. """
# Retrieve tags from the Exchangeable image file format (Exif) # included in the picture. If the orientation of the picture is not # top left side, rotate it accordingly. # @deprecated # exif_tags = dict([ (exif_tag.tag, exif_tag) # for exif_tag in exif.process_file(handle).itervalues() # if hasattr(exif_tag, 'tag') ]) exif_tags = exifread.process_file(handle) exif_tag_orientation = exif_tags.get(EXIF_TAG_ORIENTATION) rotation_angle = exif_tag_orientation and { 3L: 180, 6L: 270, 8L: 90 }.get(exif_tag_orientation.values[0]) handle.seek(0) # exif.process_file has updated the file's current position. image = Image.open(handle) return image if rotation_angle is None else image.rotate(rotation_angle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def realign_image(image, shift_x, shift_y, max_shift_x, max_shift_y, shift_angle=0.0, filter=Filter.NearestNeighbor, stretch_factor=None, cropping_box=None): """ Realign the given image providing the specific horizontal and vertical shifts, and crop the image providing the maximum horizontal and vertical shifts of images of a same set so that they all have the same size. @param image: an instance of Python Image Library (PIL) image. @param shift_x: horizontal shift in pixels of the image. @param shift_y: vertical shift in pixels of the image. @param max_shift_x: maximum absolute value of the horizontal shift in pixels of the images in the capture. @param max_shift_y: maximum absolute value of the vertical shift in pixels of the images in the capture. @param shift_angle: horizontal displacement angle in degrees of the image. @param filter: indicate the filter to use when rotating the image. @param stretch_factor: coefficient of multiplication to stretch or to shrink the image in both horizontal and vertical directions. @param cropping_box: a 4-tuple defining the left, upper, right, and lower pixel coordinate of the rectangular region from the specified image. @return: a new instance of Python Image Library (PIL) image. """
(width, height) = image.size # Determine the new size of the image based on the maximal horizontal # and vertical shifts of all the other images in this series. new_width = width - max_shift_x * 2 new_height = height - max_shift_y * 2 # Determine the coordinates of the zone to crop to center the image # based on the horizontal and vertical shifts. bounding_box_x = (0 if shift_x < 0 else shift_x * 2) bounding_box_y = (0 if shift_y < 0 else shift_y * 2) if max_shift_x > shift_x: bounding_box_width = width - abs(shift_x) * 2 bounding_box_x += (bounding_box_width - new_width) / 2 #bounding_box_x = max_shift_x - abs(shift_x) if max_shift_y > shift_y: bounding_box_height = height - abs(shift_y) * 2 bounding_box_y += (bounding_box_height - new_height) / 2 #bounding_box_y = max_shift_y - abs(shift_y) # Crop the image and rotate it based on the horizontal displacement # angle of this image. image = image.crop((bounding_box_x, bounding_box_y, bounding_box_x + new_width, bounding_box_y + new_height)) \ .rotate(-shift_angle, PIL_FILTER_MAP[filter]) # Stretch or shrink this image based on its coefficient, keeping the # calculated new size of this image. if stretch_factor and stretch_factor > 0: image = image.resize((int(round(width * stretch_factor)), int(round(height * stretch_factor))), PIL_FILTER_MAP[filter]) (width, height) = image.size if stretch_factor >= 1: image = image.crop(((width - new_width) / 2, (height - new_height) / 2, (width - new_width) / 2 + new_width - 1, (height - new_height) / 2 + new_height - 1)) else: _image = Image.new(image.mode, (new_width, new_height)) _image.paste(image, ((new_width - width) / 2, (new_height - height) / 2)) image = _image # Crop the image to the specified rectangle, if any defined. if cropping_box: (crop_x1, crop_y1, crop_x2, crop_y2) = cropping_box (width, height) = image.size image = image.crop( (int(round(crop_x1 * width)), int(round(crop_y1 * height)), int(round(crop_x2 * width)), int(round(crop_y2 * height)))) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resize_image(image, canvas_size, filter=Filter.NearestNeighbor, does_crop=False, crop_aligment=CropAlignment.center, crop_form=CropForm.rectangle, match_orientation=False): """ Resize the specified image to the required dimension. @param image: a Python Image Library (PIL) image instance. @param canvas_size: requested size in pixels, as a 2-tuple ``(width, height)``. @param filter: indicate the filter to use when resizing the image. @param does_crop: indicate whether the image needs to be cropped. @param crop_alignment: if the image needs to be cropped, select which alignment to use when cropping. @param match_orientation: indicate whether the given canvas size should be inverted to match the orientation of the image. @return: a PIL image instance corresponding to the image that has been resized, and possibly cropped. """
(source_width, source_height) = image.size source_aspect = source_width / float(source_height) (canvas_width, canvas_height) = canvas_size canvas_aspect = canvas_width / float(canvas_height) if match_orientation: if (source_aspect > 1.0 > canvas_aspect) or (source_aspect < 1.0 < canvas_aspect): (canvas_width, canvas_height) = (canvas_height, canvas_width) canvas_aspect = canvas_width / float(canvas_height) if does_crop: if source_aspect > canvas_aspect: destination_width = int(source_height * canvas_aspect) offset = 0 if crop_aligment == CropAlignment.left_or_top \ else source_width - destination_width if crop_aligment == CropAlignment.right_or_bottom \ else (source_width - destination_width) / 2 box = (offset, 0, offset + destination_width, source_height) else: destination_height = int(source_width / canvas_aspect) offset = 0 if crop_aligment == CropAlignment.left_or_top \ else source_height - destination_height if crop_aligment == CropAlignment.right_or_bottom \ else (source_height - destination_height) / 2 box = (0, offset, source_width, destination_height + offset) else: if canvas_aspect > source_aspect: # The canvas aspect is greater than the image aspect when the canvas's # width is greater than the image's width, in which case we need to # crop the left and right edges of the image. destination_width = int(canvas_aspect * source_height) offset = (source_width - destination_width) / 2 box = (offset, 0, source_width - offset, source_height) else: # The image aspect is greater than the canvas aspect when the image's # width is greater than the canvas's width, in which case we need to # crop the top and bottom edges of the image. destination_height = int(source_width / canvas_aspect) offset = (source_height - destination_height) / 2 box = (0, offset, source_width, source_height - offset) return image.crop(box).resize((canvas_width, canvas_height), PIL_FILTER_MAP[filter])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_vtt_angles(self, pvals, nvals): """ Fit the angles to the model Args: pvals (array-like) : positive values nvals (array-like) : negative values Returns: normalized coef_ values """
# https://www.khanacademy.org/math/trigonometry/unit-circle-trig-func/inverse_trig_functions/v/inverse-trig-functions--arctan angles = np.arctan2(pvals, nvals)-np.pi/4 norm = np.maximum(np.minimum(angles, np.pi-angles), -1*np.pi-angles) norm = csr_matrix(norm) # Remove any weight from the NER features. These will be added later. for key, value in self.B.items(): norm[0, key] = 0. return norm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_params(self, **params): """ Set the parameters of the estimator. Args: bias (array-like) : bias of the estimator. Also known as the intercept in a linear model. weights (array-like) : weights of the features. Also known as coeficients. NER biases (array-like) : NER entities infering column position on X and bias value. Ex: `b_4=10, b_5=6`. Example: """
if 'bias' in params.keys(): self.intercept_ = params['bias'] if 'weights' in params.keys(): self.coef_ = params['weights'] for key in params.keys(): if 'b_' == key[:2]: self.B[int(key[2:])] = params[key] return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_params(self, deep=True): """ Get parameters for the estimator. Args: deep (boolean, optional) : If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns: params : mapping of string to any contained subobjects that are estimators. """
params = {'weights':self.coef_, 'bias':self.intercept_} if deep: for key, value in self.B.items(): params['b_'+str(key)] = value return params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_email(hostname, username, password, author_name, author_email_address, recipient_email_addresses, subject, content, file_path_names=None, port_number=587, unsubscribe_mailto_link=None, unsubscribe_url=None): """ Send a electronic mail to a list of recipients. @note: Outlook and Gmail leverage the list-unsubscribe option for senders with good sending reputations: "In order to receive unsubscribe feedback, senders must include an RFC2369-compliant List-Unsubscribe header containing a mailto: address. Please note that we only enable this feedback via email, so URIs for other protocols such as http will be ignored. The sender must also have a good reputation, and must act promptly in removing users from their lists. We do not provide unsubscribe feedback to senders when a user unsubscribes from an untrusted message." [https://sendersupport.olc.protection.outlook.com/pm/junkemail.aspx] "This only works for some senders right now. We're actively encouraging senders to support auto-unsubscribe — we think 100% should. We won't provide the unsubscribe option on messages from spammers: we can't trust that they'll actually unsubscribe you, and they might even send you more spam. So you'll only see the unsubscribe option for senders that we're pretty sure are not spammers and will actually honor your unsubscribe request. We're being pretty conservative about which senders to trust in the beginning; over time, we hope to offer the ability to unsubscribe from more email." [https://gmail.googleblog.com/2009/07/unsubscribing-made-easy.html] @param hostname: Internet address or fully qualified domain name -- human-readable nickname that corresponds to the address -- of the SMTP server is running on. @param username: username to authenticate with against the SMTP server. @param password: password associate to the username to authenticate with against the SMTP server. @param author_name: complete name of the originator of the message. @param author_email_address: address of the mailbox to which the author of the message suggests that replies be sent. @param recipient_email_addresses: email address(es) of the primary recipient(s) of the message. A bare string will be treated as a list with one address. @param subject: a short string identifying the topic of the message. @param content: the body of the message. @param file_path_names: a list of complete fully qualified path name (FQPN) of the files to attach to this message. @param port_number: Internet port number on which the remote SMTP server is listening at. SMTP communication between mail servers uses TCP port 25. Mail clients on the other hand, often submit the outgoing emails to a mail server on port 587. Despite being deprecated, mail providers sometimes still permit the use of nonstandard port 465 for this purpose. @param unsubscribe_mailto_link: an email address to directly unsubscribe the recipient who requests to be removed from the mailing list (https://tools.ietf.org/html/rfc2369.html). In addition to the email address, other information can be provided. In fact, any standard mail header fields can be added to the mailto link. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term (https://tools.ietf.org/html/rfc6068). @param unsubscribe_url: a link that will take the subscriber to a landing page to process the unsubscribe request. This can be a subscription center, or the subscriber is removed from the list right away and gets sent to a landing page that confirms the unsubscribe. """
# Convert bare string representing only one email address as a list with # this single email address. if not isinstance(recipient_email_addresses, (list, set, tuple)): recipient_email_addresses = [ recipient_email_addresses ] # Build the message to be sent. message = MIMEMultipart() message['From'] = __build_author_name_expr(author_name, author_email_address) message['To'] = COMMASPACE.join(recipient_email_addresses) message['Date'] = formatdate(localtime=True) message['Subject'] = subject if author_email_address: message.add_header('Reply-To', author_email_address) # Add method(s) to unsubscribe a recipient from a mailing list at his # request. if unsubscribe_mailto_link or unsubscribe_url: unsubscribe_methods = [ unsubscribe_url and '<%s>' % unsubscribe_url, unsubscribe_mailto_link and '<mailto:%s>' % unsubscribe_mailto_link, ] message.add_header('List-Unsubscribe', ', '.join([ method for method in unsubscribe_methods if method ])) # Detect whether the content of the message is a plain text or an HTML # content, based on whether the content starts with "<" or not. message.attach(MIMEText(content.encode('utf-8'), _charset='utf-8', _subtype='html' if content and content.strip()[0] == '<' else 'plain')) # Attache the specified files to the message. for file_path_name in file_path_names or []: part = MIMEBase('application', 'octet-stream') with open(file_path_name, 'rb') as handle: part.set_payload(handle.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_path_name)) message.attach(part) # Connect the remote mail server and send the message. smtp_server = smtplib.SMTP_SSL(hostname) if port_number == 465 else smtplib.SMTP(hostname, port_number) smtp_server.ehlo() if port_number <> 465: smtp_server.starttls() smtp_server.ehlo() smtp_server.login(username, password) smtp_server.sendmail(author_email_address, recipient_email_addresses, message.as_string()) smtp_server.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def confirm_send(address, amount, ref_id=None, session=ses): """ Confirm that a send has completed. Does not actually check confirmations, but instead assumes that if this is called, the transaction has been completed. This is because we assume our own sends are safe. :param session: :param str ref_id: The updated ref_id for the transaction in question :param str address: The address that was sent to :param Amount amount: The amount that was sent """
debitq = session.query(wm.Debit) debitq = debitq.filter(wm.Debit.address == address) debitq = debitq.filter(wm.Debit.amount == amount) debit = debitq.filter(wm.Debit.transaction_state == 'unconfirmed').first() if not debit: raise ValueError("Debit already confirmed or address unknown.") debit.transaction_state = 'complete' if ref_id is not None: debit.ref_id = ref_id session.add(debit) session.commit() return debit
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_config(path): """ Read a configuration from disk. Arguments path -- the loation to deserialize """
parser = _make_parser() if parser.read(path): return parser raise Exception("Failed to read {}".format(path))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correct_rytov_sc_input(radius_sc, sphere_index_sc, medium_index, radius_sampling): """Inverse correction of refractive index and radius for Rytov This method returns the inverse of :func:`correct_rytov_output`. Parameters radius_sc: float Systematically corrected radius of the sphere [m] sphere_index_sc: float Systematically corrected refractive index of the sphere medium_index: float Refractive index of the surrounding medium radius_sampling: int Number of pixels used to sample the sphere radius when computing the Rytov field. Returns ------- radius: float Fitted radius of the sphere [m] sphere_index: float Fitted refractive index of the sphere See Also -------- correct_rytov_output: the inverse of this method """
params = get_params(radius_sampling) # sage script: # var('sphere_index, sphere_index_sc, na, nb, medium_index') # x = sphere_index / medium_index - 1 # eq = sphere_index_sc == sphere_index + ( na*x^2 + nb*x) * medium_index # solve([eq], [sphere_index]) # (take the positive sign solution) na = params["na"] nb = params["nb"] prefac = medium_index / (2 * na) sm = 2 * na - nb - 1 rt = nb**2 - 4 * na + 2 * nb + 1 + 4 / medium_index * na * sphere_index_sc sphere_index = prefac * (sm + np.sqrt(rt)) x = sphere_index / medium_index - 1 radius = radius_sc / (params["ra"] * x**2 + params["rb"] * x + params["rc"]) return radius, sphere_index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correct_rytov_output(radius, sphere_index, medium_index, radius_sampling): r"""Error-correction of refractive index and radius for Rytov This method corrects the fitting results for `radius` :math:`r_\text{Ryt}` and `sphere_index` :math:`n_\text{Ryt}` obtained using :func:`qpsphere.models.rytov` using the approach described in :cite:`Mueller2018` (eqns. 3,4, and 5). .. math:: n_\text{Ryt-SC} &= n_\text{Ryt} + n_\text{med} \cdot \left( a_n x^2 + b_n x + c_n \right) r_\text{Ryt-SC} &= r_\text{Ryt} \cdot \left( a_r x^2 +b_r x + c_r \right) &\text{with} x = \frac{n_\text{Ryt}}{n_\text{med}} - 1 The correction factors are given in :data:`qpsphere.models.mod_rytov_sc.RSC_PARAMS`. Parameters radius: float Fitted radius of the sphere :math:`r_\text{Ryt}` [m] sphere_index: float Fitted refractive index of the sphere :math:`n_\text{Ryt}` medium_index: float Refractive index of the surrounding medium :math:`n_\text{med}` radius_sampling: int Number of pixels used to sample the sphere radius when computing the Rytov field. Returns ------- radius_sc: float Systematically corrected radius of the sphere :math:`r_\text{Ryt-SC}` [m] sphere_index_sc: float Systematically corrected refractive index of the sphere :math:`n_\text{Ryt-SC}` See Also -------- correct_rytov_sc_input: the inverse of this method """
params = get_params(radius_sampling) x = sphere_index / medium_index - 1 radius_sc = radius * (params["ra"] * x**2 + params["rb"] * x + params["rc"]) sphere_index_sc = sphere_index + medium_index * (params["na"] * x**2 + params["nb"] * x) return radius_sc, sphere_index_sc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rytov_sc(radius=5e-6, sphere_index=1.339, medium_index=1.333, wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80), center=(39.5, 39.5), radius_sampling=42): r"""Field behind a dielectric sphere, systematically corrected Rytov This method implements a correction of :func:`qpsphere.models.rytov`, where the `radius` :math:`r_\text{Ryt}` and the `sphere_index` :math:`n_\text{Ryt}` are corrected using the approach described in :cite:`Mueller2018` (eqns. 3,4, and 5). .. math:: n_\text{Ryt-SC} &= n_\text{Ryt} + n_\text{med} \cdot \left( a_n x^2 + b_n x + c_n \right) r_\text{Ryt-SC} &= r_\text{Ryt} \cdot \left( a_r x^2 +b_r x + c_r \right) &\text{with} x = \frac{n_\text{Ryt}}{n_\text{med}} - 1 The correction factors are given in :data:`qpsphere.models.mod_rytov_sc.RSC_PARAMS`. Parameters radius: float Radius of the sphere [m] sphere_index: float Refractive index of the sphere medium_index: float Refractive index of the surrounding medium wavelength: float Vacuum wavelength of the imaging light [m] pixel_size: float Pixel size [m] grid_size: tuple of floats Resulting image size in x and y [px] center: tuple of floats Center position in image coordinates [px] radius_sampling: int Number of pixels used to sample the sphere radius when computing the Rytov field. The default value of 42 pixels is a reasonable number for single-cell analysis. Returns ------- qpi: qpimage.QPImage Quantitative phase data set """
r_ryt, n_ryt = correct_rytov_sc_input(radius_sc=radius, sphere_index_sc=sphere_index, medium_index=medium_index, radius_sampling=radius_sampling) qpi = mod_rytov.rytov(radius=r_ryt, sphere_index=n_ryt, medium_index=medium_index, wavelength=wavelength, pixel_size=pixel_size, grid_size=grid_size, center=center, radius_sampling=radius_sampling) # update correct simulation parameters qpi["sim radius"] = radius qpi["sim index"] = sphere_index qpi["sim model"] = "rytov-sc" return qpi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gsignal(name, *args, **kwargs): """Add a GObject signal to the current object. It current supports the following types: - str, int, float, long, object, enum :param name: name of the signal :param args: types for signal parameters, if the first one is a string 'override', the signal will be overridden and must therefor exists in the parent GObject. .. note:: flags: A combination of; - gobject.SIGNAL_RUN_FIRST - gobject.SIGNAL_RUN_LAST - gobject.SIGNAL_RUN_CLEANUP - gobject.SIGNAL_NO_RECURSE - gobject.SIGNAL_DETAILED - gobject.SIGNAL_ACTION - gobject.SIGNAL_NO_HOOKS """
frame = sys._getframe(1) try: locals = frame.f_locals finally: del frame dict = locals.setdefault('__gsignals__', {}) if args and args[0] == 'override': dict[name] = 'override' else: retval = kwargs.get('retval', None) if retval is None: default_flags = gobject.SIGNAL_RUN_FIRST else: default_flags = gobject.SIGNAL_RUN_LAST flags = kwargs.get('flags', default_flags) if retval is not None and flags != gobject.SIGNAL_RUN_LAST: raise TypeError( "You cannot use a return value without setting flags to " "gobject.SIGNAL_RUN_LAST") dict[name] = (flags, retval, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gproperty(name, ptype, default=None, nick='', blurb='', flags=gobject.PARAM_READWRITE, **kwargs): """Add a GObject property to the current object. :param name: name of property :param ptype: type of property :param default: default value :param nick: short description :param blurb: long description :param flags: parameter flags, a combination of: - PARAM_READABLE - PARAM_READWRITE - PARAM_WRITABLE - PARAM_CONSTRUCT - PARAM_CONSTRUCT_ONLY - PARAM_LAX_VALIDATION Optional, only for int, float, long types: :param minimum: minimum allowed value :param: maximum: maximum allowed value """
# General type checking if default is None: default = _DEFAULT_VALUES.get(ptype) elif not isinstance(default, ptype): raise TypeError("default must be of type %s, not %r" % ( ptype, default)) if not isinstance(nick, str): raise TypeError('nick for property %s must be a string, not %r' % ( name, nick)) nick = nick or name if not isinstance(blurb, str): raise TypeError('blurb for property %s must be a string, not %r' % ( name, blurb)) # Specific type checking if ptype == int or ptype == float or ptype == long: default = (kwargs.get('minimum', ptype(0)), kwargs.get('maximum', _MAX_VALUES[ptype]), default) elif ptype == bool: if default is not True and default is not False: raise TypeError("default must be True or False, not %r" % default) default = default, elif gobject.type_is_a(ptype, gobject.GEnum): if default is None: raise TypeError("enum properties needs a default value") elif not isinstance(default, ptype): raise TypeError("enum value %s must be an instance of %r" % (default, ptype)) default = default, elif ptype == str: default = default, elif ptype == object: if default is not None: raise TypeError("object types does not have default values") default = () else: raise NotImplementedError("type %r" % ptype) if flags < 0 or flags > 32: raise TypeError("invalid flag value: %r" % (flags,)) frame = sys._getframe(1) try: locals = frame.f_locals dict = locals.setdefault('__gproperties__', {}) finally: del frame dict[name] = (ptype, nick, blurb) + default + (flags,)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_gui(delay=0.0001, wait=0.0001): """Use up all the events waiting to be run :param delay: Time to wait before using events :param wait: Time to wait between iterations of events This function will block until all pending events are emitted. This is useful in testing to ensure signals and other asynchronous functionality is required to take place. """
time.sleep(delay) while gtk.events_pending(): gtk.main_iteration_do(block=False) time.sleep(wait)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_in_window(target, on_destroy=gtk.main_quit): """Run a widget, or a delegate in a Window """
w = _get_in_window(target) if on_destroy: w.connect('destroy', on_destroy) w.resize(500, 400) w.move(100, 100) w.show_all() gtk.main()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dict_to_form(dict): ''' Generate a flatland form based on a pandas Series. ''' from flatland import Boolean, Form, String, Integer, Float def is_float(v): try: return (float(str(v)), True)[1] except (ValueError, TypeError): return False def is_int(v): try: return (int(str(v)), True)[1] except (ValueError, TypeError): return False def is_bool(v): return v in (True, False) schema_entries = [] for k, v in dict.iteritems(): if is_int(v): schema_entries.append(Integer.named(k).using(default=v, optional=True)) elif is_float(v): schema_entries.append(Float.named(k).using(default=v, optional=True)) elif is_bool(v): schema_entries.append(Boolean.named(k).using(default=v, optional=True)) elif type(v) == str: schema_entries.append(String.named(k).using(default=v, optional=True)) return Form.of(*schema_entries)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _detect_term_type(): """ Detect the type of the terminal. """
if os.name == 'nt': if os.environ.get('TERM') == 'xterm': # maybe MinTTY return 'mintty' else: return 'nt' if platform.system().upper().startswith('CYGWIN'): return 'cygwin' return 'posix'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """ Clear the terminal screen. """
if hasattr(self.stdout, 'isatty') and self.stdout.isatty() or self.term_type == 'mintty': cmd, shell = { 'posix': ('clear', False), 'nt': ('cls', True), 'cygwin': (['echo', '-en', r'\ec'], False), 'mintty': (r'echo -en "\ec', False), }[self.term_type] subprocess.call(cmd, shell=shell, stdin=self.stdin, stdout=self.stdout, stderr=self.stderr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_input_buffer(self): """ Clear the input buffer. """
if hasattr(self.stdin, 'isatty') and self.stdin.isatty(): if os.name == 'nt': while msvcrt.kbhit(): msvcrt.getch() else: try: self.stdin.seek(0, 2) # may fail in some unseekable file object except IOError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getch(self): """ Read one character from stdin. If stdin is not a tty or set `getch_enabled`=False, read input as one line. :return: unicode: """
ch = self._get_one_char() if self.keep_input_clean: self.clear_input_buffer() try: # accept only unicode characters (for Python 2) uch = to_unicode(ch, 'ascii') except UnicodeError: return '' return uch if self._check_key_repeat(uch) else ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gets(self): """ Read line from stdin. The trailing newline will be omitted. :return: string: """
ret = self.stdin.readline() if ret == '': raise EOFError # To break out of EOF loop return ret.rstrip('\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_parser(self, subparsers): """ Creates the subparser for this particular command """
self.parser = subparsers.add_parser(self.name, help=self.help, parents=self.parents) self.add_arguments() self.parser.set_defaults(func=self.handle) return self.parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_arguments(self): """ Definition and addition of all arguments. """
if self.parser is None: raise TypeError("Parser cannot be None, has create_parser been called?") for keys, kwargs in self.args.items(): if not isinstance(keys, tuple): keys = (keys,) self.parser.add_argument(*keys, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def allocation(node,format,h): ''' Allocation provides a snapshot of how shards have located around the cluster and the state of disk usage ''' try: response = base.es.cat.allocation(node_id=node,bytes=format, h=h, format='json') table = base.draw_table(response) except Exception as e: click.echo(e) else: click.echo(table)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def count(index,h): ''' Gives count of the documents stored in Elasticsearch. If index option is provided, it will provide document count of that index. ''' try: response = base.es.cat.count(index,h=h) table = base.draw_table(response) except Exception as e: click.echo(e) else: click.echo(table)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Close the connection to the AMQP compliant broker. """
if self.channel is not None: self.channel.close() if self.__connection is not None: self.__connection.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """ Open a connection to the AMQP compliant broker. """
self._connection = \ amqp.Connection(host='%s:%s' % (self.hostname, self.port), userid=self.username, password=self.password, virtual_host=self.virtual_host, insist=False) self.channel = self._connection.channel()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(self, message_type, message_payload): """ Publish the specified object that the function automatically converts into a JSON string representation. This function use the lowered class name of the service as the AMQP routing key. For instance, if the class ``ExampleService`` inherits from the base class ``BaseService``, the methods of an instance of this class will publish messages using the routing key named ``exampleservice``. @param message_type: string representing the type of the event, more likely ``on_something_happened`. @param message_payload: an object to convert into a JSON string representation and to publish. """
payload = json.dumps(jsonpickle.Pickler(unpicklable=False).flatten(message_payload)) message = amqp.Message(payload) message.properties["delivery_mode"] = 2 name = 'majormode.%s.%s.%s' % (settings.ENVIRONMENT_STAGE, self.service_name.lower(), message_type.lower()) self.channel.queue_declare(queue=name, durable=True, exclusive=False, auto_delete=False) self.channel.exchange_declare(exchange=name, type="direct", durable=True, auto_delete=False,) self.channel.queue_bind(queue=name, exchange=name, routing_key=name) self.channel.basic_publish(message, exchange=name, routing_key=name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_py_dtypes(data_frame): ''' Return a `pandas.DataFrame` containing Python type information for the columns in `data_frame`. Args: data_frame (pandas.DataFrame) : Data frame containing data columns. Returns: (pandas.DataFrame) : Data frame indexed by the column names from `data_frame`, with the columns `'i'` and `'dtype'` indicating the index and Python type of the corresponding `data_frame` column, respectively. ''' df_py_dtypes = data_frame.dtypes.map(get_py_dtype).to_frame('dtype').copy() df_py_dtypes.loc[df_py_dtypes.dtype == object, 'dtype'] = \ (df_py_dtypes.loc[df_py_dtypes.dtype == object].index .map(lambda c: str if data_frame[c] .map(lambda v: isinstance(v, str)).all() else object)) df_py_dtypes.insert(0, 'i', range(df_py_dtypes.shape[0])) df_py_dtypes.index.name = 'column' return df_py_dtypes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_list_store(data_frame): ''' Return a `pandas.DataFrame` containing Python type information for the columns in `data_frame` and a `gtk.ListStore` matching the contents of the data frame. Args: data_frame (pandas.DataFrame) : Data frame containing data columns. Returns: (tuple) : The first element is a data frame as returned by `get_py_dtypes` and the second element is a `gtk.ListStore` matching the contents of the data frame. ''' df_py_dtypes = get_py_dtypes(data_frame) list_store = gtk.ListStore(*df_py_dtypes.dtype) for i, row_i in data_frame.iterrows(): list_store.append(row_i.tolist()) return df_py_dtypes, list_store
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_columns(tree_view, df_py_dtypes, list_store): ''' Add columns to a `gtk.TreeView` for the types listed in `df_py_dtypes`. Args: tree_view (gtk.TreeView) : Tree view to append columns to. df_py_dtypes (pandas.DataFrame) : Data frame containing type information for one or more columns in `list_store`. list_store (gtk.ListStore) : Model data. Returns: None ''' tree_view.set_model(list_store) for column_i, (i, dtype_i) in df_py_dtypes[['i', 'dtype']].iterrows(): tree_column_i = gtk.TreeViewColumn(column_i) tree_column_i.set_name(column_i) if dtype_i in (int, long): property_name = 'text' cell_renderer_i = gtk.CellRendererSpin() elif dtype_i == float: property_name = 'text' cell_renderer_i = gtk.CellRendererSpin() elif dtype_i in (bool, ): property_name = 'active' cell_renderer_i = gtk.CellRendererToggle() elif dtype_i in (str, ): property_name = 'text' cell_renderer_i = gtk.CellRendererText() else: raise ValueError('No cell renderer for dtype: %s' % dtype_i) cell_renderer_i.set_data('column_i', i) cell_renderer_i.set_data('column', tree_column_i) tree_column_i.pack_start(cell_renderer_i, True) tree_column_i.add_attribute(cell_renderer_i, property_name, i) tree_view.append_column(tree_column_i)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def daemonize(): """ Daemonize the program, ie. make it run in the "background", detach it from its controlling terminal and from its controlling process group session. NOTES: - This function also umask(0) and chdir("/") - stdin, stdout, and stderr are redirected from/to /dev/null SEE ALSO: http://www.unixguide.net/unix/programming/1.7.shtml """
try: pid = os.fork() if pid > 0: os._exit(0) # pylint: disable-msg=W0212 except OSError, e: log.exception("first fork() failed: %d (%s)", e.errno, e.strerror) sys.exit(1) os.setsid() os.umask(0) os.chdir("/") try: pid = os.fork() if pid > 0: os._exit(0) # pylint: disable-msg=W0212 except OSError, e: log.exception("second fork() failed: %d (%s)", e.errno, e.strerror) sys.exit(1) try: devnull_fd = os.open(os.devnull, os.O_RDWR) for stdf in (sys.__stdout__, sys.__stderr__): try: stdf.flush() except Exception: # pylint: disable-msg=W0703,W0704 pass for stdf in (sys.__stdin__, sys.__stdout__, sys.__stderr__): try: os.dup2(devnull_fd, stdf.fileno()) except OSError: # pylint: disable-msg=W0704 pass except Exception: # pylint: disable-msg=W0703 log.exception("error during file descriptor redirection")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def redirect_stream(system_stream, target_stream): """ Redirect a system stream to a specified file. `system_stream` is a standard system stream such as ``sys.stdout``. `target_stream` is an open file object that should replace the corresponding system stream object. If `target_stream` is ``None``, defaults to opening the operating system's null device and using its file descriptor. """
if target_stream is None: target_fd = os.open(os.devnull, os.O_RDWR) else: target_fd = target_stream.fileno() os.dup2(target_fd, system_stream.fileno())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_utf8_streams(): """Forces UTF-8 on stdout and stderr; in some crazy environments, they use 'ascii' encoding by default """
def ensure_utf8_stream(stream): if not isinstance(stream, io.StringIO): stream = getwriter("utf-8")(getattr(stream, "buffer", stream)) stream.encoding = "utf-8" return stream sys.stdout, sys.stderr = (ensure_utf8_stream(s) for s in (sys.stdout, sys.stderr))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def configure(name, host, port, auth, current): ''' Configure is used to add various ES ports you are working on. The user can add as many es ports as the one wants, but one will remain active at one point. ''' Config = ConfigParser.ConfigParser() if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except Exception as e: click.echo(e) return section_name = None if(current.lower() == 'y'): section_name = 'Current' change_current() else: section_name = name.capitalize() cfgfile = open(filename,'a') Config.add_section(section_name) Config.set(section_name,'host',host) Config.set(section_name,'port',port) Config.set(section_name,'auth',auth) Config.set(section_name,'name',name.capitalize()) Config.write(cfgfile) cfgfile.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_parts(list1, list2): """ if list2 does not start with list1, we can't really check and return 0 """
for i, item in enumerate(list1): if item != list2[i]: return 0 if len(list2) > len(list1): return ISDIR else: return ISFILE
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_event(urls): """ This parallel fetcher uses gevent one uses gevent """
rs = (grequests.get(u) for u in urls) return [content.json() for content in grequests.map(rs)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendTemplate(mailer, sender, recipient, template, context, hook=_nop): """ Simple case for sending some e-mail using a template. """
headers, parts = template.evaluate(context) headers["From"] = sender headers["To"] = recipient hook(headers, parts) content = mime.buildMessage(headers, parts) return mailer.send(sender, recipient, content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def export_cmd(cmd, src_path, dest_dir=None, item_id=None, export_format=None, scale=None): ''' Executes a `sketchtool export` command and returns formatted output :src_path: File to export. :type <str> :dest_dir: Items are exported at /dest_dir/[email protected]_format e.g. `~/Desktop/Page [email protected]` :param export_format: 'png', 'pdf' etc. :type <ExportFormat> :param scale: Specify as 1.0, 2.0 etc. :type <float> :param item_id: id or name of an Exportable :type <str> :returns: list of exported item paths ''' cmd.extend([src_path]) if not dest_dir: dest_dir = mkdtemp(prefix='pyglass') cmd.extend(['--output=%s' % dest_dir]) if export_format: cmd.extend(['--formats=%s' % export_format]) if scale: cmd.extend(['--scales=%s' % scale]) if item_id: cmd.extend(['--items=%s' % item_id]) logger.debug(u'Executing cmd: %s' % cmd) exported_str = execute(cmd) logger.debug(u'Raw result: %s' % exported_str) # Raw result is in the form: 'Exported <item-name-1>\nExported <item-name-2>\n' exported_items = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(dest_dir) for f in files if f.endswith('.%s' % export_format)] return exported_items
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_binaries(): """Download and return paths of all platform-specific binaries"""
paths = [] for arp in [False, True]: paths.append(get_binary(arp=arp)) return paths
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backward_propagation(parameters, cache, X, Y): """ Implement the backward propagation using the instructions above. Arguments: parameters -- python dictionary containing our parameters cache -- a dictionary containing "Z1", "A1", "Z2" and "A2". X -- input data of shape (2, number of examples) Y -- "true" labels vector of shape (1, number of examples) Returns: grads -- python dictionary containing your gradients with respect to different parameters """
m = X.shape[1] # First, retrieve W1 and W2 from the dictionary "parameters". W1 = parameters["W1"] W2 = parameters["W2"] # Retrieve also A1 and A2 from dictionary "cache". A1 = cache["A1"] A2 = cache["A2"] # Backward propagation: calculate dW1, db1, dW2, db2. dZ2 = A2 - Y dW2 = 1.0 / m * np.dot(dZ2, A1.T) db2 = 1.0 / m * np.sum(dZ2, axis=1, keepdims=True) dZ1 = W2.T * dZ2 * (1 - np.power(A1, 2)) dW1 = 1.0 / m * np.dot(dZ1, X.T) db1 = 1.0 / m * np.sum(dZ1, axis=1, keepdims=True) grads = {"dW1": dW1, "db1": db1, "dW2": dW2, "db2": db2} return grads
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_parameters(parameters, grads, learning_rate=1.2): """ Updates parameters using the gradient descent update rule given above Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients Returns: parameters -- python dictionary containing your updated parameters """
# Retrieve each parameter from the dictionary "parameters" W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] # Retrieve each gradient from the dictionary "grads" dW1 = grads["dW1"] db1 = grads["db1"] dW2 = grads["dW2"] db2 = grads["db2"] # Update rule for each parameter W1 -= learning_rate * dW1 b1 -= learning_rate * db1 W2 -= learning_rate * dW2 b2 -= learning_rate * db2 parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(parameters, X): """ Using the learned parameters, predicts a class for each example in X Arguments: parameters -- python dictionary containing your parameters X -- input data of size (n_x, m) Returns predictions -- vector of predictions of our model (red: 0 / blue: 1) """
# Computes probabilities using forward propagation, # and classifies to 0/1 using 0.5 as the threshold. A2, cache = forward_propagation(X, parameters) predictions = np.array([1 if (i > 0.5) else 0 for i in A2[0]]) return predictions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_email(sender, pw, to, subject, content, files=None, service='163'): """send email, recommended use 163 mailbox service, as it is tested. :param sender: str email address of sender :param pw: str password for sender :param to: str email addressee :param subject: str subject of email :param content: str content of email :param files: list path list of attachments :param service: str smtp server address, optional is ['163', 'qq'] :return: None """
se = EmailSender(from_=sender, pw=pw, service=service) se.send_email(to=to, subject=subject, content=content, files=files) se.quit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nodes(self, node=None): '''walks through tree and yields each node''' if node is None: for root in self.stack: yield from self.nodes(root) else: yield node if node.is_container(): for child in node.children: yield from self.nodes(child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def context(self, message): ''' Function decorator which adds "context" around a group of TestCases and may have a `before` and `after` func. >>> s = Suite() >>> @s.context('context 1') ... def _(): ... @s.before ... def _(): print('before 1 called.') ... @s.it('runs a test') ... def _(): print('test case 1 called.') >>> @s.context('context 2') ... def _(): ... @s.before ... def _(): print('before 2 called.') ... @s.it('runs a test') ... def _(): print('test case 2 called.') >>> tc1 = list(s.nodes())[2] >>> tc1.run() before 1 called. test case 1 called. >>> tc1 = list(s.nodes())[4] >>> tc1.run() before 2 called. test case 2 called. ''' def decorator(context_func): self.push_container(message) context_func() self.pop_container() return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def it(self, message, repeat=None): ''' Function decorator which adds a TestCase to the Suite >>> s = Suite() >>> @s.it('always passes') ... def _(): pass >>> list(s.nodes()) [<Container: root>, <TestCase: always passes>] `repeat` will add multiple test cases with extra parameters. >>> s = Suite() >>> @s.it('a={} b={}', repeat=[(1, 2), (3, 4)]) ... def _(a, b): pass >>> list(s.nodes()) [<Container: root>, <TestCase: a=1 b=2>, <TestCase: a=3 b=4>] ''' def decorator(test_func): if repeat: for set_of_args in repeat: self.add_test(message, test_func, set_of_args) else: self.add_test(message, test_func) return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spammer_view(request): """View for setting cookies on spammers."""
# Permits use of CSRF middleware context = RequestContext(request, {}) template = Template("") response = HttpResponse(template.render(context)) # Sets a cookie with a 10 years lifetime, accessible only via HTTP: response.set_cookie(COOKIE_KEY, value=COOKIE_SPAM, httponly=True, expires=datetime.now()+timedelta(days=3650)) if DJANGOSPAM_LOG: log("BLOCK RESPONSE", request.method, request.path_info, request.META.get("HTTP_USER_AGENT", "undefined")) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_object_by_name(object_name): """Load an object from a module by name"""
mod_name, attr = object_name.rsplit('.', 1) mod = import_module(mod_name) return getattr(mod, attr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bench_serpy(): """Beanchmark for 1000 objects with 2 fields. """
class FooSerializer(serpy.DictSerializer): """The serializer schema definition.""" # Use a Field subclass like IntField if you need more validation. attr_2 = serpy.IntField() attr_1 = serpy.StrField() return [FooSerializer(obj).data for obj in object_loader()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decompose_locale(locale, strict=True): """ Return the decomposition of the specified locale into a language code and a country code. @param locale: a string representation of a locale, i.e., a ISO 639-3 alpha-3 code (or alpha-2 code), optionally followed by a dash character ``-`` and a ISO 3166-1 alpha-2 code. If ``None`` passed, the function returns the default locale, i.e., standard English ``('eng', None)``. @param strict: indicate whether the string representation of a locale has to be strictly compliant with RFC 4646, or whether a Java- style locale (character ``_`` instead of ``-``) is accepted. @return: a tuple ``(language_code, country_code)``, where the first code represents a ISO 639-3 alpha-3 code (or alpha-2 code), and the second code a ISO 3166-1 alpha-2 code. """
if locale is None: return ('eng', None) match = REGEX_LOCALE.match(locale) if match is None: if strict == True: raise Locale.MalformedLocaleException() match = REGEX_JAVA_LOCALE.match(locale) if match is None: raise Locale.MalformedLocaleException() (_, locale_language_code, locale_country_code, language_code) = match.groups() return (locale_language_code, locale_country_code) if language_code is None \ else (language_code, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_drops(self, dropin): """Load `drops` from the given dropin. Args: dropin (string): path of a dropin, e.g. dropin.auth Returns: An iterable contains the drops object in the given dropin This method load drops object by some sort of convension. For example, assuming we want to load drops type `models` from dropin `dropin.articls`. The drops are discoveried with the following sequence:: import dropin.articles drops = dropin.articles.models if anything goes wrong, next try is :: import dropin.articles.models as drops if the current drops object has attribute **__drops__** :: drops = drops.__drops__ if the current drops object is a callable :: drops = drops() if not drops was found, an empty list is returned. """
obj = load_object(dropin) try: drops = getattr(obj, self.drops_type) except AttributeError: try: drops = load_object('%s.%s' % (dropin, self.drops_type)) except ImportError: drops = None if hasattr(drops, '__drops__'): drops = drops.__drops__ if callable(drops): drops = drops(self.app) return drops or []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_drops(self, dropin): """Register the `drops` in given `dropin` to a flask app. Args: app (Flask): the flask app to be initialized dropin (string): path of a python module or object, e.g. dropin.auth This is the only method that a drops loader **must** implment. The default behavior in the base loader is to store all the drops object in the app's extentions dict. For example, the drops with type `models` will be stored in a list which is accessible through:: app.extensions['dropin']['models'] or through DropInManager instance which provide a simple proxy to the dropin extension of `current_app`:: dropin = DropInManager() dropin.models Whereas the BlueprintsLoader overrided this method to actually register the blueprints to the app. """
drops = self.app.extensions['dropin'].setdefault(self.drops_type, []) drops.extend(self.load_drops(dropin))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge(cls, *others): """ Merge the `others` schema into this instance. The values will all be read from the provider of the original object. """
for other in others: for k, v in other: setattr(cls, k, BoundValue(cls, k, v.value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def field_value(self, value): """Validate against NodeType. """
if not self.is_array: return self.field_type(value) if isinstance(value, (list, tuple, set)): return [self.field_type(item) for item in value] return self.field_type(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid(self, value): """Validate value before actual instance setting based on type. Args: value (object): The value object for validation. Returns: True if value validation succeeds else False. """
if not self.is_array: return self._valid(value) if isinstance(value, (list, set, tuple)): return all([self._valid(item) for item in value]) return self._valid(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _attr_data_(self): "Special property containing the memoized data." try: return self.__attr_data except AttributeError: self.__attr_data = type( ''.join([type(self).__name__, 'EmptyData']), (), { '__module__': type(self).__module__, '__slots__': () } )() return self.__attr_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _attr_func_(self): "Special property containing functions to be lazily-evaluated." try: return self.__attr_func except AttributeError: self.__attr_func = type( ''.join([type(self).__name__, 'EmptyFuncs']), (), { '__module__': type(self).__module__, '__slots__': () } )() return self.__attr_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _loadable_get_(name, self): "Used to lazily-evaluate & memoize an attribute." func = getattr(self._attr_func_, name) ret = func() setattr(self._attr_data_, name, ret) setattr( type(self), name, property( functools.partial(self._simple_get_, name) ) ) delattr(self._attr_func_, name) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _setable_get_(name, self): "Used to raise an exception for attributes unable to be evaluated yet." raise AttributeError( "'{typename}' object has no attribute '{name}'".format( typename=type(self).__name__, name=name ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _setable_set_(name, self, func): "Used to set the attribute a single time using the given function." setattr(self._attr_data_, name, func()) if hasattr(self._attr_func_, name): delattr(self._attr_func_, name) setattr( type(self), name, property( functools.partial(self._simple_get_, name) ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _set_attr(self, name, doc=None, preload=False): "Initially sets up an attribute." if doc is None: doc = 'The {name} attribute.'.format(name=name) if not hasattr(self._attr_func_, name): attr_prop = property( functools.partial(self._setable_get_, name), functools.partial(self._setable_set_, name), doc=doc ) elif preload: func = getattr(self._attr_func_, name) setattr(self._attr_data_, name, func()) delattr(self._attr_func_, name) attr_prop = property( functools.partial(self._simple_get_, name), doc=doc ) else: attr_prop = property( functools.partial(self._loadable_get_, name), doc=doc ) setattr(type(self), name, attr_prop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple(type, short, long=None, parent=None, buttons=gtk.BUTTONS_OK, default=None, **kw): """A simple dialog :param type: The type of dialog :param short: The short description :param long: The long description :param parent: The parent Window to make this dialog transient to :param buttons: A buttons enum :param default: A default response """
if buttons == gtk.BUTTONS_OK: default = gtk.RESPONSE_OK return _message_dialog(type, short, long, parent=parent, buttons=buttons, default=default, **kw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_filechooser(title, parent=None, patterns=None, folder=None, filter=None, multiple=False, _before_run=None, action=None): """An open dialog. :param parent: window or None :param patterns: file match patterns :param folder: initial folder :param filter: file filter Use of filter and patterns at the same time is invalid. """
assert not (patterns and filter) if multiple: if action is not None and action != gtk.FILE_CHOOSER_ACTION_OPEN: raise ValueError('`multiple` is only valid for the action ' '`gtk.FILE_CHOOSER_ACTION_OPEN`.') action = gtk.FILE_CHOOSER_ACTION_OPEN else: assert action is not None filechooser = gtk.FileChooserDialog(title, parent, action, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) if multiple: filechooser.set_select_multiple(True) if patterns or filter: if not filter: filter = gtk.FileFilter() for pattern in patterns: filter.add_pattern(pattern) filechooser.set_filter(filter) filechooser.set_default_response(gtk.RESPONSE_OK) if folder: filechooser.set_current_folder(folder) try: if _before_run is not None: _before_run(filechooser) response = filechooser.run() if response not in (gtk.RESPONSE_OK, gtk.RESPONSE_NONE): return if multiple: return filechooser.get_filenames() else: return filechooser.get_filename() finally: _destroy(filechooser)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(title='Save', parent=None, current_name='', folder=None, _before_run=None, _before_overwrite=None): """Displays a save dialog."""
filechooser = gtk.FileChooserDialog(title, parent, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) if current_name: filechooser.set_current_name(current_name) filechooser.set_default_response(gtk.RESPONSE_OK) if folder: filechooser.set_current_folder(folder) path = None while True: if _before_run: _before_run(filechooser) _before_run = None # XXX: find better implications response = filechooser.run() if response != gtk.RESPONSE_OK: path = None break path = filechooser.get_filename() if not os.path.exists(path): break if ask_overwrite(path, parent, _before_run=_before_overwrite): break _before_overwrite = None # XXX: same _destroy(filechooser) return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_nans(df): """ Count the total number of NaNs in every column Parameters df pd.DataFrame Returns nas_df pd.DataFrame """
cols = df.columns res = [] for col in cols: length = len(df[col]) not_nas = len(df[col].dropna()) nas = length - not_nas rate = round(nas/length, 4) # add unique value uv = len(df[col].unique()) res_ = (col, nas, not_nas, rate, uv) res.append(res_) nas_df = pd.DataFrame(res, columns=['Column', 'NaNs', 'Not_NaNs', 'Rate', 'UV']) return nas_df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_project_dir(path=os.getcwd()): """Attempt to find the project root, returns None if not found"""
path_split = os.path.split(path) while path_split[1]: if in_armstrong_project(path): return path path = path_split[0] path_split = os.path.split(path) # we ran out of parents return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1] != item[:i+1]: prefix = prefix[:i] if i == 0: return '' break return prefix
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_headers(self, headers, cache_info=None): """ Prepare headers object for request (add cache information :param headers: Headers object :type headers: dict :param cache_info: Cache information to add :type cache_info: floscraper.models.CacheInfo :return: Prepared headers :rtype: dict """
if self.use_advanced and cache_info: hkeys = headers.keys() if cache_info.access_time and "If-Modified-Since" not in hkeys: headers['If-Modified-Since'] = cache_info.access_time.strftime( "%a, %d %b %Y %H:%M:%S GMT" ) if cache_info.etag and "If-None-Match" not in hkeys: headers['If-None-Match'] = cache_info.etag return headers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, url, ignore_access_time=False): """ Try to retrieve url from cache if available :param url: Url to retrieve :type url: str | unicode :param ignore_access_time: Should ignore the access time :type ignore_access_time: bool :return: (data, CacheInfo) None, None -> not found in cache None, CacheInfo -> found, but is expired data, CacheInfo -> found in cache :rtype: (None | str | unicode, None | floscraper.models.CacheInfo) """
key = hashlib.md5(url).hexdigest() accessed = self._cache_meta_get(key) if not accessed: # not previously cached self.debug("From inet {}".format(url)) return None, None if isinstance(accessed, dict): cached = CacheInfo.from_dict(accessed) else: cached = CacheInfo(accessed) now = now_utc() if now - cached.access_time > self.duration and not ignore_access_time: # cached expired -> remove self.debug("From inet (expired) {}".format(url)) return None, cached try: res = self._cache_get(key) except: self.exception("Failed to read cache") self.debug("From inet (failure) {}".format(url)) return None, None self.debug("From cache {}".format(url)) return res, cached
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, url, cache_info=None): """ Update cache information for url :param url: Update for this url :type url: str | unicode :param cache_info: Cache info :type cache_info: floscraper.models.CacheInfo :rtype: None """
key = hashlib.md5(url).hexdigest() access_time = None if not cache_info: cache_info = CacheInfo() if not access_time: cache_info.access_time = now_utc() self._cache_meta_set(key, cache_info.to_dict())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, url, html, cache_info=None): """ Put response into cache :param url: Url to cache :type url: str | unicode :param html: HTML content of url :type html: str | unicode :param cache_info: Cache Info (default: None) :type cache_info: floscraper.models.CacheInfo :rtype: None """
key = hashlib.md5(url).hexdigest() try: self._cache_set(key, html) except: self.exception("Failed to write cache") return self.update(url, cache_info)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def urisplit(uri): """ Basic URI Parser according to STD66 aka RFC3986 ('scheme', 'authority', 'path', 'query', 'fragment') """
inner_part = re.compile(r'\(\(.*?\)\)') m = inner_part.search(uri) inner_value = '' if m is not None: inner_value = uri[m.start():m.end()] uri = uri[:m.start()]+'__inner_part__'+uri[m.end():] # regex straight from STD 66 section B regex = '^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?' p = re.match(regex, uri).groups() scheme, authority, path, query, fragment = p[1], p[3], p[4], p[6], p[8] #if not path: path = None authority = authority.replace('__inner_part__', inner_value) if authority == '.': path = ''.join([authority, path]) authority = None # bugfix: '#' might be a legal character in a file name # it only has special meaning in urls if scheme not in ['http', 'https']: if fragment: path = '#'.join([path, fragment]) fragment = '' return (scheme, authority, path, query, fragment)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_authority(authority): """ Basic authority parser that splits authority into component parts ('user', 'password', 'host', 'port') """
if '@' in authority: userinfo, hostport = authority.split('@', 1) else: userinfo, hostport = None, authority if userinfo and ':' in userinfo: user, passwd = userinfo.split(':', 1) else: user, passwd = userinfo, None if hostport and ':' in hostport: host, port = hostport.split(':', 1) else: host, port = hostport, None if not host: host = None return (user, passwd, host, port)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, uri, defaults=None): """Parse the URI. uri is the uri to parse. defaults is a scheme-dependent list of values to use if there is no value for that part in the supplied URI. The return value is a tuple of scheme-dependent length. """
return tuple([self.scheme_of(uri)] + list(self.parser_for(uri)(defaults).parse(uri)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unparse(self, pieces, defaults=None): """Join the parts of a URI back together to form a valid URI. pieces is a tuble of URI pieces. The scheme must be in pieces[0] so that the rest of the pieces can be interpreted. """
return self.parser_for(pieces[0])(defaults).unparse(pieces)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parser_for(self, uri): """Return the Parser object used to parse a particular URI. Parser objects are required to have only 'parse' and 'unparse' methods. """
return self._parsers.get(self.scheme_of(uri), DefaultURIParser)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_temp(wdir, rmdir=True): """Remove all files in wdir"""
wdir = pathlib.Path(wdir) extensions = ["*.log", "*.dat", "*.txt"] for ext in extensions: for ff in wdir.glob(ext): ff.unlink() if rmdir: wdir.rmdir()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_field(wdir, shape_grid): """Extract electric field from simulation file "V_0Ereim.dat" Parameters wdir: str or pathlib.Path path to the working directory shape_grid: tuple of ints the shape of the simulation data grid Notes ----- These are the files present in the working directory bhfield.log: log file containing scattering coeffs etc (as well as definitions of the output fields) bhdebug.log: extra information (checking roundoff errors etc) E_0allf.dat: E2 = EFSQ[dimensionless] = (relative) squared amplitude of complex E-field; Ec*(Ec^*) / E0**2 E_1core.dat: E2 inside the core E_2coat.dat: E2 inside the coating E_3exte.dat: E2 at the outside of the sphere U_*.dat: U = UABS[F m-1 s-1] is the (relative) absorbed energy per unit volume and time; Ua [W m-3] / E0**2 EU_zax.txt: E2(0,0,z) and U(0,0,z) along z-axis; it may be blank if the grid does not include such points V_0Eelli.dat: vector electric field; vibration ellipse (major & minor axes), ellipticity, azimuth[deg], p-a angle (phi)[deg], handedness angle[deg] & handedness V_0Ereim.dat: vector electric field; snapshots [Re (t=0), Im (t=period/4)] V_0Helli.dat: vector magnetic field; vibration ellipse (major & minor axes), ellipticity, azimuth[deg], p-a angle (phi)[deg], E-&H-phase dif[deg], handedness angle[deg] & handedness V_0Hreim.dat: vector magnetic field; snapshots [Re (t=0), Im (t=period/4)] V_0Poynt.dat: Poynting vector <S>, EH angle, optical irradiance (intensity) (norm<S>), I(plane), -div<S> (1st-3rd), UABS & DIVSR V_1*.dat: vector fields inside the core V_2*.dat: vector fields inside the coating V_3*.dat: vector fields at the outside of the sphere """
wdir = pathlib.Path(wdir) check_simulation(wdir) field_file = wdir / "V_0Ereim.dat" a = np.loadtxt(field_file) assert shape_grid[0] == int( shape_grid[0]), "resulting x-size is not an integer" assert shape_grid[1] == int( shape_grid[1]), "resulting y-size is not an integer" Ex = a[:, 3] + 1j * a[:, 6] # Ey = a[:,4] + 1j*a[:,7] # Ez = a[:,5] + 1j*a[:,8] Exend = Ex.reshape((shape_grid[1], shape_grid[0])).transpose() return Exend
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_simulation(wdir): """ Check bhdebug.txt to make sure that you specify enough digits to overcome roundoff errors. """
wdir = pathlib.Path(wdir) field = wdir / "V_0Ereim.dat" if not (field.exists() and field.stat().st_size > 130): msg = "Output {} does not exist or is too small!".format(field) raise BHFIELDExecutionError(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def slices(src_path): ''' Return slices as a flat list ''' pages = list_slices(src_path) slices = [] for page in pages: slices.extend(page.slices) return slices
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def artboards(src_path): ''' Return artboards as a flat list ''' pages = list_artboards(src_path) artboards = [] for page in pages: artboards.extend(page.artboards) return artboards
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_response(self, response_json, signed_id_name='transactionid'): """ Verify the response message. :param response_json: :param signed_id_name: :return: """
auth_json = response_json.get('auth', {}) nonce = auth_json.get('nonce', '') timestamp = auth_json.get('timestamp', '') signature = binascii.unhexlify(auth_json.get('signature', '')) signed_id = response_json.get(signed_id_name, '') return self.verify_signature(signature=signature, nonce=nonce, timestamp=timestamp, signed_id=signed_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def soup(self): ''' Returns HTML as a BeautifulSoup element. ''' components_soup = Tag(name=self.tagname, builder=BUILDER) components_soup.attrs = self.attributes for c in flatten(self.components): if hasattr(c, 'soup'): components_soup.append(c.soup()) elif type(c) in (str, ): # components_soup.append(BeautifulSoup(str(c))) components_soup.append(str(c)) # else: # Component should not be integrated # pass return components_soup
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plugins(self, deduplicate=False): ''' Returns a flattened list of all plugins used by page components. ''' plugins = [] for c in self.components: if hasattr(c, 'plugins'): plugins += c.plugins() elif isinstance(c, Lib): plugins.append(c) elif hasattr(c, 'is_plugin') and c.is_plugin: plugins.append(c) if deduplicate: plugins = list(OrderedDict.fromkeys(plugins)) return plugins
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def soup(self): ''' Running plugins and adding an HTML doctype to the generated Tag HTML. ''' dom = BeautifulSoup('<!DOCTYPE html>') # BeautifulSoup behaves differently if lxml is installed or not, # and will create a basic HTML structure if lxml is installed. if len(dom) > 1: list(dom.children)[1].replaceWith('') # Removing default content soup = Element.soup(self) dom.append(soup) for plugin in self.plugins(deduplicate=True): dom = plugin(dom) return dom
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _eq__(self, other): """ Compare the current place object to another passed to the comparison method. The two place objects must have the same identification, even if some of their attributes might be different. @param other: a ``Place`` instance to compare with the current place object. @return: ``True`` if the given place corresponds to the current place; ``False`` otherwise. """
return self.place_id and other.place_id \ and self.place_id == other.place_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(payload): """ Build a ``Place`` instance from the specified JSON object. @param payload: JSON representation of a place:: { "area_id": string, "address": { component_type: string, } \ [ { "locale": string, component_type: string, }, ], "category": string, "contacts": [ [ name:string, value:string, is_primary:boolean ], ], "cover_photo_id": string, "cover_photo_url": string, "locale": string, "location": coordinates, "timezone": integer } where: * ``area_id`` (optional): identification of the geographic area where the place is located in. This parameter is optional if the parameter ``address`` is passed. Both ``area_id`` and ``address`` can be passed to the function. If this parameter is passed to the function, it takes precedence over any administrative division of the same level or larger that would be defined as part of the address components. * ``address`` (required): postal address of the place, composed of one or more address components, which textual information is written in the specified locale. An address component is defined with a component type and its value. The component type is a string representation of an item of the enumeration ``AddressComponentType``. * ``category_id`` (optional): category qualifying this place. * ``contacts`` (optional): list of properties such as e-mail addresses, phone numbers, etc., in respect of the electronic business card specification (vCard). The contact information is represented by a list of tuples of the following form:: where: * ``name`` (required): type of this contact information, which can be one of these standard names in respect of the electronic business card specification (vCard). * ``value`` (required): value of this contact information representing by a string, such as ``+84.01272170781``, the formatted value for a telephone number property. * ``is_primary`` (optional): indicate whether this contact information is the primary for this place. By default, the first contact information of a given type is the primary of this place. * ``cover_photo_id``: identification of the cover photo of the place, if any defined. * ``cover_photo_url``: Uniform Resource Locator (URL) that specifies the location of the cover photo of the place, if any defined. The client application can use this URL and append the query parameter ``size`` to specify a given pixel resolution of this photo, such as ``thumbnail``, ``small``, ``medium``, ``large``. * ``boundaries`` (optional): a collection of one or more polygons that delimit the topological space of the place. All of the polygons are within the spatial reference system. It corresponds to an array of vertices. There must be at least three vertices. Each vertex is a tuple composed of a longitude, a latitude, and a altitude:: [ longitude, latitude, altitude ] Note that the first and last vertices must not be identical; a polygon is "auto-closed" between the first and last vertices. * ``locale`` (required): locale of the textual information that describes this place. A locale corresponds to a tag respecting RFC 4646, i.e., a ISO 639-3 alpha-3 code element optionally followed by a dash character ``-`` and a ISO 3166-1 alpha-2 code (referencing the country that this language might be specific to). For example: ``eng`` (which denotes a standard English), ``eng-US`` (which denotes an American English). * ``location`` (optional): geographic coordinates of the location of the place represented with the following JSON structure:: { "accuracy": decimal "altitude": decimal, "latitude": decimal, "longitude": decimal, } where: * ``accuracy`` (optional): accuracy of the place's position in meters. * ``altitude`` (optional): altitude in meters of the place. * ``latitude`` (required): latitude-angular distance, expressed in decimal degrees (WGS84 datum), measured from the center of the Earth, of a point north or south of the Equator corresponding to the place's location. * ``longitude`` (required): longitude-angular distance, expressed in decimal degrees (WGS84 datum), measured from the center of the Earth, of a point east or west of the Prime Meridian corresponding to the place's location. .. note:: The parameter ``location`` is ignored when the parameter ``boundaries`` is provided. The platform computes the coordinates of the geometric center (centroid) of the polygon representing the boundaries of the place. It corresponds to the arithmetic mean ("average") position of all the points in the shape. * ``timezone`` (required): time zone at the place's location. It is the difference between the time at this location and UTC (Coordinated Universal Time). UTC is also known as GMT or Greenwich Mean Time or Zulu Time. @note: the name of the place corresponds to the address component ``recipient_name``. @return: a ``Place`` instance or ``None`` if the JSON payload is nil. """
return payload and \ Place([ (float(lon), float(lat), float(alt)) for (lon, lat, alt) in payload['boundaries']] if payload.get('boundaries') else GeoPoint.from_json(payload['location']), address=payload.get('address') and ( Place.__parse_address__(payload['address']) if isinstance(payload['address'], dict) else [ Place.__parse_address__(address) for address in payload['address'] ]), category_id=cast.string_to_uuid(payload.get('category_id')), area_id=cast.string_to_uuid(payload.get('area_id')), contacts=payload.get('contacts') and [ (cast.string_to_enum(contact[0], ContactPropertyName), # name contact[1], # value contact[2] if len(contact) >= 3 else None, # is_primary contact[3] if len(contact) == 4 else None) # is_verified for contact in payload['contacts'] ], cover_photo_id=cast.string_to_uuid(payload.get('cover_photo_id')), cover_photo_url=payload.get('cover_photo_url'), locale=cast.string_to_locale(payload.get('locale')) and DEFAULT_LOCALE, object_status=payload.get("object_status"), place_id=cast.string_to_uuid(payload.get('place_id')), timezone=payload.get('timezone'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_classes(package_str): '''Load all classes from modules of a given `package_str`. All class instances are stored in a case-insensitive `dict` and returned. If a package doesn't contain any class `None` is returned''' _logger.debug('Loading all modules from %s', package_str) package = importlib.import_module(package_str) package_path = package.__path__ _logger.debug('Searching for modules in package %s (%s)', package_str, package_path) for _, name, ispkg in pkgutil.iter_modules(package_path, package_str + "."): if not ispkg: _logger.debug('Found module: %s', name) module = importlib.import_module(name) if hasattr(module, CLASS_NAME_ATTR): class_name = getattr(module, CLASS_NAME_ATTR) _logger.debug('Found class: %s', class_name) clasz = getattr(module, class_name) if package_str not in _dynamo_cache: _dynamo_cache[package_str] = CaseInsensitiveDict() if class_name not in _dynamo_cache[package_str]: _dynamo_cache[package_str][class_name] = clasz _logger.debug('Correctly loaded class: %s from: "%s"', class_name, package_str) else: _logger.warning('Already loaded class: %s from: "%s"', class_name, package_str) else: _logger.warning('Module inside %s does not contain required attribute: %s', package_str, CLASS_NAME_ATTR) else: _logger.warning('Ignoring package: %s', name) if package_str in _dynamo_cache: return _dynamo_cache[package_str] else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get(package_str, classname): '''Retrieve from the internal cache a class instance. All arguments are case-insensitive''' if (package_str in _dynamo_cache) and (classname in _dynamo_cache[package_str]): return _dynamo_cache[package_str][classname] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ex_literal(val): """An int, float, long, bool, string, or None literal with the given value. """
if val is None: return ast.Name('None', ast.Load()) elif isinstance(val, int): return ast.Num(val) elif isinstance(val, bool): return ast.Name(bytes(val), ast.Load()) elif isinstance(val, str): return ast.Str(val) raise TypeError(u'no literal for {0}'.format(type(val)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ex_varassign(name, expr): """Assign an expression into a single variable. The expression may either be an `ast.expr` object or a value to be used as a literal. """
if not isinstance(expr, ast.expr): expr = ex_literal(expr) return ast.Assign([ex_lvalue(name)], expr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ex_call(func, args): """A function-call expression with only positional parameters. The function may be an expression or the name of a function. Each argument may be an expression or a value to be used as a literal. """
if isinstance(func, str): func = ex_rvalue(func) args = list(args) for i in range(len(args)): if not isinstance(args[i], ast.expr): args[i] = ex_literal(args[i]) if sys.version_info[:2] < (3, 5): return ast.Call(func, args, [], None, None) else: return ast.Call(func, args, [])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_func(arg_names, statements, name='_the_func', debug=False): """Compile a list of statements as the body of a function and return the resulting Python function. If `debug`, then print out the bytecode of the compiled function. """
func_def = ast.FunctionDef( name=name, args=ast.arguments( args=[ast.arg(arg=n, annotation=None) for n in arg_names], kwonlyargs=[], kw_defaults=[], defaults=[ex_literal(None) for _ in arg_names], ), body=statements, decorator_list=[], ) mod = ast.Module([func_def]) ast.fix_missing_locations(mod) prog = compile(mod, '<generated>', 'exec') # Debug: show bytecode. if debug: dis.dis(prog) for const in prog.co_consts: if isinstance(const, types.CodeType): dis.dis(const) the_locals = {} exec(prog, {}, the_locals) return the_locals[name]