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 _refresh(self): """ refresh internal directory cache """
log.debug('refreshing directory cache') self._users.update(list(self._user_gen())) self._channels.update(list(self._channel_gen()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(self, attr, val): """ lookup object in directory with attribute matching value """
self._lock.acquire() try: for x in self: if getattr(x, attr) == val: return x finally: self._lock.release()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def biggus_chunk(chunk_key, biggus_array, masked): """ A function that lazily evaluates a biggus.Chunk. This is useful for passing through as a dask task so that...
if masked: array = biggus_array.masked_array() else: array = biggus_array.ndarray() return biggus._init.Chunk(chunk_key, array)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lazy_chunk_creator(name): """ Create a lazy chunk creating function with a nice name that is suitable for representation in a dask graph. """
# TODO: Could this become a LazyChunk class? def biggus_chunk(chunk_key, biggus_array, masked): """ A function that lazily evaluates a biggus.Chunk. This is useful for passing through as a dask task so that we don't have to compute the chunk in order to c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_nodes(self, dsk_graph, array, iteration_order, masked, top=False): """ Recursive function that returns the dask items for the given array. NOTE: Curren...
cache_key = _array_id(array, iteration_order, masked) # By the end of this function Nodes will be a dictionary with one item # per chunk to be processed for this array. nodes = self._node_cache.get(cache_key, None) if nodes is None: if hasattr(array, 'streams_handle...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_element_has_focus(self, locator, timeout=None): """Waits until the element identified by `locator` has focus. You might rather want to use `El...
self._info("Waiting for focus on '%s'" % (locator)) self._wait_until_no_error(timeout, self._check_element_focus_exp, True, locator, timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_element_does_not_have_focus(self, locator, timeout=None): """Waits until the element identified by `locator` doesn't have focus. You might rat...
self._info("Waiting until '%s' does not have focus" % (locator)) self._wait_until_no_error(timeout, self._check_element_focus_exp, False, locator, timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_element_value_is(self, locator, expected, strip=False, timeout=None): """Waits until the element identified by `locator` value is exactly the ...
self._info("Waiting for '%s' value to be '%s'" % (locator, expected)) self._wait_until_no_error(timeout, self._check_element_value_exp, False, locator, expected, strip, timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_element_value_contains(self, locator, expected, timeout=None): """Waits until the element identified by `locator` contains the expected value....
self._info("Waiting for '%s' value to contain '%s'" % (locator, expected)) self._wait_until_no_error(timeout, self._check_element_value_exp, True, locator, expected, False, timeout)
<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_element_focus(self, locator): """Sets focus on the element identified by `locator`. Should be used with elements meant to have focus only, such as ...
self._info("Setting focus on element '%s'" % (locator)) element = self._element_find(locator, True, True) element.send_keys(Keys.NULL) self._wait_until_no_error(None, self._check_element_focus, True, locator)
<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_field(self, locator, method=0): """Clears the text field identified by `locator` The element.clear() method doesn't seem to work properly on ...
element = self._element_find(locator, True, True) if (int(method) == 0): self._info("Clearing input on element '%s'" % (locator)) element.clear() elif (int(method) == 1): self._info("Clearing input on element '%s' by pressing 'CTRL + A + DELETE'" % (locator)) element.send_keys(Keys.CONTROL + '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_width_should_be(self, locator, expected): """Verifies the element identified by `locator` has the expected width. Expected width should be in pix...
self._info("Verifying element '%s' width is '%s'" % (locator, expected)) self._check_element_size(locator, 'width', expected)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_height_should_be(self, locator, expected): """Verifies the element identified by `locator` has the expected height. Expected height should be in ...
self._info("Verifying element '%s' height is '%s'" % (locator, expected)) self._check_element_size(locator, 'height', expected)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_value_should_be(self, locator, expected, strip=False): """Verifies the element identified by `locator` has the expected value. | *Argument* | *De...
self._info("Verifying element '%s' value is '%s'" % (locator, expected)) element = self._element_find(locator, True, True) value = element.get_attribute('value') if (strip): value = value.strip() if str(value) == expected: return else: raise AssertionError("Element '%s' value was not '%...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_value_should_not_be(self, locator, value, strip=False): """Verifies the element identified by `locator` is not the specified value. | *Argument* ...
self._info("Verifying element '%s' value is not '%s'" % (locator, value)) element = self._element_find(locator, True, True) elem_value = str(element.get_attribute('value')) if (strip): elem_value = elem_value.strip() if elem_value == value: raise AssertionError("Value was '%s' for element '%s' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_value_should_contain(self, locator, expected): """Verifies the element identified by `locator` contains the expected value. | *Argument* | *Descr...
self._info("Verifying element '%s' value contains '%s'" % (locator, expected)) element = self._element_find(locator, True, True) value = str(element.get_attribute('value')) if expected in value: return else: raise AssertionError("Value '%s' did not appear in element '%s'. It's value was '%s'"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_value_should_not_contain(self, locator, value): """Verifies the element identified by `locator` does not contain the specified value. | *Argument...
self._info("Verifying element '%s' value does not contain '%s'" % (locator, value)) element = self._element_find(locator, True, True) elem_value = str(element.get_attribute('value')) if value in elem_value: raise AssertionError("Value '%s' was found in element '%s' while it shouldn't have" % (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 element_focus_should_be_set(self, locator): """Verifies the element identified by `locator` has focus. | *Argument* | *Description* | *Example* | | loc...
self._info("Verifying element '%s' focus is set" % locator) self._check_element_focus(True, locator)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_focus_should_not_be_set(self, locator): """Verifies the element identified by `locator` does not have focus. | *Argument* | *Description* | *Exam...
self._info("Verifying element '%s' focus is not set" % locator) self._check_element_focus(False, locator)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_css_attribute_should_be(self, locator, prop, expected): """Verifies the element identified by `locator` has the expected value for the targeted `...
self._info("Verifying element '%s' has css attribute '%s' with a value of '%s'" % (locator, prop, expected)) self._check_element_css_value(locator, prop, expected)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_page_does_not_contain_these_elements(self, timeout, *locators): """Waits until all of the specified elements are not found on the page. | *Arg...
self._wait_until_no_error(timeout, self._wait_for_elements_to_go_away, locators)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_element_is_clickable(self, locator, timeout=None): """Clicks the element specified by `locator` until the operation succeeds. This should be u...
self._wait_until_no_error(timeout, self._wait_for_click_to_succeed, locator)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _visitor_impl(self, arg): """Actual visitor method implementation."""
if (_qualname(type(self)), type(arg)) in _methods: method = _methods[(_qualname(type(self)), type(arg))] return method(self, arg) else: # if no visitor method found for this arg type, # search in parent arg type: arg_parent_type = arg.__class__.__bases__[0] while...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visitor(arg_type): """Decorator that creates a visitor method."""
def decorator(fn): declaring_class = _declaring_class(fn) _methods[(declaring_class, arg_type)] = fn # Replace all decorated methods with _visitor_impl return _visitor_impl 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 absolute(parser, token): ''' Returns a full absolute URL based on the request host. This template tag takes exactly the same paramters as url template tag. ''' node = url(parser, token) return AbsoluteUrlNode( view_name=node.view_name, args=node.args, kwargs=node.kwa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def site(parser, token): ''' Returns a full absolute URL based on the current site. This template tag takes exactly the same paramters as url template tag. ''' node = url(parser, token) return SiteUrlNode( view_name=node.view_name, args=node.args, kwargs=node.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 get_callable_method_dict(obj): """Returns a dictionary of callable methods of object `obj`. @param obj: ZOS API Python COM object @return: a dictionary of ca...
methodDict = {} for methodStr in dir(obj): method = getattr(obj, methodStr, 'none') if callable(method) and not methodStr.startswith('_'): methodDict[methodStr] = method return methodDict
<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_properties(zos_obj): """Returns a lists of properties bound to the object `zos_obj` @param zos_obj: ZOS API Python COM object @return prop_get: list of p...
prop_get = set(zos_obj._prop_map_get_.keys()) prop_set = set(zos_obj._prop_map_put_.keys()) if prop_set.issubset(prop_get): prop_get = prop_get.difference(prop_set) else: msg = 'Assumption all getters are also setters is incorrect!' raise NotImplementedError(msg) return list...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrapped_zos_object(zos_obj): """Helper function to wrap ZOS API COM objects. @param zos_obj : ZOS API Python COM object @return: instance of the wrapped ZOS ...
if hasattr(zos_obj, '_wrapped') or ('CLSID' not in dir(zos_obj)): return zos_obj else: Class = managed_wrapper_class_factory(zos_obj) return Class(zos_obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Clean any processing data, and prepare object for reuse """
self.current_table = None self.tables = [] self.data = [{}] self.additional_data = {} self.lines = [] self.set_state('document') self.current_file = None self.set_of_energies = set()
<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_table(self, data): """Set current parsing state to 'table', create new table object and add it to tables collection """
self.set_state('table') self.current_table = HEPTable(index=len(self.tables) + 1) self.tables.append(self.current_table) self.data.append(self.current_table.metadata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reformat_matrix(self): """Transform a square matrix into a format with two independent variables and one dependent variable. """
nxax = len(self.current_table.data['independent_variables']) nyax = len(self.current_table.data['dependent_variables']) npts = len(self.current_table.data['dependent_variables'][0]['values']) # check if 1 x-axis, and npts (>=2) equals number of y-axes if nxax != 1 or nyax != np...
<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_qual(self, data): """Parse qual attribute of the old HEPData format example qual: *qual: RE : P P --> Z0 Z0 X :param data: data to be parsed :type dat...
list = [] headers = data.split(':') name = headers[0].strip() name = re.split(' IN ', name, flags=re.I) # ignore case units = None if len(name) > 1: units = name[1].strip() name = name[0].strip() if len(headers) < 2: raise BadFor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _strip_comments(line): """Processes line stripping any comments from it :param line: line to be processed :type line: str :return: line with removed comments...
if line == '': return line r = re.search('(?P<line>[^#]*)(#(?P<comment>.*))?', line) if r: line = r.group('line') if not line.endswith('\n'): line += '\n' return line return '\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 _bind_set_table_metadata(self, key, multiline=False): """Returns parsing function which will parse data as text, and add it to the table metatadata dictionar...
def set_table_metadata(self, data): if multiline: data = self._read_multiline(data) if key == 'location' and data: data = 'Data from ' + data self.current_table.metadata[key] = data.strip() # method must be bound, so we use __get__ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bind_parse_additional_data(self, key, multiline=False): """Returns parsing function which will parse data as text, and add it to the table additional data d...
def _set_additional_data_bound(self, data): """Concrete method for setting additional data :param self: :type self: OldHEPData """ # if it's multiline, parse it if multiline: data = self._read_multiline(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 error_value_processor(value, error): """ If an error is a percentage, we convert to a float, then calculate the percentage of the supplied value. :param valu...
if isinstance(error, (str, unicode)): try: if "%" in error: error_float = float(error.replace("%", "")) error_abs = (value/100) * error_float return error_abs elif error == "": error = 0.0 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 send_msg(self, text, channel, confirm=True): """ Send a message to a channel or group via Slack RTM socket, returning the resulting message object params: - ...
self._send_id += 1 msg = SlackMsg(self._send_id, channel.id, text) self.ws.send(msg.json) self._stats['messages_sent'] += 1 if confirm: # Wait for confirmation our message was received for e in self.events(): if e.get('reply_to') == 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 _process_event(self, event): """ Extend event object with User and Channel objects """
if event.get('user'): event.user = self.lookup_user(event.get('user')) if event.get('channel'): event.channel = self.lookup_channel(event.get('channel')) if self.user.id in event.mentions: event.mentions_me = True event.mentions = [ self.lookup_use...
<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_token_stream(source: str) -> CommonTokenStream: """ Get the antlr token stream. """
lexer = LuaLexer(InputStream(source)) stream = CommonTokenStream(lexer) return stream
<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_evolution_stone(self, slug): """ Returns a Evolution Stone object containing the details about the evolution stone. """
endpoint = '/evolution-stone/' + slug return self.make_request(self.BASE_URL + endpoint)
<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_league(self, slug): """ Returns a Pokemon League object containing the details about the league. """
endpoint = '/league/' + slug return self.make_request(self.BASE_URL + endpoint)
<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_pokemon_by_name(self, name): """ Returns an array of Pokemon objects containing all the forms of the Pokemon specified the name of the Pokemon. """
endpoint = '/pokemon/' + str(name) return self.make_request(self.BASE_URL + endpoint)
<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_pokemon_by_number(self, number): """ Returns an array of Pokemon objects containing all the forms of the Pokemon specified the Pokedex number. """
endpoint = '/pokemon/' + str(number) return self.make_request(self.BASE_URL + endpoint)
<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_keyid(keytype, scheme, key_value, hash_algorithm = 'sha256'): """Return the keyid of 'key_value'."""
# 'keyid' will be generated from an object conformant to KEY_SCHEMA, # which is the format Metadata files (e.g., root.json) store keys. # 'format_keyval_to_metadata()' returns the object needed by _get_keyid(). key_meta = format_keyval_to_metadata(keytype, scheme, key_value, private=False) # Convert the ke...
<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_concrete_class(cls, class_name): """This method provides easier access to all writers inheriting Writer class :param class_name: name of the parser (name...
def recurrent_class_lookup(cls): for cls in cls.__subclasses__(): if lower(cls.__name__) == lower(class_name): return cls elif len(cls.__subclasses__()) > 0: r = recurrent_class_lookup(cls) if r is not 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 GetPupil(self): """Retrieve pupil data """
pupil_data = _co.namedtuple('pupil_data', ['ZemaxApertureType', 'ApertureValue', 'entrancePupilDiameter', 'entrancePupilPosition', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _groups_of(length, total_length): """ Return an iterator of tuples for slicing, in 'length' chunks. Parameters length : int Length of each chunk. total_lengt...
indices = tuple(range(0, total_length, length)) + (None, ) return _pairwise(indices)
<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(sources, targets, masked=False): """ Save the numeric results of each source into its corresponding target. Parameters sources: list The list of source ...
# TODO: Remove restriction assert len(sources) == 1 and len(targets) == 1 array = sources[0] target = targets[0] # Request bitesize pieces of the source and assign them to the # target. # NB. This algorithm does not use the minimal number of chunks. # e.g. If the second dimension cou...
<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(a, axis=None): """ Count the non-masked elements of the array along the given axis. .. note:: Currently limited to operating on a single axis. :param a...
axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) return _Aggregation(a, axes[0], _CountStreamsHandler, _CountMaskedStreamsHandler, np.dt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min(a, axis=None): """ Request the minimum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters a : Arr...
axes = _normalise_axis(axis, a) assert axes is not None and len(axes) == 1 return _Aggregation(a, axes[0], _MinStreamsHandler, _MinMaskedStreamsHandler, a.dtype, {})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max(a, axis=None): """ Request the maximum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters a : Arr...
axes = _normalise_axis(axis, a) assert axes is not None and len(axes) == 1 return _Aggregation(a, axes[0], _MaxStreamsHandler, _MaxMaskedStreamsHandler, a.dtype, {})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sum(a, axis=None): """ Request the sum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters a : Array o...
axes = _normalise_axis(axis, a) assert axes is not None and len(axes) == 1 return _Aggregation(a, axes[0], _SumStreamsHandler, _SumMaskedStreamsHandler, a.dtype, {})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mean(a, axis=None, mdtol=1): """ Request the mean of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis...
axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) dtype = (np.array([0], dtype=a.dtype) / 1.).dtype kwargs = dict(mdtol=mdtol) return _Aggregation(a, axes[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 std(a, axis=None, ddof=0): """ Request the standard deviation of an Array over any number of axes. .. note:: Currently limited to operating on a single axis....
axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) dtype = (np.array([0], dtype=a.dtype) / 1.).dtype return _Aggregation(a, axes[0], _StdStreamsHandler, _StdM...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def var(a, axis=None, ddof=0): """ Request the variance of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param ax...
axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) dtype = (np.array([0], dtype=a.dtype) / 1.).dtype return _Aggregation(a, axes[0], _VarStreamsHandler, _VarM...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ufunc_wrapper(ufunc, name=None): """ A function to generate the top level biggus ufunc wrappers. """
if not isinstance(ufunc, np.ufunc): raise TypeError('{} is not a ufunc'.format(ufunc)) ufunc_name = ufunc.__name__ # Get hold of the masked array equivalent, if it exists. ma_ufunc = getattr(np.ma, ufunc_name, None) if ufunc.nin == 2 and ufunc.nout == 1: func = _dual_input_fn_wrapp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sliced_shape(shape, keys): """ Returns the shape that results from slicing an array of the given shape by the given keys. (1, 10, 90, 1) """
keys = _full_keys(keys, len(shape)) sliced_shape = [] shape_dim = -1 for key in keys: shape_dim += 1 if _is_scalar(key): continue elif isinstance(key, slice): size = len(range(*key.indices(shape[shape_dim]))) sliced_shape.append(size) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(array): """ Return a human-readable description of the number of bytes required to store the data of the given array. For example:: 14000000 >> biggus.s...
nbytes = array.nbytes if nbytes < (1 << 10): size = '{} B'.format(nbytes) elif nbytes < (1 << 20): size = '{:.02f} KiB'.format(nbytes / (1 << 10)) elif nbytes < (1 << 30): size = '{:.02f} MiB'.format(nbytes / (1 << 20)) elif nbytes < (1 << 40): size = '{:.02f} GiB'.f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output(self, chunk): """ Dispatch the given Chunk onto all the registered output queues. If the chunk is None, it is silently ignored. """
if chunk is not None: for queue in self.output_queues: queue.put(chunk)
<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(self): """ Emit the Chunk instances which cover the underlying Array. The Array is divided into chunks with a size limit of MAX_CHUNK_SIZE which are emit...
try: chunk_index = self.chunk_index_gen(self.array.shape, self.iteration_order) for key in chunk_index: # Now we have the slices that describe the next chunk. # For example, key might be equivalent to ...
<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_input_nodes(self, input_nodes): """ Set the given nodes as inputs for this node. Creates a limited-size queue.Queue for each input node and registers eac...
self.input_queues = [queue.Queue(maxsize=3) for _ in input_nodes] for input_node, input_queue in zip(input_nodes, self.input_queues): input_node.add_output_queue(input_queue)
<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(self): """ Process the input queues in lock-step, and push any results to the registered output queues. """
try: while True: input_chunks = [input.get() for input in self.input_queues] for input in self.input_queues: input.task_done() if any(chunk is QUEUE_ABORT for chunk in input_chunks): self.abort() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_chunks(self, chunks): """ Store the incoming chunk at the corresponding position in the result array. """
chunk, = chunks if chunk.keys: self.result[chunk.keys] = chunk.data else: self.result[...] = chunk.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 _cleanup_new_key(self, key, size, axis): """ Return a key of type int, slice, or tuple that is guaranteed to be valid for the given dimension size. Raises In...
if _is_scalar(key): if key >= size or key < -size: msg = 'index {0} is out of bounds for axis {1} with' \ ' size {2}'.format(key, axis, size) raise IndexError(msg) elif isinstance(key, slice): pass elif isinstance(key...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _remap_new_key(self, indices, new_key, axis): """ Return a key of type int, slice, or tuple that represents the combination of new_key with the given indices...
size = len(indices) if _is_scalar(new_key): if new_key >= size or new_key < -size: msg = 'index {0} is out of bounds for axis {1}' \ ' with size {2}'.format(new_key, axis, size) raise IndexError(msg) result_key = indices[new_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_axes_mapping(self, target, inverse=False): """ Apply the transposition to the target iterable. Parameters target - iterable The iterable to transpose....
if len(target) != self.ndim: raise ValueError('The target iterable is of length {}, but ' 'should be of length {}.'.format(len(target), self.ndim)) if inverse: axis_map = self._inverse_axe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output_keys(self, source_keys): """ Given input chunk keys, compute what keys will be needed to put the result into the result array. As an example of where ...
keys = list(source_keys) # Remove the aggregated axis from the keys. del keys[self.axis] return tuple(keys)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zDDEInit(self): """Initiates link with OpticStudio DDE server"""
self.pyver = _get_python_version() # do this only one time or when there is no channel if _PyZDDE.liveCh==0: try: _PyZDDE.server = _dde.CreateServer() _PyZDDE.server.Create("ZCLIENT") except Exception as err: _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 zDDEClose(self): """Close the DDE link with Zemax server"""
if _PyZDDE.server and not _PyZDDE.liveCh: _PyZDDE.server.Shutdown(self.conversation) _PyZDDE.server = 0 elif _PyZDDE.server and self.connection and _PyZDDE.liveCh == 1: _PyZDDE.server.Shutdown(self.conversation) self.connection = False self.ap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setTimeout(self, time): """Set global timeout value, in seconds, for all DDE calls"""
self.conversation.SetDDETimeout(round(time)) return self.conversation.GetDDETimeout()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sendDDEcommand(self, cmd, timeout=None): """Send command to DDE client"""
reply = self.conversation.Request(cmd, timeout) if self.pyver > 2: reply = reply.decode('ascii').rstrip() return reply
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zGetUpdate(self): """Update the lens"""
status,ret = -998, None ret = self._sendDDEcommand("GetUpdate") if ret != None: status = int(ret) #Note: Zemax returns -1 if GetUpdate fails. return status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zLoadFile(self, fileName, append=None): """Loads a zmx file into the DDE server"""
reply = None if append: cmd = "LoadFile,{},{}".format(fileName, append) else: cmd = "LoadFile,{}".format(fileName) reply = self._sendDDEcommand(cmd) if reply: return int(reply) #Note: Zemax returns -999 if update fails. 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 zPushLens(self, update=None, timeout=None): """Copy lens in the Zemax DDE server into LDE"""
reply = None if update == 1: reply = self._sendDDEcommand('PushLens,1', timeout) elif update == 0 or update is None: reply = self._sendDDEcommand('PushLens,0', timeout) else: raise ValueError('Invalid value for flag') if reply: 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 zSaveFile(self, fileName): """Saves the lens currently loaded in the server to a Zemax file """
cmd = "SaveFile,{}".format(fileName) reply = self._sendDDEcommand(cmd) return int(float(reply.rstrip()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zSyncWithUI(self): """Turn on sync-with-ui"""
if not OpticalSystem._dde_link: OpticalSystem._dde_link = _get_new_dde_link() if not self._sync_ui_file: self._sync_ui_file = _get_sync_ui_filename() self._sync_ui = 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 zPushLens(self, update=None): """Push lens in ZOS COM server to UI"""
self.SaveAs(self._sync_ui_file) OpticalSystem._dde_link.zLoadFile(self._sync_ui_file) OpticalSystem._dde_link.zPushLens(update)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zGetRefresh(self): """Copy lens in UI to headless ZOS COM server"""
OpticalSystem._dde_link.zGetRefresh() OpticalSystem._dde_link.zSaveFile(self._sync_ui_file) self._iopticalsystem.LoadFile (self._sync_ui_file, False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SaveAs(self, filename): """Saves the current system to the specified file. @param filename: absolute path (string) @return: None @raise: ValueError if path (...
directory, zfile = _os.path.split(filename) if zfile.startswith('pyzos_ui_sync_file'): self._iopticalsystem.SaveAs(filename) else: # regular file if not _os.path.exists(directory): raise ValueError('{} is not valid.'.format(directory)) 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 Save(self): """Saves the current system"""
# This method is intercepted to allow ui_sync if self._file_to_save_on_Save: self._iopticalsystem.SaveAs(self._file_to_save_on_Save) else: self._iopticalsystem.Save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zGetSurfaceData(self, surfNum): """Return surface data"""
if self.pMode == 0: # Sequential mode surf_data = _co.namedtuple('surface_data', ['radius', 'thick', 'material', 'semidia', 'conic', 'comment']) surf = self.pLDE.GetSurfaceAt(surfNum) return surf_data(surf.pRadius, sur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zSetSurfaceData(self, surfNum, radius=None, thick=None, material=None, semidia=None, conic=None, comment=None): """Sets surface data"""
if self.pMode == 0: # Sequential mode surf = self.pLDE.GetSurfaceAt(surfNum) if radius is not None: surf.pRadius = radius if thick is not None: surf.pThickness = thick if material is not None: surf.pMaterial = mater...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zSetDefaultMeritFunctionSEQ(self, ofType=0, ofData=0, ofRef=0, pupilInteg=0, rings=0, arms=0, obscuration=0, grid=0, delVignetted=False, useGlass=False, glass...
mfe = self.pMFE wizard = mfe.pSEQOptimizationWizard wizard.pType = ofType wizard.pData = ofData wizard.pReference = ofRef wizard.pPupilIntegrationMethod = pupilInteg wizard.pRing = rings wizard.pArm = arms wizard.pObscuration = obscuration ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_error_labels(value): """ Process the error labels of a dependent variable 'value' to ensure uniqueness. """
observed_error_labels = {} for error in value.get('errors', []): label = error.get('label', 'error') if label not in observed_error_labels: observed_error_labels[label] = 0 observed_error_labels[label] += 1 if observed_error_labels[labe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw(text): """Returns a raw string representation of text"""
new_string = '' for char in text: try: new_string += escape_dict[char] except KeyError: new_string += char return new_string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def WinMSGLoop(): """Run the main windows message loop."""
LPMSG = POINTER(MSG) LRESULT = c_ulong GetMessage = get_winfunc("user32", "GetMessageW", BOOL, (LPMSG, HWND, UINT, UINT)) TranslateMessage = get_winfunc("user32", "TranslateMessage", BOOL, (LPMSG,)) # restype = LRESULT DispatchMessage = get_winfunc("user32", "DispatchMessageW", LRESULT, (LPMSG,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Request(self, item, timeout=None): """Request DDE client timeout in seconds """
if not timeout: timeout = self.ddetimeout try: reply = self.ddec.request(item, int(timeout*1000)) # convert timeout into milliseconds except DDEError: err_str = str(sys.exc_info()[1]) error = err_str[err_str.find('err=')+4:err_str.find('err=')+10]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def advise(self, item, stop=False): """Request updates when DDE data changes."""
hszItem = DDE.CreateStringHandle(self._idInst, item, CP_WINUNICODE) hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_ADVSTOP if stop else XTYP_ADVSTART, TIMEOUT_ASYNC, LPDWORD()) DDE.FreeStringHandle(self._idInst, hszItem) if not hDdeData: ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, command): """Execute a DDE command."""
pData = c_char_p(command) cbData = DWORD(len(command) + 1) hDdeData = DDE.ClientTransaction(pData, cbData, self._hConv, HSZ(), CF_TEXT, XTYP_EXECUTE, TIMEOUT_ASYNC, LPDWORD()) if not hDdeData: raise DDEError("Unable to send command", self._idInst) DDE.FreeDataHandle(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, item, timeout=5000): """Request data from DDE service."""
hszItem = DDE.CreateStringHandle(self._idInst, item, CP_WINUNICODE) #hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_REQUEST, timeout, LPDWORD()) pdwResult = DWORD(0) hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_REQU...
<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_molo_comments(parser, token): """ Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. ...
keywords = token.contents.split() if len(keywords) != 5 and len(keywords) != 7 and len(keywords) != 9: raise template.TemplateSyntaxError( "'%s' tag takes exactly 2,4 or 6 arguments" % (keywords[0],)) if keywords[1] != 'for': raise template.TemplateSyntaxError( "firs...
<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_comments_content_object(parser, token): """ Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables ...
keywords = token.contents.split() if len(keywords) != 5: raise template.TemplateSyntaxError( "'%s' tag takes exactly 2 arguments" % (keywords[0],)) if keywords[1] != 'for': raise template.TemplateSyntaxError( "first argument to '%s' tag must be 'for'" % (keywords[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 report(request, comment_id): """ Flags a comment on GET. Redirects to whatever is provided in request.REQUEST['next']. """
comment = get_object_or_404( django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) if comment.parent is not None: messages.info(request, _('Reporting comment replies is not allowed.')) else: perform_flag(request, comment) messages.info(request, _('The comme...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_molo_comment(request, next=None, using=None): """ Allows for posting of a Molo Comment, this allows comments to be set with the "user_name" as "Anonymou...
data = request.POST.copy() if 'submit_anonymously' in data: data['name'] = 'Anonymous' # replace with our changed POST data # ensure we always set an email data['email'] = request.user.email or 'blank@email.com' request.POST = data return post_comment(request, next=next, using=nex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drape(raster, feature): """Convert a 2D feature to a 3D feature by sampling a raster Parameters: raster (rasterio): raster to provide the z coordinate featu...
coords = feature['geometry']['coordinates'] geom_type = feature['geometry']['type'] if geom_type == 'Point': xyz = sample(raster, [coords]) result = Point(xyz[0]) elif geom_type == 'LineString': xyz = sample(raster, coords) points = [Point(x, y, z) for x, y, z in xyz] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(raster, coords): """Sample a raster at given coordinates Given a list of coordinates, return a list of x,y,z triples with z coordinates sampled from a...
if len(coords[0]) == 3: logging.info('Input is a 3D geometry, z coordinate will be updated.') z = raster.sample([(x, y) for x, y, z in coords], indexes=raster.indexes) else: z = raster.sample(coords, indexes=raster.indexes) result = [(vert[0], vert[1], vert_z) for vert, vert_z in z...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(source_f, raster_f, output, verbose): """ Converts 2D geometries to 3D using GEOS sample through fiona. \b Example: drape point.shp elevation.tif -o poin...
with fiona.open(source_f, 'r') as source: source_driver = source.driver source_crs = source.crs sink_schema = source.schema.copy() source_geom = source.schema['geometry'] if source_geom == 'Point': sink_schema['geometry'] = '3D Point' elif source_geom ==...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def eval(self, command): 'Blocking call, returns the value of the execution in JS' event = threading.Event() # TODO: Add event to server #job_id = str(id(command)) import random job_id = str(random.random()) server.EVALUATIONS[job_id] = event message = '?...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def launch_exception(message): """ Launch a Python exception from an error that took place in the browser. messsage format: - name: str - description: str """
error_name = message['name'] error_descr = message['description'] mapping = { 'ReferenceError': NameError, } if message['name'] in mapping: raise mapping[error_name](error_descr) else: raise Exception('{}: {}'.format(error_name, error_descr))