output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def extract_objects(self, fname, type_filter=None): '''Extract objects from a source file Args: fname(str): Name of file to read from type_filter (class, optional): Object class to filter results Returns: List of objects extracted from the file. ''' objects = [] if fname in se...
Write a Python 3 function that can extract objects from a source file
As a Python code composer, you craft elegant and concise scripts.
Extract object declarations from a text buffer containing a verilog file.
Can you tell what is the following Python 3 function doing def extract_objects_from_source(self, text, type_filter=None): '''Extract object declarations from a text buffer Args: text (str): Source code to parse type_filter (class, optional): Object class to filter results Returns: List of...
You are a Python code architect, reviewing and designing scalable and efficient code
def load_json_from_file(file_path): """Load schema from a JSON file""" try: with open(file_path) as f: json_data = json.load(f) except ValueError as e: raise ValueError('Given file {} is not a valid JSON file: {}'.format(file_path, e)) else: return json_data
Write a Python 3 function that can load schema from a JSON file
As a Python code analyst, you investigate and solve complex coding mysteries
def load_json_from_string(string): """Load schema from JSON string""" try: json_data = json.loads(string) except ValueError as e: raise ValueError('Given string is not valid JSON: {}'.format(e)) else: return json_data
Write a Python 3 function that can load schema from JSON string
You are a Python code architect, reviewing and designing scalable and efficient code
def fetch(method, uri, params_prefix=None, **params): """Fetch the given uri and return the contents of the response.""" params = urlencode(_prepare_params(params, params_prefix)) binary_params = params.encode('ASCII') # build the HTTP request url = "https://%s/%s.xml" % (CHALLONGE_API_URL, uri) ...
How would you implement a function in Python 3 that fetches the given uri and return the contents of the response.
You are a Python code generator, capable of creating scripts from specifications.
def fetch_and_parse(method, uri, params_prefix=None, **params): """Fetch the given uri and return the root Element of the response.""" doc = ElementTree.parse(fetch(method, uri, params_prefix, **params)) return _parse(doc.getroot())
Create a Python 3 function for fetching the given uri and return the root Element of the response.
As a Python code translator, you convert algorithms and pseudocode into Python.
Recursively convert an Element into python data types
Given the following Python 3 function, write the documentation def _parse(root): if root.tag == "nil-classes": return [] elif root.get("type") == "array": return [_parse(child) for child in root] d = {} for child in root: type = child.get("type") or "string" if child.ge...
As a Python code composer, you craft elegant and concise scripts.
Prepares parameters to be sent to challonge. com.
How would you explain what the following Python 3 function does def _prepare_params(dirty_params, prefix=None): params = {} for k, v in dirty_params.items(): if hasattr(v, "isoformat"): v = v.isoformat() elif isinstance(v, bool): # challonge.com only accepts lowercase tru...
As a Python code composer, you craft elegant and concise scripts.
def expandDescendants(self, branches): """ Expand descendants from list of branches :param list branches: list of immediate children as TreeOfContents objs :return: list of all descendants """ return sum([b.descendants() for b in branches], []) + \ [b.source ...
Implement a function in Python 3 to expand descendants from list of branches as TreeOfContents objs
As a Python code composer, you craft elegant and concise scripts.
def parseBranches(self, descendants): """ Parse top level of markdown :param list elements: list of source objects :return: list of filtered TreeOfContents objects """ parsed, parent, cond = [], False, lambda b: (b.string or '').strip() for branch in filter(cond,...
Write a Python 3 function for parsing top level of markdown tree of contents.
You are a Python code analyst, evaluating scripts for potential improvements.
def fromMarkdown(md, *args, **kwargs): """ Creates abstraction using path to file :param str path: path to markdown file :return: TreeOfContents object """ return TOC.fromHTML(markdown(md, *args, **kwargs))
Write a Python 3 function for creating a TreeOfContents object from a markdown string.
As a python code expert, you are capable of creating scripts from specifications.
Creates a TreeOfContents object from a HTML string.
Given the following Python 3 function, write the documentation def fromHTML(html, *args, **kwargs): source = BeautifulSoup(html, 'html.parser', *args, **kwargs) return TOC('[document]', source=source, descendants=source.children)
You are a Python code analyst, evaluating scripts for potential improvements.
def from_data(cls, type, **data): """Create an attachment from data. :param str type: attachment type :param kwargs data: additional attachment data :return: an attachment subclass object :rtype: `~groupy.api.attachments.Attachment` """ try: return cl...
Write a Python 3 script for creating an attachment from data.
As a Python code analyst, you investigate and solve complex coding mysteries
def from_file(self, fp): """Create a new image attachment from an image file. :param file fp: a file object containing binary image data :return: an image attachment :rtype: :class:`~groupy.api.attachments.Image` """ image_urls = self.upload(fp) return Image(imag...
Write a Python 3 script for creating a new image attachment from an image file.
You are a Python code architect, reviewing and designing scalable and efficient code
Upload image data to the image service.
Here you have a function in Python 3, explain what it does def upload(self, fp): url = utils.urljoin(self.url, 'pictures') response = self.session.post(url, data=fp.read()) image_urls = response.data return image_urls
You are a Python code generator, capable of creating scripts from specifications.
Download the binary data of an image attachment.
Explain what the following Python 3 code does def download(self, image, url_field='url', suffix=None): url = getattr(image, url_field) if suffix is not None: url = '.'.join(url, suffix) response = self.session.get(url) return response.content
As a Python code analyst, you investigate and solve complex coding mysteries
Downloads the binary data of an image attachment at preview size.
Can you tell what is the following Python 3 function doing def download_preview(self, image, url_field='url'): return self.download(image, url_field=url_field, suffix='preview')
You are a Python code analyst, evaluating scripts for potential improvements.
Downloads the binary data of an image attachment at large size.
Make a summary of the following Python 3 code def download_large(self, image, url_field='url'): return self.download(image, url_field=url_field, suffix='large')
You are a Python code generator, capable of creating scripts from specifications.
def download_avatar(self, image, url_field='url'): """Downlaod the binary data of an image attachment at avatar size. :param str url_field: the field of the image with the right URL :return: binary image data :rtype: bytes """ return self.download(image, url_field=url_f...
Can you implement a function in Python 3 that downloads the binary data of an image attachment at avatar size.
As a Python code composer, you craft elegant and concise scripts.
Iterate through results from all pages.
How would you explain what the following Python 3 function does def autopage(self): while self.items: yield from self.items self.items = self.fetch_next()
You are a Python code analyst, evaluating scripts for potential improvements.
def detect_mode(cls, **params): """Detect which listing mode of the given params. :params kwargs params: the params :return: one of the available modes :rtype: str :raises ValueError: if multiple modes are detected """ modes = [] for mode in cls.modes: ...
Write a Python 3 function that can detect which listing mode of the given params.
As a Python code translator, you convert algorithms and pseudocode into Python.
Set the params so that the next page is fetched.
Given the following Python 3 function, write the documentation def set_next_page_params(self): if self.items: index = self.get_last_item_index() self.params[self.mode] = self.get_next_page_param(self.items[index])
You are a Python code generator, capable of creating scripts from specifications.
List the users you have blocked.
Explain what the following Python 3 code does def list(self): params = {'user': self.user_id} response = self.session.get(self.url, params=params) blocks = response.data['blocks'] return [Block(self, **block) for block in blocks]
You are a Python code analyst, evaluating scripts for potential improvements.
def between(self, other_user_id): """Check if there is a block between you and the given user. :return: ``True`` if the given user has been blocked :rtype: bool """ params = {'user': self.user_id, 'otherUser': other_user_id} response = self.session.get(self.url, params=p...
Write a Python 3 function that can check if there is a block between you and the given user.
You are a Python code generator, capable of creating scripts from specifications.
Block the given user.
Can you generate the documentation for the following Python 3 function def block(self, other_user_id): params = {'user': self.user_id, 'otherUser': other_user_id} response = self.session.post(self.url, params=params) block = response.data['block'] return Block(self, **block)
As a Python code composer, you craft elegant and concise scripts.
def unblock(self, other_user_id): """Unblock the given user. :param str other_user_id: the ID of the user to unblock :return: ``True`` if successful :rtype: bool """ params = {'user': self.user_id, 'otherUser': other_user_id} response = self.session.delete(self.u...
Write a Python 3 function for unblocking the given user.
As a python code expert, you are capable of creating scripts from specifications.
List a page of chats.
Given the following Python 3 function, write the documentation def list(self, page=1, per_page=10): return pagers.ChatList(self, self._raw_list, per_page=per_page, page=page)
You are a Python code architect, reviewing and designing scalable and efficient code
Return a page of group messages.
Can you generate the documentation for the following Python 3 function def list(self, before_id=None, since_id=None, after_id=None, limit=20): return pagers.MessageList(self, self._raw_list, before_id=before_id, after_id=after_id, since_id=since_id, ...
You are a Python code generator, capable of creating scripts from specifications.
Return a page of group messages created since a message.
Here you have a function in Python 3, explain what it does def list_since(self, message_id, limit=None): return self.list(since_id=message_id, limit=limit)
You are a Python code architect, reviewing and designing scalable and efficient code
def list_after(self, message_id, limit=None): """Return a page of group messages created after a message. This is used to page forwards through messages. :param str message_id: the ID of a message :param int limit: maximum number of messages per page :return: group messages ...
Write a Python 3 function that can return a page of group messages created after a message.
You are a Python code architect, reviewing and designing scalable and efficient code
Return all group messages created before a message.
Make a summary of the following Python 3 code def list_all_before(self, message_id, limit=None): return self.list_before(message_id, limit=limit).autopage()
You are a Python code generator, capable of creating scripts from specifications.
def list_all_after(self, message_id, limit=None): """Return all group messages created after a message. :param str message_id: the ID of a message :param int limit: maximum number of messages per page :return: group messages :rtype: generator """ return self.list...
Can you create a Python 3 function that returns all group messages created after a message.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a new message in the group.
Explain what the following Python 3 code does def create(self, text=None, attachments=None, source_guid=None): message = { 'source_guid': source_guid or str(time.time()), } if text is not None: message['text'] = text if attachments is not None: messa...
As a python code expert, you are capable of creating scripts from specifications.
def list(self, before_id=None, since_id=None, **kwargs): """Return a page of direct messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``. :param str before_id: message ID for paging backwards :param str sin...
How would you code a function in Python 3 to return a page of direct messages.
You are a Python code architect, reviewing and designing scalable and efficient code
Return all direct messages.
Can you generate the documentation for the following Python 3 function def list_all(self, before_id=None, since_id=None, **kwargs): return self.list(before_id=before_id, since_id=since_id, **kwargs).autopage()
As a Python code analyst, you investigate and solve complex coding mysteries
Add a user to the group.
How would you explain what the following Python 3 function does def add(self, nickname, email=None, phone_number=None, user_id=None): member = { 'nickname': nickname, 'email': email, 'phone_number': phone_number, 'user_id': user_id, } return self.a...
As a Python code translator, you convert algorithms and pseudocode into Python.
Adds multiple users to the group at once.
Make a summary of the following Python 3 code def add_multiple(self, *users): guid = uuid.uuid4() for i, user_ in enumerate(users): user_['guid'] = '{}-{}'.format(guid, i) payload = {'members': users} url = utils.urljoin(self.url, 'add') response = self.session.post(...
You are a Python code architect, reviewing and designing scalable and efficient code
Check for results of a membership request.
Given the following Python 3 function, write the documentation def check(self, results_id): path = 'results/{}'.format(results_id) url = utils.urljoin(self.url, path) response = self.session.get(url) if response.status_code == 503: raise exceptions.ResultsNotReady(response) ...
As a Python code composer, you craft elegant and concise scripts.
Update your own membership.
Can you generate the documentation for the following Python 3 function def update(self, nickname=None, **kwargs): url = self.url + 'hips/update' payload = { 'membership': { 'nickname': nickname, }, } payload['membership'].update(kwargs) res...
As a python code expert, you are capable of creating scripts from specifications.
Removes a member from the group.
How would you explain what the following Python 3 function does def remove(self, membership_id): path = '{}/remove'.format(membership_id) url = utils.urljoin(self.url, path) payload = {'membership_id': membership_id} response = self.session.post(url, json=payload) return response...
As a Python code analyst, you investigate and solve complex coding mysteries
Post a direct message to the user.
Can you generate a brief explanation for the following Python 3 code def post(self, text=None, attachments=None, source_guid=None): return self.messages.create(text=text, attachments=attachments, source_guid=source_guid)
You are a Python code architect, reviewing and designing scalable and efficient code
def add_to_group(self, group_id, nickname=None): """Add the member to another group. If a nickname is not provided the member's current nickname is used. :param str group_id: the group_id of a group :param str nickname: a new nickname :return: a membership request :rtyp...
How would you implement a function in Python 3 that adds the member to another group.
You are a Python code analyst, evaluating scripts for potential improvements.
Check for and fetch the results if ready.
Can you generate the documentation for the following Python 3 function def check_if_ready(self): try: results = self.manager.check(self.results_id) except exceptions.ResultsNotReady as e: self._is_ready = False self._not_ready_exception = e except exceptions.R...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_failed_requests(self, results): """Return the requests that failed. :param results: the results of a membership request check :type results: :class:`list` :return: the failed requests :rtype: generator """ data = {member['guid']: member for member in resu...
How would you implement a function in Python 3 that returns the requests that failed.
You are a Python code analyst, evaluating scripts for potential improvements.
Return the newly added members.
Here you have a function in Python 3, explain what it does def get_new_members(self, results): for member in results: guid = member.pop('guid') yield Member(self.manager, self.group_id, **member) member['guid'] = guid
You are a Python code architect, reviewing and designing scalable and efficient code
def is_ready(self, check=True): """Return ``True`` if the results are ready. If you pass ``check=False``, no attempt is made to check again for results. :param bool check: whether to query for the results :return: ``True`` if the results are ready :rtype: bool "...
Write a Python 3 function that can return True if the results are ready.
As a Python code translator, you convert algorithms and pseudocode into Python.
def poll(self, timeout=30, interval=2): """Return the results when they become ready. :param int timeout: the maximum time to wait for the results :param float interval: the number of seconds between checks :return: the membership request result :rtype: :class:`~groupy.api.membe...
Write a Python 3 function for polling the membership request for the result set to become ready.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the results now.
Explain what the following Python 3 code does def get(self): if self._expired_exception: raise self._expired_exception if self._not_ready_exception: raise self._not_ready_exception return self.results
As a Python code analyst, you investigate and solve complex coding mysteries
List the groups by page.
How would you explain what the following Python 3 function does def list(self, page=1, per_page=10, omit=None): return pagers.GroupList(self, self._raw_list, page=page, per_page=per_page, omit=omit)
You are a Python code analyst, evaluating scripts for potential improvements.
List all groups. Since the order of groups is determined by recent activity, this is the recommended way to obtain a list of all groups. See :func:`~groupy.api.groups.Groups.list` for details about ``omit``. :param int per_page: number of groups per page :param int omit: a comm...
Here you have a function in Python 3, explain what it does def list_all(self, per_page=10, omit=None): return self.list(per_page=per_page, omit=omit).autopage()
You are a Python code architect, reviewing and designing scalable and efficient code
List all former groups.
Can you generate the documentation for the following Python 3 function def list_former(self): url = utils.urljoin(self.url, 'former') response = self.session.get(url) return [Group(self, **group) for group in response.data]
As a python code expert, you are capable of creating scripts from specifications.
def get(self, id): """Get a single group by ID. :param str id: a group ID :return: a group :rtype: :class:`~groupy.api.groups.Group` """ url = utils.urljoin(self.url, id) response = self.session.get(url) return Group(self, **response.data)
How would you implement a function in Python 3 that gets a single group by ID.
You are a Python code generator, capable of creating scripts from specifications.
Create a new group.
Explain what the following Python 3 code does def create(self, name, description=None, image_url=None, share=None, **kwargs): payload = { 'name': name, 'description': description, 'image_url': image_url, 'share': share, } payload.update(kwargs) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Update the details of a group.
Can you generate a brief explanation for the following Python 3 code def update(self, id, name=None, description=None, image_url=None, office_mode=None, share=None, **kwargs): """Update the details of a group. .. note:: There are significant bugs in this endpoint! ...
You are a Python code analyst, evaluating scripts for potential improvements.
def destroy(self, id): """Destroy a group. :param str id: a group ID :return: ``True`` if successful :rtype: bool """ path = '{}/destroy'.format(id) url = utils.urljoin(self.url, path) response = self.session.post(url) return response.ok
Write a Python 3 script for destroying a group s ID .
You are a Python code analyst, evaluating scripts for potential improvements.
def join(self, group_id, share_token): """Join a group using a share token. :param str group_id: the group_id of a group :param str share_token: the share token :return: the group :rtype: :class:`~groupy.api.groups.Group` """ path = '{}/join/{}'.format(group_id, ...
Write a Python 3 function for joining a group using a share token.
As a Python code composer, you craft elegant and concise scripts.
Rejoin a former group.
Here you have a function in Python 3, explain what it does def rejoin(self, group_id): url = utils.urljoin(self.url, 'join') payload = {'group_id': group_id} response = self.session.post(url, json=payload) return Group(self, **response.data)
You are a Python code generator, capable of creating scripts from specifications.
def change_owners(self, group_id, owner_id): """Change the owner of a group. .. note:: you must be the owner to change owners :param str group_id: the group_id of a group :param str owner_id: the ID of the new owner :return: the result :rtype: :class:`~groupy.api.groups...
Write a Python 3 function that can change the owner of a group.
As a Python code analyst, you investigate and solve complex coding mysteries
def update(self, name=None, description=None, image_url=None, office_mode=None, share=None, **kwargs): """Update the details of the group. :param str name: group name (140 characters maximum) :param str description: short description (255 characters maximum) :param str im...
Create a Python 3 function for updating the details of the group.
As a Python code composer, you craft elegant and concise scripts.
Refresh the group from the server in place.
Can you generate a brief explanation for the following Python 3 code def refresh_from_server(self): group = self.manager.get(id=self.id) self.__init__(self.manager, **group.data)
You are a Python code generator, capable of creating scripts from specifications.
def create_bot(self, name, avatar_url=None, callback_url=None, dm_notification=None, **kwargs): """Create a new bot in a particular group. :param str name: bot name :param str avatar_url: the URL of an image to use as an avatar :param str callback_url: a POST-back URL...
Write a Python 3 function for creating a new bot in a particular group.
As a Python code composer, you craft elegant and concise scripts.
Get your membership. Note that your membership may not exist. For example, you do not have a membership in a former group. Also, the group returned by the API when rejoining a former group does not contain your membership. You must call :func:`refresh_from_server` to update the list of ...
How would you explain what the following Python 3 function does def get_membership(self): user_id = self._user.me['user_id'] for member in self.members: if member.user_id == user_id: return member raise exceptions.MissingMembershipError(self.group_id, user_id)
You are a Python code generator, capable of creating scripts from specifications.
def update_membership(self, nickname=None, **kwargs): """Update your own membership. Note that this fails on former groups. :param str nickname: new nickname :return: updated membership :rtype: :class:`~groupy.api.members.Member` """ return self.memberships.upda...
Write a Python 3 function for updating your own membership. Note that this fails on former groups. :param str nickname: new nickname :return: updated membership :rtype: :class:`~groupy.api.members.Member`
You are a Python code analyst, evaluating scripts for potential improvements.
Join a base url with a relative path.
Can you tell what is the following Python 3 function doing def urljoin(base, path=None): # /foo/bar + baz makes /foo/bar/baz instead of /foo/baz if path is None: url = base else: if not base.endswith('/'): base += '/' url = urllib.parse.urljoin(base, str(path)) return...
As a Python code analyst, you investigate and solve complex coding mysteries
Parse a group s share url.
How would you explain what the following Python 3 function does def parse_share_url(share_url): *__, group_id, share_token = share_url.rstrip('/').split('/') return group_id, share_token
As a python code expert, you are capable of creating scripts from specifications.
def get_rfc3339(when): """Return an RFC 3339 timestamp. :param datetime.datetime when: a datetime in UTC :return: RFC 3339 timestamp :rtype: str """ microseconds = format(when.microsecond, '04d')[:4] rfc3339 = '%Y-%m-%dT%H:%M:%S.{}Z' return when.strftime(rfc3339.format(microseconds))
Write a Python 3 script to return an RFC 3339 timestamp.
You are a Python code architect, reviewing and designing scalable and efficient code
def make_filter(**tests): """Create a filter from keyword arguments.""" tests = [AttrTest(k, v) for k, v in tests.items()] return Filter(tests)
Write a Python 3 script to create a filter from keyword arguments.
As a Python code translator, you convert algorithms and pseudocode into Python.
def find(self, objects): """Find exactly one match in the list of objects. :param objects: objects to filter :type objects: :class:`list` :return: the one matching object :raises groupy.exceptions.NoMatchesError: if no objects match :raises groupy.exceptions.MultipleMatc...
How would you code a function in Python 3 to find exactly one match in the list of objects.
You are a Python code generator, capable of creating scripts from specifications.
def list(self): """Return a list of bots. :return: all of your bots :rtype: :class:`list` """ response = self.session.get(self.url) return [Bot(self, **bot) for bot in response.data]
How would you implement a function in Python 3 that returns a list of your bots.
As a python code expert, you are capable of creating scripts from specifications.
def create(self, name, group_id, avatar_url=None, callback_url=None, dm_notification=None, **kwargs): """Create a new bot in a particular group. :param str name: bot name :param str group_id: the group_id of a group :param str avatar_url: the URL of an image to use as an ...
Implement a Python 3 function for creating a new bot in a particular group.
You are a Python code analyst, evaluating scripts for potential improvements.
Post a new message as a bot to its room.
Can you generate the documentation for the following Python 3 function def post(self, bot_id, text, attachments=None): url = utils.urljoin(self.url, 'post') payload = dict(bot_id=bot_id, text=text) if attachments: payload['attachments'] = [a.to_json() for a in attachments] ...
As a python code expert, you are capable of creating scripts from specifications.
def destroy(self, bot_id): """Destroy a bot. :param str bot_id: the ID of the bot to destroy :return: ``True`` if successful :rtype: bool """ url = utils.urljoin(self.url, 'destroy') payload = {'bot_id': bot_id} response = self.session.post(url, json=payl...
How would you implement a function in Python 3 that destroys a bot. :param str bot_id: the ID of the bot to destroy :return: ``True`` if successful :rtype: bool
As a Python code composer, you craft elegant and concise scripts.
def post(self, text, attachments=None): """Post a message as the bot. :param str text: the text of the message :param attachments: a list of attachments :type attachments: :class:`list` :return: ``True`` if successful :rtype: bool """ return self.manager....
Write a Python 3 script for posting a message as the bot.
You are a Python code generator, capable of creating scripts from specifications.
def flatten_until(is_leaf, xs): """ Flatten a nested sequence. A sequence could be a nested list of lists or tuples or a combination of both :param is_leaf: Predicate. Predicate to determine whether an item in the iterable `xs` is a leaf node or not. :param xs: Iterable. Neste...
Can you create a Python 3 function that flattens a nested sequence.
As a Python code composer, you craft elegant and concise scripts.
def flip(f): """ Calls the function f by flipping the first two positional arguments """ def wrapped(*args, **kwargs): return f(*flip_first_two(args), **kwargs) f_spec = make_func_curry_spec(f) return curry_by_spec(f_spec, wrapped)
Implement a Python 3 function for calling the function f by flipping the first two positional arguments
As a Python code analyst, you investigate and solve complex coding mysteries
A persistent stale - free memoization decorator.
Can you tell what is the following Python 3 function doing def cachier(stale_after=None, next_time=False, pickle_reload=True, mongetter=None): """A persistent, stale-free memoization decorator. The positional and keyword arguments to the wrapped function must be hashable (i.e. Python's immutabl...
You are a Python code generator, capable of creating scripts from specifications.
def defineID(defid): """Search for UD's definition ID and return list of UrbanDefinition objects. Keyword arguments: defid -- definition ID to search for (int or str) """ json = _get_urban_json(UD_DEFID_URL + urlquote(str(defid))) return _parse_urban_json(json)
Implement a Python 3 function for searching for UD s definition ID and return list of UrbanDefinition objects.
You are a Python code analyst, evaluating scripts for potential improvements.
def has_external_dependency(name): 'Check that a non-Python dependency is installed.' for directory in os.environ['PATH'].split(':'): if os.path.exists(os.path.join(directory, name)): return True return False
Write a Python 3 function that can check that a non - Python dependency is installed.
You are a Python code analyst, evaluating scripts for potential improvements.
def with_vtk(plot=True): """ Tests VTK interface and mesh repair of Stanford Bunny Mesh """ mesh = vtki.PolyData(bunny_scan) meshfix = pymeshfix.MeshFix(mesh) if plot: print('Plotting input mesh') meshfix.plot() meshfix.repair() if plot: print('Plotting repaired mesh') ...
Write a Python 3 function that can test VTK interface and repair of Stanford Bunny Mesh
You are a Python code generator, capable of creating scripts from specifications.
Loads triangular mesh from vertex and face numpy arrays.
Make a summary of the following Python 3 code def load_arrays(self, v, f): # Check inputs if not isinstance(v, np.ndarray): try: v = np.asarray(v, np.float) if v.ndim != 2 and v.shape[1] != 3: raise Exception('Invalid vertex format. Shape ...
You are a Python code analyst, evaluating scripts for potential improvements.
Return the surface mesh
Explain what the following Python 3 code does def mesh(self): triangles = np.empty((self.f.shape[0], 4)) triangles[:, -3:] = self.f triangles[:, 0] = 3 return vtki.PolyData(self.v, triangles, deep=False)
As a Python code analyst, you investigate and solve complex coding mysteries
Plot the mesh. Parameters ---------- show_holes : bool, optional Shows boundaries. Default True
Can you generate a brief explanation for the following Python 3 code def plot(self, show_holes=True): if show_holes: edges = self.mesh.extract_edges(boundary_edges=True, feature_edges=False, manifold_edges=False)...
As a Python code analyst, you investigate and solve complex coding mysteries
def repair(self, verbose=False, joincomp=False, remove_smallest_components=True): """Performs mesh repair using MeshFix's default repair process. Parameters ---------- verbose : bool, optional Enables or disables debug printing. Disabled by default. ...
How would you implement a function in Python 3 that performs a mesh repair using MeshFix s default repair process.
As a Python code translator, you convert algorithms and pseudocode into Python.
def write(self, filename, binary=True): """Writes a surface mesh to disk. Written file may be an ASCII or binary ply, stl, or vtk mesh file. Parameters ---------- filename : str Filename of mesh to be written. Filetype is inferred from the exten...
Create a Python 3 function for writing a surface mesh to disk.
You are a Python code analyst, evaluating scripts for potential improvements.
def scrape(url, params=None, user_agent=None): ''' Scrape a URL optionally with parameters. This is effectively a wrapper around urllib2.urlopen. ''' headers = {} if user_agent: headers['User-Agent'] = user_agent data = params and six.moves.urllib.parse.urlencode(params) or None ...
How would you implement a function in Python 3 that scrapes a URL optionally with parameters.
You are a Python code architect, reviewing and designing scalable and efficient code
def pdftoxml(pdfdata, options=""): """converts pdf file to xml file""" pdffout = tempfile.NamedTemporaryFile(suffix='.pdf') pdffout.write(pdfdata) pdffout.flush() xmlin = tempfile.NamedTemporaryFile(mode='r', suffix='.xml') tmpxml = xmlin.name # "temph.xml" cmd = 'pdftohtml -xml -nodrm -zo...
Can you implement a function in Python 3 that converts pdf file to xml file
You are a Python code generator, capable of creating scripts from specifications.
def execute(query, data=None): """ Execute an arbitrary SQL query given by query, returning any results as a list of OrderedDicts. A list of values can be supplied as an, additional argument, which will be substituted into question marks in the query. """ connection = _State.connection() ...
Create a Python 3 function for executing an arbitrary SQL query given by query returning a list of OrderedDicts.
As a python code expert, you are capable of creating scripts from specifications.
Perform a sql select statement with the given query and return any results as a list of OrderedDicts.
Explain what the following Python 3 code does def select(query, data=None): connection = _State.connection() _State.new_transaction() if data is None: data = [] result = connection.execute('select ' + query, data) rows = [] for row in result: rows.append(dict(list(row.items()))...
As a Python code analyst, you investigate and solve complex coding mysteries
def save(unique_keys, data, table_name='swdata'): """ Save the given data to the table specified by `table_name` (which defaults to 'swdata'). The data must be a mapping or an iterable of mappings. Unique keys is a list of keys that exist for all rows and for which a unique index will be created. ...
Write a Python 3 script for saving the given data to the specified table.
You are a Python code generator, capable of creating scripts from specifications.
def _set_table(table_name): """ Specify the table to work on. """ _State.connection() _State.reflect_metadata() _State.table = sqlalchemy.Table(table_name, _State.metadata, extend_existing=True) if list(_State.table.columns.keys()) == []: _State.t...
How would you code a function in Python 3 to set the table to work on.
As a Python code composer, you craft elegant and concise scripts.
Return the names of the tables currently in the database.
Can you tell what is the following Python 3 function doing def show_tables(): _State.connection() _State.reflect_metadata() metadata = _State.metadata response = select('name, sql from sqlite_master where type="table"') return {row['name']: row['sql'] for row in response}
You are a Python code generator, capable of creating scripts from specifications.
def save_var(name, value): """ Save a variable to the table specified by _State.vars_table_name. Key is the name of the variable, and value is the value. """ connection = _State.connection() _State.reflect_metadata() vars_table = sqlalchemy.Table( _State.vars_table_name, _State.meta...
Can you create a Python 3 function that saves a variable to the table specified by _State. vars_table_name.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_var(name, default=None): """ Returns the variable with the provided key from the table specified by _State.vars_table_name. """ alchemytypes = {"text": lambda x: x.decode('utf-8'), "big_integer": lambda x: int(x), "date": lambda x: x.decode('utf-8'), ...
Write a Python 3 function that can return the value of a variable in the _State. vars_table_name.
You are a Python code architect, reviewing and designing scalable and efficient code
def create_index(column_names, unique=False): """ Create a new index of the columns in column_names, where column_names is a list of strings. If unique is True, it will be a unique index. """ connection = _State.connection() _State.reflect_metadata() table_name = _State.table.name t...
Write a Python 3 function that can create a new index of the columns in column_names where column_names is a list of strings.
You are a Python code analyst, evaluating scripts for potential improvements.
Takes a row and checks to make sure it fits in the columns of the current table. Adds the required columns.
Make a summary of the following Python 3 code def fit_row(connection, row, unique_keys): new_columns = [] for column_name, column_value in list(row.items()): new_column = sqlalchemy.Column(column_name, get_column_type(column_value)) if not column_name in l...
You are a Python code architect, reviewing and designing scalable and efficient code
Create the table in the database.
How would you explain what the following Python 3 function does def create_table(unique_keys): _State.new_transaction() _State.table.create(bind=_State.engine, checkfirst=True) if unique_keys != []: create_index(unique_keys, unique=True) _State.table_pending = False _State.reflect_metadata()
As a Python code analyst, you investigate and solve complex coding mysteries
def add_column(connection, column): """ Add a column to the current table. """ stmt = alembic.ddl.base.AddColumn(_State.table.name, column) connection.execute(stmt) _State.reflect_metadata()
Write a Python 3 function for adding a column to the current table.
You are a Python code architect, reviewing and designing scalable and efficient code
Drop the current table if it exists.
Can you tell what is the following Python 3 function doing def drop(): # Ensure the connection is up _State.connection() _State.table.drop(checkfirst=True) _State.metadata.remove(_State.table) _State.table = None _State.new_transaction()
As a Python code translator, you convert algorithms and pseudocode into Python.
def attach_attrs_table(key, value, fmt, meta): """Extracts attributes and attaches them to element.""" # We can't use attach_attrs_factory() because Table is a block-level element if key in ['Table']: assert len(value) == 5 caption = value[0] # caption, align, x, head, body # Set ...
How would you implement a function in Python 3 that extracts attributes and attaches them to element.
You are a Python code architect, reviewing and designing scalable and efficient code
def process_tables(key, value, fmt, meta): """Processes the attributed tables.""" global has_unnumbered_tables # pylint: disable=global-statement # Process block-level Table elements if key == 'Table': # Inspect the table if len(value) == 5: # Unattributed, bail out has_...
Write a Python 3 script to process the attributed tables.
As a Python code translator, you convert algorithms and pseudocode into Python.