output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Adds the base64 encoded values of the indices to the index.
Can you tell what is the following Python 3 function doing def _add_to_indices(self, pipeline): for att in self.indices: self._add_to_index(att, pipeline=pipeline)
As a Python code composer, you craft elegant and concise scripts.
def _add_to_index(self, att, val=None, pipeline=None): """ Adds the id to the index. This also adds to the _indices set of the object. """ index = self._index_key_for(att) if index is None: return t, index = index if t == 'attribute': ...
Implement a function in Python 3 to add the id to the index.
As a Python code composer, you craft elegant and concise scripts.
Deletes the object s id from the sets ( indices ) it has been added to and removes its list of indices.
Here you have a function in Python 3, explain what it does def _delete_from_indices(self, pipeline): s = Set(self.key()['_indices']) z = Set(self.key()['_zindices']) for index in s.members: pipeline.srem(index, self.id) for index in z.members: pipeline.zrem(index,...
As a Python code composer, you craft elegant and concise scripts.
Returns a key based on the attribute and its value.
Can you generate a brief explanation for the following Python 3 code def _index_key_for(self, att, value=None): if value is None: value = getattr(self, att) if callable(value): value = value() if value is None: return None if att not in self.li...
As a python code expert, you are capable of creating scripts from specifications.
def isdisjoint(self, other): """Return True if the set has no elements in common with other.""" return not bool(self.db.sinter([self.key, other.key]))
Implement a Python 3 function for returning True if the set has no elements in common with other.
As a python code expert, you are capable of creating scripts from specifications.
def union(self, key, *others): """Return a new set with elements from the set and all others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sunionstore(key, [self.key] + [o.key for o in others]) return Set(key)
Implement a function in Python 3 to return a new set with elements from the set and all others.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a new set with elements common to the set and all others.
Can you generate a brief explanation for the following Python 3 code def intersection(self, key, *others): if not isinstance(key, str): raise ValueError("String expected.") self.db.sinterstore(key, [self.key] + [o.key for o in others]) return Set(key)
As a python code expert, you are capable of creating scripts from specifications.
def difference(self, key, *others): """Return a new set with elements in the set that are not in the others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sdiffstore(key, [self.key] + [o.key for o in others]) return Set(key)
Implement a Python 3 function for returning a new set with elements in the set that are not in the others.
You are a Python code generator, capable of creating scripts from specifications.
Update the set with the elements from all others.
Make a summary of the following Python 3 code def update(self, *others): self.db.sunionstore(self.key, [self.key] + [o.key for o in others])
As a Python code translator, you convert algorithms and pseudocode into Python.
Update the set keeping only elements found in it and all others.
Make a summary of the following Python 3 code def intersection_update(self, *others): self.db.sinterstore(self.key, [o.key for o in [self.key] + others])
As a python code expert, you are capable of creating scripts from specifications.
Update the set removing elements found in others.
Can you generate the documentation for the following Python 3 function def difference_update(self, *others): self.db.sdiffstore(self.key, [o.key for o in [self.key] + others])
As a Python code analyst, you investigate and solve complex coding mysteries
Copy the set to another key and return the new Set.
Here you have a function in Python 3, explain what it does def copy(self, key): copy = Set(key=key, db=self.db) copy.clear() copy |= self return copy
As a Python code analyst, you investigate and solve complex coding mysteries
Performs an intersection between this set and the given set of common members. Uses Redis. sinter.
Here you have a function in Python 3, explain what it does def sinter(self, *other_sets): return self.db.sinter([self.key] + [s.key for s in other_sets])
As a Python code analyst, you investigate and solve complex coding mysteries
Union between Sets. Returns a set of common members. Uses Redis. sdiff.
Given the following Python 3 function, write the documentation def sdiff(self, *other_sets): return self.db.sdiff([self.key] + [s.key for s in other_sets])
As a Python code analyst, you investigate and solve complex coding mysteries
Copy the list to a new list.
Can you tell what is the following Python 3 function doing def copy(self, key): copy = List(key, self.db) copy.clear() copy.extend(self) return copy
As a Python code composer, you craft elegant and concise scripts.
Returns the list of the members of the set that have scores less than v.
Can you generate the documentation for the following Python 3 function def lt(self, v, limit=None, offset=None): if limit is not None and offset is None: offset = 0 return self.zrangebyscore(self._min_score, "(%f" % v, start=offset, num=limit)
As a Python code analyst, you investigate and solve complex coding mysteries
def gt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores greater than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore("(%f" % v, self._max_score, start=offset, num=lim...
Write a Python 3 function that can return the list of members of the set that have scores greater than v.
As a Python code translator, you convert algorithms and pseudocode into Python.
def between(self, min, max, limit=None, offset=None): """Returns the list of the members of the set that have scores between min and max. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore(min, max, start=offset, num=limi...
Create a Python 3 function for returning the members of the set that have scores between min and max.
As a python code expert, you are capable of creating scripts from specifications.
convert hex string to bytes
Explain what the following Python 3 code does def hex_to_bytes(s): if len(s) % 2: s = b'0' + s ia = [int(s[i:i+2], 16) for i in range(0, len(s), 2)] # int array return bs(ia) if PYTHON_MAJOR_VER == 3 else b''.join([chr(c) for c in ia])
As a Python code analyst, you investigate and solve complex coding mysteries
Random seed for the client public key and private key.
How would you explain what the following Python 3 function does def client_seed(a=random.randrange(0, 1 << SRP_KEY_SIZE)): if DEBUG: a = DEBUG_PRIVATE_KEY N, g, k = get_prime() A = pow(g, a, N) if DEBUG_PRINT: print('a=', binascii.b2a_hex(long2bytes(a)), end='\n') print('A=', bin...
As a python code expert, you are capable of creating scripts from specifications.
Random seed for server public key and private key.
Given the following Python 3 function, write the documentation def server_seed(v, b=random.randrange(0, 1 << SRP_KEY_SIZE)): N, g, k = get_prime() if DEBUG: b = DEBUG_PRIVATE_KEY gb = pow(g, b, N) kv = (k * v) % N B = (kv + gb) % N if DEBUG_PRINT: print("v", binascii.b2a_hex(long...
As a Python code analyst, you investigate and solve complex coding mysteries
Client session secret Both: u = H(A, B) User: x = H(s, p) (user enters password) User: S = (B - kg^x) ^ (a + ux) (computes session key) User: K = H(S)
Can you generate a brief explanation for the following Python 3 code def client_session(user, password, salt, A, B, a): N, g, k = get_prime() u = get_scramble(A, B) x = getUserHash(salt, user, password) # x gx = pow(g, x, N) # g^x kgx = (k * gx) % N # kg^...
As a python code expert, you are capable of creating scripts from specifications.
def server_session(user, password, salt, A, B, b): """ Server session secret Both: u = H(A, B) Host: S = (Av^u) ^ b (computes session key) Host: K = H(S) """ N, g, k = get_prime() u = get_scramble(A, B) v = get_verifier(user, password, salt) vu = pow(...
How would you implement a function in Python 3 that computes the server session secret
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert a DPD encoded value to an integer.
Given the following Python 3 function, write the documentation def dpd_to_int(dpd): b = [None] * 10 b[9] = 1 if dpd & 0b1000000000 else 0 b[8] = 1 if dpd & 0b0100000000 else 0 b[7] = 1 if dpd & 0b0010000000 else 0 b[6] = 1 if dpd & 0b0001000000 else 0 b[5] = 1 if dpd & 0b0000100000 else 0 b[...
You are a Python code analyst, evaluating scripts for potential improvements.
def calc_significand(prefix, dpd_bits, num_bits): """ prefix: High bits integer value dpd_bits: dpd encoded bits num_bits: bit length of dpd_bits """ # https://en.wikipedia.org/wiki/Decimal128_floating-point_format#Densely_packed_decimal_significand_field num_segments = num_bits // 10 se...
Implement a Python 3 function for calculating the significand of a given number of bits.
You are a Python code generator, capable of creating scripts from specifications.
decimal128 bytes to Decimal
Here you have a function in Python 3, explain what it does def decimal128_to_decimal(b): "decimal128 bytes to Decimal" v = decimal128_to_sign_digits_exponent(b) if isinstance(v, Decimal): return v sign, digits, exponent = v return Decimal((sign, Decimal(digits).as_tuple()[1], exponent))
As a python code expert, you are capable of creating scripts from specifications.
Raises an exception if the response code is not a valid service error.
Can you generate the documentation for the following Python 3 function def error_response(response): if response.status_code >= 500: raise exceptions.GeocodioServerError elif response.status_code == 403: raise exceptions.GeocodioAuthError elif response.status_code == 422: raise exc...
As a Python code translator, you convert algorithms and pseudocode into Python.
Wrap all request building
Can you generate a brief explanation for the following Python 3 code def _req(self, method="get", verb=None, headers={}, params={}, data={}): url = self.BASE_URL.format(verb=verb) request_headers = {"content-type": "application/json"} request_params = {"api_key": self.API_KEY} request_he...
As a Python code composer, you craft elegant and concise scripts.
Returns an Address dictionary with the components of the queried address.
Can you tell what is the following Python 3 function doing def parse(self, address): response = self._req(verb="parse", params={"q": address}) if response.status_code != 200: return error_response(response) return Address(response.json())
You are a Python code generator, capable of creating scripts from specifications.
def batch_geocode(self, addresses, **kwargs): """ Returns an Address dictionary with the components of the queried address. """ fields = ",".join(kwargs.pop("fields", [])) response = self._req( "post", verb="geocode", params={"fields": ...
Can you create a Python 3 function that returns a dictionary with the components of the queried address.
As a Python code translator, you convert algorithms and pseudocode into Python.
def geocode_address(self, address, **kwargs): """ Returns a Location dictionary with the components of the queried address and the geocoded location. >>> client = GeocodioClient('some_api_key') >>> client.geocode("1600 Pennsylvania Ave, Washington DC") { "input":...
Write a Python 3 function that can return a Location dictionary with the components of the queried address and the geocoded location.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a geocoding data for the given address data.
Given the following Python 3 function, write the documentation def geocode(self, address_data, **kwargs): if isinstance(address_data, list): return self.batch_geocode(address_data, **kwargs) return self.geocode_address(address_data, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
This method is used to identify an address from a geographic point
Can you tell what is the following Python 3 function doing def reverse_point(self, latitude, longitude, **kwargs): fields = ",".join(kwargs.pop("fields", [])) point_param = "{0},{1}".format(latitude, longitude) response = self._req( verb="reverse", params={"q": point_param, "fields":...
You are a Python code analyst, evaluating scripts for potential improvements.
Method for identifying the addresses from a list of lat / lng tuples
Can you generate a brief explanation for the following Python 3 code def batch_reverse(self, points, **kwargs): fields = ",".join(kwargs.pop("fields", [])) response = self._req( "post", verb="reverse", params={"fields": fields}, data=json_points(points) ) if response.status_c...
As a Python code translator, you convert algorithms and pseudocode into Python.
def str_to_bytes(self, s): "convert str to bytes" if (PYTHON_MAJOR_VER == 3 or (PYTHON_MAJOR_VER == 2 and type(s) == unicode)): return s.encode(charset_map.get(self.charset, self.charset)) return s
Write a Python 3 script to convert str to bytes
As a Python code composer, you craft elegant and concise scripts.
def bytes_to_str(self, b): "convert bytes array to raw string" if PYTHON_MAJOR_VER == 3: return b.decode(charset_map.get(self.charset, self.charset)) return b
Write a Python 3 function that can convert bytes array to raw string
As a Python code composer, you craft elegant and concise scripts.
def bytes_to_ustr(self, b): "convert bytes array to unicode string" return b.decode(charset_map.get(self.charset, self.charset))
Implement a Python 3 function for converting bytes array to unicode string
As a Python code translator, you convert algorithms and pseudocode into Python.
def params_to_blr(self, trans_handle, params): "Convert parameter array to BLR and values format." ln = len(params) * 2 blr = bs([5, 2, 4, 0, ln & 255, ln >> 8]) if self.accept_version < PROTOCOL_VERSION13: values = bs([]) else: # start with null indicator...
Write a Python 3 function for converting parameter array to BLR and values format.
As a python code expert, you are capable of creating scripts from specifications.
def coords(self): """ Returns a tuple representing the location of the address in a GIS coords format, i.e. (longitude, latitude). """ x, y = ("lat", "lng") if self.order == "lat" else ("lng", "lat") try: return (self["location"][x], self["location"][y]) ...
Write a Python 3 function for returning a tuple representing the location of the address in GIS coords format i. e. longitude latitude.
As a python code expert, you are capable of creating scripts from specifications.
def get(self, key): """ Returns an individual Location by query lookup, e.g. address or point. """ if isinstance(key, tuple): # TODO handle different ordering try: x, y = float(key[0]), float(key[1]) except IndexError: ...
Implement a Python 3 function for returning an individual Location by query lookup e. g. address or point.
As a python code expert, you are capable of creating scripts from specifications.
def calc_blr(xsqlda): "Calculate BLR from XSQLVAR array." ln = len(xsqlda) * 2 blr = [5, 2, 4, 0, ln & 255, ln >> 8] for x in xsqlda: sqltype = x.sqltype if sqltype == SQL_TYPE_VARYING: blr += [37, x.sqllen & 255, x.sqllen >> 8] elif sqltype == SQL_TYPE_TEXT: ...
Create a Python 3 function to calculate BLR from XSQLVAR array.
As a python code expert, you are capable of creating scripts from specifications.
def _parse_date(self, raw_value): "Convert raw data to datetime.date" nday = bytes_to_bint(raw_value) + 678882 century = (4 * nday - 1) // 146097 nday = 4 * nday - 1 - 146097 * century day = nday // 4 nday = (4 * day + 3) // 1461 day = 4 * day + 3 - 1461 * nday ...
Create a Python 3 function to convert raw data to datetime. date
As a python code expert, you are capable of creating scripts from specifications.
def _parse_time(self, raw_value): "Convert raw data to datetime.time" n = bytes_to_bint(raw_value) s = n // 10000 m = s // 60 h = m // 60 m = m % 60 s = s % 60 return (h, m, s, (n % 10000) * 100)
Can you create a Python 3 function that converts raw data to datetime. time
As a Python code translator, you convert algorithms and pseudocode into Python.
Execute the update based on command line args and returns a dictionary with execution result response code response info and process friendly message.
Can you generate the documentation for the following Python 3 function def execute_update(args): provider_class = getattr(dnsupdater, dnsupdater.AVAILABLE_PLUGINS.get(args.provider)) updater_options = {} process_message = None auth = None if args.store: # --store argu...
As a Python code translator, you convert algorithms and pseudocode into Python.
def update_dns(self, new_ip): """Call No-IP API based on dict login_info and return the status code. """ headers = None if self.auth_type == 'T': api_call_url = self._base_url.format(hostname=self.hostname, token=self.auth.tok...
Implement a Python 3 function for calling No - IP API based on dict login_info and return the status code and the text of the response.
You are a Python code analyst, evaluating scripts for potential improvements.
def status_message(self): """Return friendly response from API based on response code. """ msg = None if self.last_ddns_response in response_messages.keys(): return response_messages.get(self.last_ddns_response) if 'good' in self.last_ddns_response: ip = re.sear...
Can you implement a function in Python 3 that returns friendly response from API based on response code.
You are a Python code architect, reviewing and designing scalable and efficient code
Return machine s origin IP address.
Explain what the following Python 3 code does def get_ip(): try: r = requests.get(HTTPBIN_URL) ip, _ = r.json()['origin'].split(',') return ip if r.status_code == 200 else None except requests.exceptions.ConnectionError: return None
As a Python code analyst, you investigate and solve complex coding mysteries
def store(auth, provider, config_location=DEFAULT_CONFIG_DIR): """Store auth info in file for specified provider """ auth_file = None try: # only for custom locations _create_config_dir(config_location, "Creating custom config directory [%s]... ") config_...
How would you implement a function in Python 3 that stores auth info in file for specified provider
You are a Python code analyst, evaluating scripts for potential improvements.
def load(provider, config_location=DEFAULT_CONFIG_DIR): """Load provider specific auth info from file """ auth = None auth_file = None try: config_dir = os.path.join(config_location, NOIPY_CONFIG) print("Loading stored auth info [%s]... " % config_dir, end="") auth_file = os.pat...
Write a Python 3 script to load provider specific auth info from file
You are a Python code architect, reviewing and designing scalable and efficient code
def exists(provider, config_location=DEFAULT_CONFIG_DIR): """Check whether provider info is already stored """ config_dir = os.path.join(config_location, NOIPY_CONFIG) auth_file = os.path.join(config_dir, provider) return os.path.exists(auth_file)
How would you code a function in Python 3 to check whether provider info is already stored
You are a Python code architect, reviewing and designing scalable and efficient code
Return an ApiAuth instance from an encoded key
Can you generate the documentation for the following Python 3 function def get_instance(cls, encoded_key): login_str = base64.b64decode(encoded_key).decode('utf-8') usertoken, password = login_str.strip().split(':', 1) instance = cls(usertoken, password) return instance
You are a Python code generator, capable of creating scripts from specifications.
def update_index(model_items, model_name, action='index', bulk_size=100, num_docs=-1, start_date=None, end_date=None, refresh=True): ''' Updates the index for the provided model_items. :param model_items: a list of model_items (django Model instances, or proxy instances) which are to be indexed/updated or d...
How would you implement a function in Python 3 that updates the index for the provided list of models.
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete an item from the index.
How would you explain what the following Python 3 function does def delete_index_item(item, model_name, refresh=True): ''' Deletes an item from the index. :param item: must be a serializable object. :param model_name: doctype, which must also be the model name. :param refresh: a boolean that determi...
You are a Python code architect, reviewing and designing scalable and efficient code
Creates the document that will be passed into the bulk index function.
Given the following Python 3 function, write the documentation def create_indexed_document(index_instance, model_items, action): ''' Creates the document that will be passed into the bulk index function. Either a list of serialized objects to index, or a a dictionary specifying the primary keys of items to ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def filter_model_items(index_instance, model_items, model_name, start_date, end_date): ''' Filters the model items queryset based on start and end date.''' if index_instance.updated_field is None: logger.warning("No updated date field found for {} - not restricting with start and end date".format(model_...
Implement a function in Python 3 to filter the model items queryset based on start and end date.
You are a Python code architect, reviewing and designing scalable and efficient code
This function tries to extract the version from the help text of any program.
How would you explain what the following Python 3 function does def extract_version(txt): words = txt.replace(',', ' ').split() version = None for x in reversed(words): if len(x) > 2: if x[0].lower() == 'v': x = x[1:] if '.' in x and x[0].isdigit(): ...
As a python code expert, you are capable of creating scripts from specifications.
Run command with arguments. Wait for command to complete.
Can you tell what is the following Python 3 function doing def check(self, return_code=0): ret = self.call().return_code ok = ret == return_code if not ok: raise EasyProcessError( self, 'check error, return code is not {0}!'.format(return_code)) return self
As a Python code analyst, you investigate and solve complex coding mysteries
def call(self, timeout=None): """Run command with arguments. Wait for command to complete. same as: 1. :meth:`start` 2. :meth:`wait` 3. :meth:`stop` :rtype: self """ self.start().wait(timeout=timeout) if self.is_alive(): self.stop...
Create a Python 3 function to wait for command to complete.
You are a Python code analyst, evaluating scripts for potential improvements.
start command in background and does not wait for it.
Make a summary of the following Python 3 code def start(self): if self.is_started: raise EasyProcessError(self, 'process was started twice!') if self.use_temp_files: self._stdout_file = tempfile.TemporaryFile(prefix='stdout_') self._stderr_file = tempfile.TemporaryFi...
As a Python code analyst, you investigate and solve complex coding mysteries
def wait(self, timeout=None): """Wait for command to complete. Timeout: - discussion: http://stackoverflow.com/questions/1191374/subprocess-with-timeout - implementation: threading :rtype: self """ if timeout is not None: if not self._thread: ...
Write a Python 3 function for waiting for command to complete.
As a python code expert, you are capable of creating scripts from specifications.
Send SIGTERM to the process.
Can you tell what is the following Python 3 function doing def sendstop(self): ''' Kill process (:meth:`subprocess.Popen.terminate`). Do not wait for command to complete. :rtype: self ''' if not self.is_started: raise EasyProcessError(self, 'process was not s...
As a Python code analyst, you investigate and solve complex coding mysteries
A decorator that wraps a function which returns a function which starts process AttributeNames 2. call func save result AttributeNames 3. stop process AttributeNames 4. return a function which returns a function which returns None
Can you generate the documentation for the following Python 3 function def wrap(self, func, delay=0): ''' returns a function which: 1. start process 2. call func, save result 3. stop process 4. returns result similar to :keyword:`with` statement :rty...
As a Python code translator, you convert algorithms and pseudocode into Python.
Send a message to a given room
Can you generate the documentation for the following Python 3 function def send_message(self, message, room_id, **kwargs): return SendMessage(settings=self.settings, **kwargs).call( message=message, room_id=room_id, **kwargs )
As a Python code composer, you craft elegant and concise scripts.
def get_private_rooms(self, **kwargs): """ Get a listing of all private rooms with their names and IDs """ return GetPrivateRooms(settings=self.settings, **kwargs).call(**kwargs)
Can you write a function in Python 3 where it gets a listing of all private rooms with their names and IDs.
As a Python code composer, you craft elegant and concise scripts.
def get_private_room_history(self, room_id, oldest=None, **kwargs): """ Get various history of specific private group in this case private :param room_id: :param kwargs: :return: """ return GetPrivateRoomHistory(settings=self.settings, **kwargs).call( ...
Write a Python 3 script to get various history of specific private group in this case
As a python code expert, you are capable of creating scripts from specifications.
Get a listing of all public rooms with their names and IDs.
Given the following Python 3 function, write the documentation def get_public_rooms(self, **kwargs): return GetPublicRooms(settings=self.settings, **kwargs).call(**kwargs)
You are a Python code generator, capable of creating scripts from specifications.
def get_room_info(self, room_id, **kwargs): """ Get various information about a specific channel/room :param room_id: :param kwargs: :return: """ return GetRoomInfo(settings=self.settings, **kwargs).call( room_id=room_id, **kwargs ...
Write a Python 3 script for getting various information about a specific channel or room.
As a Python code composer, you craft elegant and concise scripts.
def upload_file(self, room_id, description, file, message, **kwargs): """ Upload file to room :param room_id: :param description: :param file: :param kwargs: :return: """ return UploadFile(settings=self.settings, **kwargs).call( room_id...
Can you implement a function in Python 3 that uploads file to a specific room
You are a Python code architect, reviewing and designing scalable and efficient code
def get_private_room_info(self, room_id, **kwargs): """ Get various information about a specific private group :param room_id: :param kwargs: :return: """ return GetPrivateRoomInfo(settings=self.settings, **kwargs).call( room_id=room_id, *...
Implement a Python 3 function for getting various information about a specific private group.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_room_id(self, room_name, **kwargs): """ Get room ID :param room_name: :param kwargs: :return: """ return GetRoomId(settings=self.settings, **kwargs).call( room_name=room_name, **kwargs )
How would you implement a function in Python 3 that gets room ID :param room_name: :param kwargs: :return:
As a Python code translator, you convert algorithms and pseudocode into Python.
Get various history of specific channel and room.
Can you tell what is the following Python 3 function doing def get_room_history( self, room_id, oldest=None, latest=datetime.now(), inclusive=False, count=20, ...
As a Python code analyst, you investigate and solve complex coding mysteries
Create public room with given name.
Can you generate the documentation for the following Python 3 function def create_public_room(self, name, **kwargs): return CreatePublicRoom(settings=self.settings, **kwargs).call(name=name, **kwargs)
You are a Python code analyst, evaluating scripts for potential improvements.
Delete public room with given ID
Can you generate the documentation for the following Python 3 function def delete_public_room(self, room_id, **kwargs): return DeletePublicRoom(settings=self.settings, **kwargs).call(room_id=room_id, **kwargs)
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_users(self, **kwargs): """ Gets all of the users in the system and their information :param kwargs: :return: """ return GetUsers(settings=self.settings, **kwargs).call(**kwargs)
Implement a Python 3 function for getting all of the users in the system and their information
As a Python code composer, you craft elegant and concise scripts.
def get_user_info(self, user_id, **kwargs): """ Retrieves information about a user, the result is only limited to what the callee has access to view. :param user_id: :param kwargs: :return: """ return GetUserInfo(settings=self.settings, **kwargs).call( ...
Can you write a function in Python 3 where it retrieves information about a user
As a Python code analyst, you investigate and solve complex coding mysteries
Create user in nagios user store
Make a summary of the following Python 3 code def create_user(self, email, name, password, username, **kwargs): return CreateUser(settings=self.settings, **kwargs).call( email=email, name=name, password=password, username=username, **kwargs )
You are a Python code analyst, evaluating scripts for potential improvements.
Delete user from cache
Given the following Python 3 function, write the documentation def delete_user(self, user_id, **kwargs): return DeleteUser(settings=self.settings, **kwargs).call(user_id=user_id, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
def get_index(cls, model, via_class=False): ''' Returns the index name (as a string) for the given model as a class or a string. :param model: model name or model class if via_class set to True. :param via_class: set to True if parameter model is a class. :raise KeyError: If the ...
Implement a Python 3 function for returning the index name for the given model.
As a python code expert, you are capable of creating scripts from specifications.
def get_model_index(cls, model, default=True): ''' Returns the default model index for the given model, or the list of indices if default is False. :param model: model name as a string. :raise KeyError: If the provided model does not have any index associated. ''' try: ...
Can you write a function in Python 3 where it returns the model index for the given model.
You are a Python code generator, capable of creating scripts from specifications.
def get_models(cls, index, as_class=False): ''' Returns the list of models defined for this index. :param index: index name. :param as_class: set to True to return the model as a model object instead of as a string. ''' try: return cls._index_to_model[index] i...
Write a Python 3 script for returning the list of models defined for this index.
As a Python code composer, you craft elegant and concise scripts.
def get_model_indices(cls, index): ''' Returns the list of model indices (i.e. ModelIndex objects) defined for this index. :param index: index name. ''' try: return cls._idx_name_to_mdl_to_mdlidx[index].values() except KeyError: raise KeyError('Cou...
Create a Python 3 function to return the list of model indices defined for this index.
You are a Python code analyst, evaluating scripts for potential improvements.
Maps raw results to database model objects.
Can you tell what is the following Python 3 function doing def map_raw_results(cls, raw_results, instance=None): ''' Maps raw results to database model objects. :param raw_results: list raw results as returned from elasticsearch-dsl-py. :param instance: Bungiesearch instance if you want ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Must clone additional fields to those cloned by elasticsearch-dsl-py.
Here you have a function in Python 3, explain what it does def _clone(self): ''' Must clone additional fields to those cloned by elasticsearch-dsl-py. ''' instance = super(Bungiesearch, self)._clone() instance._raw_results_only = self._raw_results_only return instance
As a python code expert, you are capable of creating scripts from specifications.
def execute(self, return_results=True): ''' Executes the query and attempts to create model objects from results. ''' if self.results: return self.results if return_results else None self.execute_raw() if self._raw_results_only: self.results = se...
Implement a function in Python 3 to execute the query and attempts to create model objects from results.
You are a Python code analyst, evaluating scripts for potential improvements.
Restrict the fields to be fetched when mapping.
Here you have a function in Python 3, explain what it does def only(self, *fields): ''' Restricts the fields to be fetched when mapping. Set to `__model` to fetch all fields define in the ModelIndex. ''' s = self._clone() if len(fields) == 1 and fields[0] == '__model': ...
As a Python code composer, you craft elegant and concise scripts.
def hook_alias(self, alias, model_obj=None): ''' Returns the alias function, if it exists and if it can be applied to this model. ''' try: search_alias = self._alias_hooks[alias] except KeyError: raise AttributeError('Could not find search alias named {}. ...
Write a Python 3 function for returning the function that will be called when an alias is applied to this model.
As a Python code composer, you craft elegant and concise scripts.
def custom_search(self, index, doc_type): ''' Performs a search on a custom elasticsearch index and mapping. Will not attempt to map result objects. ''' from bungiesearch import Bungiesearch return Bungiesearch(raw_results=True).index(index).doc_type(doc_type)
How would you code a function in Python 3 to perform a custom elasticsearch search on a custom index and mapping. Will not attempt to map result objects.
As a Python code analyst, you investigate and solve complex coding mysteries
Sets up the signal processor.
Can you generate a brief explanation for the following Python 3 code def contribute_to_class(self, cls, name): ''' Sets up the signal processor. Since self.model is not available in the constructor, we perform this operation here. ''' super(BungiesearchManager, self).contribute_t...
You are a Python code analyst, evaluating scripts for potential improvements.
def django_field_to_index(field, **attr): ''' Returns the index field type that would likely be associated with each Django type. ''' dj_type = field.get_internal_type() if dj_type in ('DateField', 'DateTimeField'): return DateField(**attr) elif dj_type in ('BooleanField', 'NullBoolean...
Write a Python 3 function that can return the index field type that would likely be associated with each Django type.
You are a Python code generator, capable of creating scripts from specifications.
def value(self, obj): ''' Computes the value of this field to update the index. :param obj: object instance, as a dictionary or as a model instance. ''' if self.template_name: t = loader.select_template([self.template_name]) return t.render(Context({'objec...
How would you implement a function in Python 3 that computes the value of this field to update the index.
You are a Python code architect, reviewing and designing scalable and efficient code
split command into list of strings
Can you generate the documentation for the following Python 3 function def split_command(cmd, posix=None): ''' - cmd is string list -> nothing to do - cmd is string -> split it using shlex :param cmd: string ('ls -l') or list of strings (['ls','-l']) :rtype: string list ''' if not isinsta...
You are a Python code generator, capable of creating scripts from specifications.
def get_mapping(self, meta_fields=True): ''' Returns the mapping for the index as a dictionary. :param meta_fields: Also include elasticsearch meta fields in the dictionary. :return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype. '''...
Implement a Python 3 function for returning the mapping for the index as a dictionary.
As a Python code composer, you craft elegant and concise scripts.
collects the analysis definition from the analyzer class
Explain what the following Python 3 code does def collect_analysis(self): ''' :return: a dictionary which is used to get the serialized analyzer definition from the analyzer class. ''' analysis = {} for field in self.fields.values(): for analyzer_name in ('analyzer', ...
As a python code expert, you are capable of creating scripts from specifications.
def serialize_object(self, obj, obj_pk=None): ''' Serializes an object for it to be added to the index. :param obj: Object to be serialized. Optional if obj_pk is passed. :param obj_pk: Object primary key. Superseded by `obj` if available. :return: A dictionary representing the ...
Implement a Python 3 function for serializing an object for it to be added to the index.
You are a Python code architect, reviewing and designing scalable and efficient code
def _get_fields(self, fields, excludes, hotfixes): ''' Given any explicit fields to include and fields to exclude, add additional fields based on the associated model. If the field needs a hotfix, apply it. ''' final_fields = {} fields = fields or [] excludes = ex...
Create a Python 3 function for giving any explicit fields to include and fields to exclude add additional fields based on the associated model.
As a Python code translator, you convert algorithms and pseudocode into Python.
Validates the items in the backing array including the items in the backing array including the _typed property and clears the dirty flag as a side effect Sets the dirty flag as a side effect clears the dirty flag as a side effect
Can you generate the documentation for the following Python 3 function def validate_items(self): logger.debug(fmt("Validating {}", self)) from python_jsonschema_objects import classbuilder if self.__itemtype__ is None: return type_checks = self.__itemtype__ if not i...
As a Python code analyst, you investigate and solve complex coding mysteries
Create an array validator based on the passed in constraints.
Explain what the following Python 3 code does def create(name, item_constraint=None, **addl_constraints): logger.debug(fmt("Constructing ArrayValidator with {} and {}", item_constraint, addl_constraints)) from python_jsonschema_objects import classbuilder klassbuilder = addl_constraints.pop("cla...
As a Python code translator, you convert algorithms and pseudocode into Python.
def extendMarkdown(self, md, md_globals): """ Add FencedBlockPreprocessor to the Markdown instance. """ md.registerExtension(self) md.preprocessors.add('fenced_code_block', SpecialFencePreprocessor(md), ">normalize_whitespace")
Write a Python 3 function for adding the FencedBlockPreprocessor to the Markdown instance.
As a Python code translator, you convert algorithms and pseudocode into Python.
def propmerge(into, data_from): """ Merge JSON schema requirements into a dictionary """ newprops = copy.deepcopy(into) for prop, propval in six.iteritems(data_from): if prop not in newprops: newprops[prop] = propval continue new_sp = newprops[prop] for subp...
Write a Python 3 function that can merge JSON schema requirements into a dictionary.
As a python code expert, you are capable of creating scripts from specifications.
def as_dict(self): """ Return a dictionary containing the current values of the object. Returns: (dict): The object represented as a dictionary """ out = {} for prop in self: propval = getattr(self, prop) if hasattr(propval, 'for_json...
Implement a function in Python 3 to return a dictionary containing the current values of the object.
As a python code expert, you are capable of creating scripts from specifications.