output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
A function that can be used to make an observable method.
Explain what the following Python 3 code does def observable_method(func, strategy='instances'): if strategy == 'instances': return ObservableMethodManager_PersistOnInstances(func) elif strategy == 'descriptor': return ObservableMethodManager_PersistOnDescriptor(func) else: raise Val...
As a Python code translator, you convert algorithms and pseudocode into Python.
Register an observer to observe me.
Here you have a function in Python 3, explain what it does def add_observer(self, observer, identify_observed=False): # If the observer is a bound method, if hasattr(observer, "__self__"): result = self._add_bound_method(observer, identify_observed) # Otherwise, assume observer is a...
As a Python code analyst, you investigate and solve complex coding mysteries
def _add_function(self, func, identify_observed): """Add a function as an observer. Args: func: The function to register as an observer. identify_observed: See docstring for add_observer. Returns: True if the function is added, otherwise False. """ ...
Implement a function in Python 3 to add a function to the internal dictionary of observers.
As a Python code analyst, you investigate and solve complex coding mysteries
Add an bound method to the internal dictionary.
Explain what the following Python 3 code does def _add_bound_method(self, bound_method, identify_observed): inst = bound_method.__self__ method_name = bound_method.__name__ key = self.make_key(bound_method) if key not in self.observers: self.observers[key] = ObserverBoundMet...
You are a Python code analyst, evaluating scripts for potential improvements.
Construct a unique hashable immutable key for an observer.
Here you have a function in Python 3, explain what it does def make_key(observer): if hasattr(observer, "__self__"): inst = observer.__self__ method_name = observer.__name__ key = (id(inst), method_name) else: key = id(observer) return key
You are a Python code architect, reviewing and designing scalable and efficient code
def group(self): """Yield a group from the iterable""" yield self.current # start enumerate at 1 because we already yielded the last saved item for num, item in enumerate(self.iterator, 1): self.current = item if num == self.limit: break ...
Implement a function in Python 3 to yield a group from the iterable
You are a Python code architect, reviewing and designing scalable and efficient code
def lock_packages(self, deps_file_path=None, depslock_file_path=None, packages=None): """ Lock packages. Downloader search packages """ if deps_file_path is None: deps_file_path = self._deps_path if depslock_file_path is None: depslock_file_path = self._de...
Implement a function in Python 3 to lock packages. Downloader search packages
You are a Python code analyst, evaluating scripts for potential improvements.
def stdout(self): """ Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT. Если есть любое значение в CROSSPM_STDOUT - оно понимается как True :return: """ # --stdout stdout = self._args['--stdout'] if stdout: return True ...
How would you code a function in Python 3 to return True if stdout is set False otherwise.
You are a Python code generator, capable of creating scripts from specifications.
def prepare_args(args, windows=None): """ Prepare args - add support for old interface, e.g: - --recursive was "flag" and for now it support True or False value :param args: :return: """ if windows is None: windows = "win" in sys.platform ...
How would you code a function in Python 3 to prepare args for the command.
You are a Python code architect, reviewing and designing scalable and efficient code
async def log( self, date: datetime.date = None, days: int = None, details: bool = False) -> list: """Get watering information for X days from Y date.""" endpoint = 'watering/log' if details: endpoint += '/details' if date and ...
Can you create a Python 3 function that gets watering information for X days from Y date.
You are a Python code architect, reviewing and designing scalable and efficient code
async def runs(self, date: datetime.date = None, days: int = None) -> list: """Return all program runs for X days from Y date.""" endpoint = 'watering/past' if date and days: endpoint = '{0}/{1}/{2}'.format( endpoint, date.strftime('%Y-%m-%d'), days) data = ...
Write a Python 3 function that can return all program runs for X days from Y date.
You are a Python code architect, reviewing and designing scalable and efficient code
def search_auth(self, list_or_file_path, source): """ Looking for auth in env, cmdline, str :param list_or_file_path: :param source: """ _auth = source.args['auth'] if isinstance(_auth, str): if ':' in _auth: _auth = _auth.split(':') ...
How would you implement a function in Python 3 that searches for auth in env cmdline str
You are a Python code analyst, evaluating scripts for potential improvements.
async def _post(self, program_id: int = None, json: dict = None) -> dict: """Post data to a (non)existing program.""" return await self._request( 'post', 'program/{0}'.format(program_id), json=json)
Can you create a Python 3 function that posts data to a non - existing program.
As a Python code translator, you convert algorithms and pseudocode into Python.
A function decorator that caches the JSON - serializable output of the function to a given file
Can you generate a brief explanation for the following Python 3 code def cache_json(filename): def cache_decorator(cacheable_function): @wraps(cacheable_function) def cache_wrapper(*args, **kwargs): path = CACHE_DIRECTORY + filename check_create_folder(path) if os...
As a python code expert, you are capable of creating scripts from specifications.
Check if the folder exisits. If not create the folder
Can you generate the documentation for the following Python 3 function def check_create_folder(filename): os.makedirs(os.path.dirname(filename), exist_ok=True)
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a payment request from the given request
Given the following Python 3 function, write the documentation def get_payment_request(self, cart, request): shop_ns = resolve(request.path).namespace return_url = reverse('{}:{}:return'.format(shop_ns, self.namespace)) cancel_url = reverse('{}:{}:cancel'.format(shop_ns, self.namespace)) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def postings(self, quarter, stats_counter=None): """Yield job postings in common schema format Args: quarter (str) The quarter, in format '2015Q1' stats_counter (object, optional) A counter that can track both input and output documents using a 'track' method. ...
Can you write a function in Python 3 where it yields all job postings in common schema format
You are a Python code architect, reviewing and designing scalable and efficient code
def _generate_search_terms(self): """ Map search terms to what test case(s) they're related to Returns: dict: maps search terms to what test case(s) it's relevant to Example: { '12034': ['ui.tests.TestSomething.test_hello_world'], 'buggy': ['...
Can you write a function in Python 3 where it generates a dictionary of search terms to what test case(s) they re related to
As a Python code translator, you convert algorithms and pseudocode into Python.
def afterSummaryReport(self, event): """ After everything is done, generate the report """ logger.info('Generating HTML report...') sorted_test_results = self._sort_test_results() context = { 'test_report_title': 'Test Report', 'test_summary': se...
Can you write a function in Python 3 where it generates the HTML report for the current test set.
As a Python code analyst, you investigate and solve complex coding mysteries
Convert a quarter in arbitrary filename - ready format into start and end datetimes
Can you generate the documentation for the following Python 3 function def quarter_to_daterange(quarter): assert len(quarter) == 6 year = int(quarter[0:4]) quarter = quarter[5] MONTH_DAY = { '1': ((1, 1), (3, 31)), '2': ((4, 1), (6, 30)), '3': ((7, 1), (9, 30)), '4': ((10...
You are a Python code architect, reviewing and designing scalable and efficient code
def datetime_to_year_quarter(dt): """ Args: dt: a datetime Returns: tuple of the datetime's year and quarter """ year = dt.year quarter = int(math.ceil(float(dt.month)/3)) return (year, quarter)
Can you create a Python 3 function that returns a tuple of the datetime s year and quarter
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns all dates between two dates.
How would you explain what the following Python 3 function does def dates_in_range(start_date, end_date): return [ start_date + timedelta(n) for n in range(int((end_date - start_date).days)) ]
As a python code expert, you are capable of creating scripts from specifications.
def load_hooks(): """ Load the exposed hooks. Returns a dict of hooks where the keys are the name of the hook and the values are the actual hook functions. """ hooks = {} for entrypoint in pkg_resources.iter_entry_points(ENTRYPOINT): name = str(entrypoint).split('=')[0].strip() ...
How would you implement a function in Python 3 that loads the exposed hooks.
As a Python code composer, you craft elegant and concise scripts.
def gettext(ui_file_path): """ Let you use gettext instead of the Qt tools for l18n """ with open(ui_file_path, 'r') as fin: content = fin.read() # replace ``_translate("context", `` by ``_(`` content = re.sub(r'_translate\(".*",\s', '_(', content) content = content.replace( ...
Can you create a Python 3 function that lets you use gettext instead of the Qt tools for l18n
As a Python code translator, you convert algorithms and pseudocode into Python.
def stream_json_file(local_file): """Stream a JSON file (in JSON-per-line format) Args: local_file (file-like object) an open file-handle that contains a JSON string on each line Yields: (dict) JSON objects """ for i, line in enumerate(local_file): try: ...
Create a Python 3 function to stream a JSON file in JSON - per - line format
You are a Python code analyst, evaluating scripts for potential improvements.
Download the package and return the path of the downloaded file.
Can you generate a brief explanation for the following Python 3 code def download(self, force=False): exists, dest_path = self._downloader.cache.exists_packed(package=self, pkg_path=self.packed_path, check_stat=not self._in_cache) unp_exis...
You are a Python code architect, reviewing and designing scalable and efficient code
def find_dependencies(self, depslock_file_path, property_validate=True, deps_content=None): """ Find all dependencies by package :param depslock_file_path: :param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file, :param deps_...
Implement a function in Python 3 to find all dependencies by package
As a Python code translator, you convert algorithms and pseudocode into Python.
def find_usedby(self, depslock_file_path, property_validate=True): """ Find all dependencies by package :param depslock_file_path: :param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file, we can skip validate part :re...
Can you implement a function in Python 3 that finds all dependencies by package
As a Python code composer, you craft elegant and concise scripts.
def get_params(self, param_list=None, get_path=False, merged=False, raw=False): """ Get Package params :param param_list: name or list of parameters :param get_path: :param merged: if version splited, True return version in string :param raw: :return: """ ...
Write a Python 3 script to get the parameters of the current object.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_none_packages(self): """ Get packages with None (not founded), recursively """ not_found = set() for package_name, package in self.packages.items(): if package is None: not_found.add(package_name) else: if package.pa...
How would you code a function in Python 3 to get packages with None ( not founded ) recursively
As a Python code analyst, you investigate and solve complex coding mysteries
def get_params_with_extra(self, rule_name, params): """ Get params with extra, like 'any' :param rule_name: 'path' :param params: default params :return: list of combination params """ # HACK for prefer-local result = [] extra_params = self._rules_...
Can you write a function in Python 3 where it gets params with extra vars like any
You are a Python code generator, capable of creating scripts from specifications.
Split path into fixed and masked parts
Make a summary of the following Python 3 code def split_fixed_pattern(path): _first_pattern_pos = path.find('*') _path_separator_pos = path.rfind('/', 0, _first_pattern_pos) + 1 _path_fixed = path[:_path_separator_pos] _path_pattern = path[_path_separator_pos:] return _path_fixed...
As a Python code analyst, you investigate and solve complex coding mysteries
def split_fixed_pattern_with_file_name(path): """ Split path into fixed, masked parts and filename :param path: e.g https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/*.*.*/vc110/x86/win/boost.*.*.*.tar.gz :return: _path_fixed: https://repo.example.c...
Implement a Python 3 function for splitting path into fixed parts and filename
You are a Python code generator, capable of creating scripts from specifications.
def basic_client(): """Returns an Elasticsearch basic client that is responsive to the environment variable ELASTICSEARCH_ENDPOINT""" es_connected = False while not es_connected: try: ES = Elasticsearch( hosts=[HOSTNAME] ) es_connected = True ...
Create a Python 3 function to return an Elasticsearch basic client that is responsive racket to the environment variable ELASTICSEARCH_ENDPOINT
You are a Python code analyst, evaluating scripts for potential improvements.
Creates an index with a given configuration
Can you tell what is the following Python 3 function doing def create_index(index_name, index_config, client): client.create(index=index_name, body=index_config)
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_index_from_alias(alias_name, index_client=None): """Retrieve the base index name from an alias Args: alias_name (str) Name of the alias index_client (Elasticsearch.IndicesClient) an Elasticsearch index client. Optional, will create one if not given Returns: (str) Name o...
How would you code a function in Python 3 to retrieve the base index name from an alias
As a Python code translator, you convert algorithms and pseudocode into Python.
This function performs an atomic index alias swap.
Explain what the following Python 3 code does def atomic_swap(alias_name, new_index_name, index_client): logging.info('Performing atomic index alias swap') if index_client.exists_alias(name=alias_name): old_index_name = get_index_from_alias(alias_name, index_client) logging.info('Removing old as...
You are a Python code analyst, evaluating scripts for potential improvements.
Context manager that creates a new index based on a given alias and then assigns it to the alias.
Explain what the following Python 3 code does def zero_downtime_index(index_name, index_config): client = indices_client() temporary_name = index_name + '_' + str(uuid.uuid4()) logging.info('creating index with config %s', index_config) create_index(temporary_name, index_config, client) try: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Replace index with a new one.
Can you generate a brief explanation for the following Python 3 code def replace(self): with zero_downtime_index(self.alias_name, self.index_config()) as target_index: self.index_all(target_index)
You are a Python code analyst, evaluating scripts for potential improvements.
Index documents onto an existing index.
Can you tell what is the following Python 3 function doing def append(self): target_index = get_index_from_alias(self.alias_name) if not target_index: self.replace() else: self.index_all(target_index)
As a Python code composer, you craft elegant and concise scripts.
def index_all(self, index_name): """Index all available documents, using streaming_bulk for speed Args: index_name (string): The index """ oks = 0 notoks = 0 for ok, item in streaming_bulk( self.es_client, self._iter_documents(index_name) ...
How would you code a function in Python 3 to index all available documents using streaming_bulk for speed
You are a Python code generator, capable of creating scripts from specifications.
Build the arguments list for passing to subprocess. call_check Taxonomy
How would you explain what the following Python 3 function does def build_args(cmd, src, dst): cmd = cmd % (quote(src), quote(dst)) args = shlex.split(cmd) return [arg for arg in args if arg]
You are a Python code architect, reviewing and designing scalable and efficient code
def register_output_format(name): """ Load output format function to dictionary (decorator with this function name) """ def check_decorator(fn): _output_format_map[name] = fn def wrapper(*args, **kwargs): return fn(*args, **kwargs) return wrapper return check_...
Implement a Python 3 function for registering a function as an output format.
You are a Python code analyst, evaluating scripts for potential improvements.
Write the output of a set of packages to a file.
Can you tell what is the following Python 3 function doing def write_output(self, params, packages): if params['out_format'] not in _output_format_map: raise CrosspmException( CROSSPM_ERRORCODE_UNKNOWN_OUT_TYPE, 'Unknown out_format: [{}]'.format(params['out_format']),...
You are a Python code generator, capable of creating scripts from specifications.
Formats the module and returns the output as a dict.
How would you explain what the following Python 3 function does def output_format_module(self, packages, esc_path=False): def create_ordered_list(packages_): """ Recursive for package.packages """ list_ = [] for _pkg_name in packages_: ...
As a Python code composer, you craft elegant and concise scripts.
Simple decorator to get custom fields on admin class
Explain what the following Python 3 code does def smart(**kwargs): def decorator(func): for key, value in kwargs.items(): setattr(func, key, value) return func return decorator
You are a Python code architect, reviewing and designing scalable and efficient code
Create a numpy array of the required length filled with value If the value is a float create a numpy array of the required length filled with value Otherwise throw a type error
Here you have a function in Python 3, explain what it does def create_buffer(params, value): ''' If the value is a float, create a numpy array of the required length, filled with value If the value is a numpy array, check its length Otherwise throw a type error ''' try: fv = float(value)...
As a Python code composer, you craft elegant and concise scripts.
Update the length of the buffer in seconds
Here you have a function in Python 3, explain what it does def set_time(self, time): ''' Update the length of the buffer in seconds :param time: number of seconds :return: self ''' self.length = int(time*self.sample_rate) return self
As a python code expert, you are capable of creating scripts from specifications.
Make a request to another service.
Can you generate a brief explanation for the following Python 3 code def make_request(self, method, service, path, body=None, query_params: QueryParams=None, headers: dict=None, correlation_id: str=None, content_...
As a Python code analyst, you investigate and solve complex coding mysteries
def get(self, service, path, **kwargs): """ Make a get request (this returns a coroutine)""" return self.make_request(Methods.GET, service, path, **kwargs)
Implement a function in Python 3 to make a GET request.
You are a Python code analyst, evaluating scripts for potential improvements.
def put(self, service, path, body, **kwargs): """ Make a put request (this returns a coroutine)""" return self.make_request(Methods.POST, service, path, body=body, **kwargs)
How would you implement a function in Python 3 that makes a PUT request.
You are a Python code analyst, evaluating scripts for potential improvements.
Make a PATCH request
Can you generate the documentation for the following Python 3 function def patch(self, service, path, body, **kwargs): return self.make_request(Methods.PATCH, service, path, body=body, **kwargs)
As a Python code translator, you convert algorithms and pseudocode into Python.
def delete(self, service, path, **kwargs): """ Make a delete requests (this returns a coroutine)""" return self.make_request(Methods.DELETE, service, path, **kwargs)
Can you implement a function in Python 3 that makes a DELETE request
As a Python code analyst, you investigate and solve complex coding mysteries
Fetch Resource and return Entity
Explain what the following Python 3 code does def process_request(self, request_object): identifier = request_object.identifier # Look for the object by its ID and return it resource = request_object.entity_cls.get(identifier) return ResponseSuccess(Status.SUCCESS, resource)
As a Python code translator, you convert algorithms and pseudocode into Python.
Initialize a ListRequestObject object from a dictionary.
Given the following Python 3 function, write the documentation def from_dict(cls, entity_cls, adict): invalid_req = InvalidRequestObject() # Extract the pagination parameters from the input page = int(adict.pop('page', 1)) per_page = int(adict.pop( 'per_page', getattr(active...
As a Python code analyst, you investigate and solve complex coding mysteries
Return a list of resources
Can you tell what is the following Python 3 function doing def process_request(self, request_object): resources = (request_object.entity_cls.query .filter(**request_object.filters) .offset((request_object.page - 1) * request_object.per_page) .limit(...
You are a Python code analyst, evaluating scripts for potential improvements.
def process_request(self, request_object): """Process Create Resource Request""" resource = request_object.entity_cls.create(**request_object.data) return ResponseSuccessCreated(resource)
Implement a function in Python 3 to process Create Resource Request
You are a Python code architect, reviewing and designing scalable and efficient code
def process_request(self, request_object): """Process Update Resource Request""" # Retrieve the object by its identifier entity = request_object.entity_cls.get(request_object.identifier) # Update the object and return the updated data resource = entity.update(request_object.dat...
Can you write a function in Python 3 where it processes an update resource request
As a Python code composer, you craft elegant and concise scripts.
def process_request(self, request_object): """Process the Delete Resource Request""" # Delete the object by its identifier entity = request_object.entity_cls.get(request_object.identifier) entity.delete() # FIXME Check for return value of `delete()` # We have successfu...
Write a Python 3 script for processing the Delete Resource Request
As a python code expert, you are capable of creating scripts from specifications.
Convert the value to its string representation
Can you generate a brief explanation for the following Python 3 code def _cast_to_type(self, value): if isinstance(value, str) or value is None: return value return str(value)
As a Python code translator, you convert algorithms and pseudocode into Python.
def _cast_to_type(self, value): """ Convert the value to an int and raise error on failures""" try: return int(value) except (ValueError, TypeError): self.fail('invalid', value=value)
Can you create a Python 3 function that converts the value to an int and raise error on failures
As a Python code composer, you craft elegant and concise scripts.
def _cast_to_type(self, value): """ Convert the value to a float and raise error on failures""" try: return float(value) except (ValueError, TypeError): self.fail('invalid', value=value)
Can you create a Python 3 function that converts the value to a float and raise error on failures
You are a Python code generator, capable of creating scripts from specifications.
def _cast_to_type(self, value): """ Convert the value to a boolean and raise error on failures""" if value in (True, False): return bool(value) if value in ('t', 'True', '1'): return True if value in ('f', 'False', '0'): return False self.fail(...
Write a Python 3 script for converting the value to a boolean and raise error on failures
You are a Python code architect, reviewing and designing scalable and efficient code
def _cast_to_type(self, value): """ Raise error if the value is not a list """ if not isinstance(value, list): self.fail('invalid', value=value) return value
Can you create a Python 3 function that casts the value to the type of the object. Raise error if the value is not a list.
You are a Python code analyst, evaluating scripts for potential improvements.
Cast the value to the type of the object. Raise error if the value is not a dict.
Given the following Python 3 function, write the documentation def _cast_to_type(self, value): if not isinstance(value, dict): self.fail('invalid', value=value) return value
You are a Python code analyst, evaluating scripts for potential improvements.
def _cast_to_type(self, value): """ Convert the value to a date and raise error on failures""" if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value try: value = date_parser(value) re...
Can you implement a function in Python 3 that converts the value to a date and raise error on failures
As a Python code composer, you craft elegant and concise scripts.
Convert the value to a datetime and raise error on failures
Given the following Python 3 function, write the documentation def _cast_to_type(self, value): if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) return value ...
As a Python code composer, you craft elegant and concise scripts.
async def make_request(self, service: str, method: str, path: str, body: bytes=None, query: str=None, headers: dict=None, correlation_id: str=None, content_type: str=None, timeout:int = 30, ...
Can you create a Python 3 function that makes a request to the specified service.
As a Python code translator, you convert algorithms and pseudocode into Python.
Generic executor method of all UseCases
Given the following Python 3 function, write the documentation def execute(self, request_object): # If the request object is not valid then return a failure response if not request_object.is_valid: return ResponseFailure.build_from_invalid_request( request_object) #...
You are a Python code architect, reviewing and designing scalable and efficient code
Decorator to measure execution time of a function in a sequence.
How would you explain what the following Python 3 function does def FunctionTimer(on_done=None): ''' To check execution time of a function borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d >>> def logger(details, args, kwargs): #some func...
As a Python code composer, you craft elegant and concise scripts.
Override this method to change how an exchange is declared
Explain what the following Python 3 code does async def exchange_declare(self): await self.channel.exchange_declare( self.exchange, self.exchange_type, durable=self.durable, auto_delete=self.auto_delete, no_wait=self.no_wait, )
As a python code expert, you are capable of creating scripts from specifications.
Override this method to change how a queue is declared
Explain what the following Python 3 code does async def queue_declare(self): await self.channel.queue_declare( self.queue, durable=self.durable, exclusive=self.exclusive, no_wait=self.no_wait )
You are a Python code generator, capable of creating scripts from specifications.
def from_entity(cls, entity: Entity) -> 'DictModel': """Convert the entity to a dictionary record """ dict_obj = {} for field_name in entity.meta_.attributes: dict_obj[field_name] = getattr(entity, field_name) return dict_obj
Can you write a function in Python 3 where it converts the given entity to a dictionary record
As a python code expert, you are capable of creating scripts from specifications.
Return the dictionary database object
Can you generate a brief explanation for the following Python 3 code def get_connection(self): database = { 'data': _databases.setdefault(self.identifier, defaultdict(dict)), 'lock': _locks.setdefault(self.identifier, Lock()), 'counters': _counters } return da...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_repository(self, entity_cls): """Return a repository object configured with a live connection""" model_cls = self.get_model(entity_cls) return DictRepository(self, entity_cls, model_cls)
Can you create a Python 3 function that returns a repository object configured with a live connection
As a Python code translator, you convert algorithms and pseudocode into Python.
Evaluate the lookup criteria for the given key and value in the given database.
Can you tell what is the following Python 3 function doing def _evaluate_lookup(self, key, value, negated, db): results = {} for record_key, record_value in db.items(): match = True stripped_key, lookup_class = self._extract_lookup(key) lookup = lookup_class(record_v...
You are a Python code generator, capable of creating scripts from specifications.
def raw(self, query: Any, data: Any = None): """Run raw queries on the database As an example of running ``raw`` queries on a Dict repository, we will run the query on all possible schemas, and return all results. """ assert isinstance(query, str) conn = self.get_connec...
Write a Python 3 function that can run raw queries on the database and return all results.
You are a Python code analyst, evaluating scripts for potential improvements.
def _set_auto_fields(self, model_obj): """Set the values of the auto field using counter""" for field_name, field_obj in \ self.entity_cls.meta_.auto_fields: counter_key = f'{self.schema_name}_{field_name}' if not (field_name in model_obj and model_obj[field_name]...
Can you create a Python 3 function that sets the values of the auto fields using counter
You are a Python code analyst, evaluating scripts for potential improvements.
def create(self, model_obj): """Write a record to the dict repository""" # Update the value of the counters model_obj = self._set_auto_fields(model_obj) # Add the entity to the repository identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['l...
Write a Python 3 function that can write a record to the dict repository
As a Python code translator, you convert algorithms and pseudocode into Python.
Recursive function to filter items from dictionary based on the filters
Can you generate the documentation for the following Python 3 function def _filter(self, criteria: Q, db): # Filter the dictionary objects based on the filters negated = criteria.negated input_db = None if criteria.connector == criteria.AND: # Trim database records over succ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Read the repository and return results as per the filer
Make a summary of the following Python 3 code def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()): if criteria.children: items = list(self._filter(criteria, self.conn['data'][self.schema_name]).values()) else: items = list(self.conn['data'][self....
As a Python code analyst, you investigate and solve complex coding mysteries
def update(self, model_obj): """Update the entity record in the dictionary """ identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['lock']: # Check if object is present if identifier not in self.conn['data'][self.schema_name]: ...
How would you code a function in Python 3 to update the entity record in the dictionary
As a python code expert, you are capable of creating scripts from specifications.
Update all objects satisfying the criteria
Explain what the following Python 3 code does def update_all(self, criteria: Q, *args, **kwargs): items = self._filter(criteria, self.conn['data'][self.schema_name]) update_count = 0 for key in items: item = items[key] item.update(*args) item.update(kwargs) ...
You are a Python code generator, capable of creating scripts from specifications.
Delete all the items in the dictionary by its criteria
Here you have a function in Python 3, explain what it does def delete_all(self, criteria: Q = None): if criteria: # Delete the object from the dictionary and return the deletion count items = self._filter(criteria, self.conn['data'][self.schema_name]) # Delete all the matchi...
As a Python code translator, you convert algorithms and pseudocode into Python.
def raw(self, query: Any, data: Any = None): """Run raw query on Repository. For this stand-in repository, the query string is a json string that contains kwargs criteria with straigh-forward equality checks. Individual criteria are always ANDed and the result is always a subset of the ...
Write a Python 3 function for running raw query on Repository.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return source with transformations if any
Make a summary of the following Python 3 code def process_source(self): if isinstance(self.source, str): # Replace single and double quotes with escaped single-quote self.source = self.source.replace("'", "\'").replace('"', "\'") return "\"{source}\"".format(source=self.sourc...
As a Python code analyst, you investigate and solve complex coding mysteries
def process_target(self): """Return target with transformations, if any""" if isinstance(self.target, str): # Replace single and double quotes with escaped single-quote self.target = self.target.replace("'", "\'").replace('"', "\'") return "\"{target}\"".format(target...
Write a Python 3 script to return target with transformations if any
As a Python code translator, you convert algorithms and pseudocode into Python.
def challenge(arg: ChallengeArg) -> dict: """ Response is dict like `Trial` because Status(OwlEnum) can't be pickled. """ name: str = arg.req.name.get_or(str(arg.seq)) log_prefix = f"[{arg.seq} / {arg.number_of_request}]" logger.info_lv3(f"{log_prefix} {'-'*80}") logger.info_lv3(f"{log_prefix}...
Write a Python 3 script for returning a response dict like Trial because Status can t be pickled.
As a Python code composer, you craft elegant and concise scripts.
def parse_url_to_topic(method, route): """ Transforms a URL to a topic. `GET /bar/{id}` -> `get.bar.*` `POST /bar/{id}` -> `post.bar.*` `GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz` Possible gotchas `GET /foo/{id}` -> `get.foo.*` `GET /foo/{id}:action` -> `get.foo.*` However, on...
How would you implement a function in Python 3 that parses a URL to a topic.
You are a Python code generator, capable of creating scripts from specifications.
def wrap(anything: bytes, encoding: str) -> str: """Use for example of Transformer.function """ return json.dumps({ "wrap": load_json(anything.decode(encoding)) }, ensure_ascii=False)
Can you implement a function in Python 3 that uses for example of Transformer. function
As a Python code composer, you craft elegant and concise scripts.
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()) -> ResultSet: """ Filter objects from the repository. Method must return a `ResultSet` object """
Create a Python 3 function for returning a ResultSet containing only the records matching the given criteria.
As a python code expert, you are capable of creating scripts from specifications.
Process the declared fields and construct a list of tuples that can be fed into dataclass constructor factory factory.
Can you generate a brief explanation for the following Python 3 code def _format_fields(cls, declared_fields: typing.List[tuple]): formatted_fields = [] for declared_field in declared_fields: field_name = field_type = field_defn = None # Case when only (name), or "name", is spec...
You are a Python code generator, capable of creating scripts from specifications.
def save(params, filename, source): ''' Write a sequence of samples as a WAV file Currently a 16 bit mono file ''' writer = wave.open(filename, 'wb'); # Set the WAV file parameters, currently default values writer.setnchannels(1) writer.setsampwidth(2) writer.setframerate(params.samp...
Create a Python 3 function to save a sequence of samples as a WAV file
As a Python code analyst, you investigate and solve complex coding mysteries
def smallest(self): """Return the item with the lowest priority. Raises IndexError if the object is empty. """ heap = self._heap v, k = heap[0] while k not in self or self[k] != v: heappop(heap) v, k = heap[0] return k
Implement a Python 3 function for returning the item with the lowest priority. Raises IndexError if the object is empty.
As a python code expert, you are capable of creating scripts from specifications.
Return the item with the lowest priority and remove it. Raises IndexError if the object is empty. Returns the item with the lowest priority and remove it. Raises IndexError if the object is empty.
Can you generate a brief explanation for the following Python 3 code def pop_smallest(self): heap = self._heap v, k = heappop(heap) while k not in self or self[k] != v: v, k = heappop(heap) del self[k] return k
As a Python code composer, you craft elegant and concise scripts.
def body(self) -> dict: """ Decoded Body """ if self.ignore_content_type: return self.original_body if self._body is None and self.original_body is not None: if isinstance(self.original_body, bytes): self._body = self.parser.decode(self.original_body) ...
Can you create a Python 3 function that decodes the original body.
You are a Python code analyst, evaluating scripts for potential improvements.
def raw_body(self) -> bytes: """ Encoded Body """ if self._raw_body is None and self.original_body is not None: if isinstance(self.original_body, dict): self._raw_body = self.parser.encode(self.original_body) if isinstance(self._raw_body, str): ...
Create a Python 3 function for returning the raw HTTP request body.
As a Python code analyst, you investigate and solve complex coding mysteries
Redirect messages to the dummy outbox
Given the following Python 3 function, write the documentation def send_messages(self, messages): msg_count = 0 for message in messages: # .message() triggers header validation message.message() email.outbox.append(message) msg_count += 1 return msg_count
You are a Python code generator, capable of creating scripts from specifications.
def square_wave(params, frequency=400, amplitude=1, offset=0, ratio=0.5): ''' Generate a square wave :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :param offs...
Write a Python 3 function for generating a square wave of the given frequency amplitude and offset ratio
As a Python code translator, you convert algorithms and pseudocode into Python.
def noise(params, amplitude=1, offset=0): ''' Generate a noise signal :param params: buffer parameters, controls length of signal created :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero (array or value) :return: array of resulting signal ''' ...
How would you implement a function in Python 3 that generates a noise signal
You are a Python code architect, reviewing and designing scalable and efficient code