docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Adds a logical interface to a thing type. Parameters: - thingTypeId (string) - the thing type - logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface Throws APIException on failure.
def addLogicalInterfaceToThingType(self, thingTypeId, logicalInterfaceId, schemaId = None, name = None): req = ApiClient.allThingTypeLogicalInterfacesUrl % (self.host, "/draft", thingTypeId) body = {"id" : logicalInterfaceId} # body = {"name" : name, "id" : logicalInterfaceId, "schemaId"...
445,435
Removes a logical interface from a thing type. Parameters: - thingTypeId (string) - the thing type - logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface Throws APIException on failure.
def removeLogicalInterfaceFromThingType(self, thingTypeId, logicalInterfaceId): req = ApiClient.oneThingTypeLogicalInterfaceUrl % (self.host, thingTypeId, logicalInterfaceId) resp = requests.delete(req, auth=self.credentials, verify=self.verify) if resp.status_code == 204: s...
445,436
Get all the mappings for a thing type. Parameters: - thingTypeId (string) - the thing type - draft (boolean) - draft or active Throws APIException on failure.
def getMappingsOnThingType(self, thingTypeId, draft=False): if draft: req = ApiClient.allThingTypeMappingsUrl % (self.host, "/draft", thingTypeId) else: req = ApiClient.allThingTypeMappingsUrl % (self.host, "", thingTypeId) resp = requests.get(req, auth=self.cre...
445,437
Gets the mappings for a logical interface from a thing type. Parameters: - thingTypeId (string) - the thing type - logicalInterfaceId (string) - the platform returned id of the logical interface Throws APIException on failure.
def getMappingsOnThingTypeForLogicalInterface(self, thingTypeId, logicalInterfaceId, draft=False): if draft: req = ApiClient.oneThingTypeMappingUrl % (self.host, "/draft", thingTypeId, logicalInterfaceId) else: req = ApiClient.oneThingTypeMappingUrl % (self.host, "", thi...
445,438
turns the DataFrame returned by getData into a dictionary arguments: the params passed used for table or d3 outputs are forwarded on to getData
def getJsonData(self, params): try: return eval("self." + str(params['output_id']) + "(params)") except AttributeError: df = self.getData(params) if df is None: return None return df.to_dict(orient='records')
447,156
Override this function arguments: params (dict) returns: matplotlib.pyplot figure
def getPlot(self, params): try: return eval("self." + str(params['output_id']) + "(params)") except AttributeError: df = self.getData(params) if df is None: return None return df.plot()
447,158
Run toolchain from UFO sources. Args: ufos: List of UFO sources, as either paths or opened objects. output: List of output formats to generate. kwargs: Arguments passed along to save_otfs.
def run_from_ufos(self, ufos, output=(), **kwargs): if set(output) == {"ufo"}: return # the `ufos` parameter can be a list of UFO objects # or it can be a path (string) with a glob syntax ufo_paths = [] if isinstance(ufos, basestring): ufo_paths...
447,232
Generate an output directory. Args: ext: extension string. is_instance: The output is instance font or not. interpolatable: The output is interpolatable or not. autohinted: The output is autohinted or not. is_variable: The outp...
def _output_dir( self, ext, is_instance=False, interpolatable=False, autohinted=False, is_variable=False, ): assert not (is_variable and any([is_instance, interpolatable])) # FIXME? Use user configurable destination folders. if is_var...
447,235
Initialize a new image viewer. Args: caption (str): the caption/title for the window height (int): the height of the window width (int): the width of the window Returns: None
def __init__(self, caption, height, width): self.caption = caption self.height = height self.width = width self._window = None
447,703
Show an array of pixels on the window. Args: frame (numpy.ndarray): the frame to show on the window Returns: None
def show(self, frame): # check that the frame has the correct dimensions if len(frame.shape) != 3: raise ValueError('frame should have shape with only 3 dimensions') # open the window if it isn't open already if not self.is_open: self.open() # pre...
447,706
Display an image to the pygame screen. Args: screen (pygame.Surface): the pygame surface to write frames to arr (np.ndarray): numpy array representing a single frame of gameplay video_size (tuple): the size to render the frame as transpose (bool): whether to transpose the frame befo...
def display_arr(screen, arr, video_size, transpose): # take the transpose if necessary if transpose: pyg_img = pygame.surfarray.make_surface(arr.swapaxes(0, 1)) else: pyg_img = arr # resize the image according to given image size pyg_img = pygame.transform.scale(pyg_img, video_s...
447,707
Play the game using the keyboard as a human. Args: env (gym.Env): the environment to use for playing transpose (bool): whether to transpose frame before viewing them fps (int): number of steps of the environment to execute every second nop_ (any): the object to use as a null op acti...
def play(env, transpose=True, fps=30, nop_=0): # ensure the observation space is a box of pixels assert isinstance(env.observation_space, gym.spaces.box.Box) # ensure the observation space is either B&W pixels or RGB Pixels obs_s = env.observation_space is_bw = len(obs_s.shape) == 2 is_rgb ...
447,708
Play the environment using keyboard as a human. Args: env (gym.Env): the initialized gym environment to play Returns: None
def play_human(env): # play the game and catch a potential keyboard interrupt try: play(env, fps=env.metadata['video.frames_per_second']) except KeyboardInterrupt: pass # reset and close the environment env.close()
447,709
Initialize a new binary to discrete action space wrapper. Args: env (gym.Env): the environment to wrap actions (list): an ordered list of actions (as lists of buttons). The index of each button list is its discrete coded value Returns: None
def __init__(self, env, actions): super(BinarySpaceToDiscreteSpaceEnv, self).__init__(env) # create the new action space self.action_space = gym.spaces.Discrete(len(actions)) # create the action map from the list of discrete actions self._action_map = {} self._ac...
447,710
Initialize a new ROM. Args: rom_path (str): the path to the ROM file Returns: None
def __init__(self, rom_path): # make sure the rom path is a string if not isinstance(rom_path, str): raise TypeError('rom_path must be of type: str.') # make sure the rom path exists if not os.path.exists(rom_path): msg = 'rom_path points to non-existent ...
447,713
Create a new NES environment. Args: rom_path (str): the path to the ROM for the environment Returns: None
def __init__(self, rom_path): # create a ROM file from the ROM path rom = ROM(rom_path) # check that there is PRG ROM if rom.prg_rom_size == 0: raise ValueError('ROM has no PRG-ROM banks.') # ensure that there is no trainer if rom.has_trainer: ...
447,716
Find the pointer to a controller and setup a NumPy buffer. Args: port: the port of the controller to setup Returns: a NumPy buffer with the controller's binary data
def _controller_buffer(self, port): # get the address of the controller address = _LIB.Controller(self._env, port) # create a memory buffer using the ctypes pointer for this vector buffer_ = ctypes.cast(address, ctypes.POINTER(CONTROLLER_VECTOR)).contents # create a NumP...
447,719
Advance a frame in the emulator with an action. Args: action (byte): the action to press on the joy-pad Returns: None
def _frame_advance(self, action): # set the action on the controller self.controllers[0][:] = action # perform a step on the emulator _LIB.Step(self._env)
447,720
Run one frame of the NES and return the relevant observation data. Args: action (byte): the bitmap determining which buttons to press Returns: a tuple of: - state (np.ndarray): next frame as a result of the given action - reward (float) : amount of rewar...
def step(self, action): # if the environment is done, raise an error if self.done: raise ValueError('cannot step in a done environment! call `reset`') # set the action on the controller self.controllers[0][:] = action # pass the action to the emulator as an u...
447,722
Render the environment. Args: mode (str): the mode to render with: - human: render to the current display - rgb_array: Return an numpy.ndarray with shape (x, y, 3), representing RGB values for an x-by-y pixel image Returns: a numpy array if...
def render(self, mode='human'): if mode == 'human': # if the viewer isn't setup, import it and create one if self.viewer is None: from ._image_viewer import ImageViewer # get the caption for the ImageViewer if self.spec is None: ...
447,724
Play the environment making uniformly random decisions. Args: env (gym.Env): the initialized gym environment to play steps (int): the number of random steps to take Returns: None
def play_random(env, steps): try: done = True progress = tqdm(range(steps)) for _ in progress: if done: _ = env.reset() action = env.action_space.sample() _, reward, done, info = env.step(action) progress.set_postfix(reward...
447,728
Convert string into camel case. Args: string: String to convert. Returns: string: Camel case string.
def camelcase(string): string = re.sub(r"^[\-_\.]", '', str(string)) if not string: return string return lowercase(string[0]) + re.sub(r"[\-_\.\s]([a-z])", lambda matched: uppercase(matched.group(1)), string[1:])
447,736
Convert string into capital case. First letters will be uppercase. Args: string: String to convert. Returns: string: Capital case string.
def capitalcase(string): string = str(string) if not string: return string return uppercase(string[0]) + string[1:]
447,737
Convert string into path case. Join punctuation with slash. Args: string: String to convert. Returns: string: Path cased string.
def pathcase(string): string = snakecase(string) if not string: return string return re.sub(r"_", "/", string)
447,738
Convert string into spinal case. Join punctuation with backslash. Args: string: String to convert. Returns: string: Spinal cased string.
def backslashcase(string): str1 = re.sub(r"_", r"\\", snakecase(string)) return str1
447,739
Convert string into sentence case. First letter capped and each punctuations are joined with space. Args: string: String to convert. Returns: string: Sentence cased string.
def sentencecase(string): joiner = ' ' string = re.sub(r"[\-_\.\s]", joiner, str(string)) if not string: return string return capitalcase(trimcase( re.sub(r"[A-Z]", lambda matched: joiner + lowercase(matched.group(0)), string) ))
447,740
Convert string into snake case. Join punctuation with underscore Args: string: String to convert. Returns: string: Snake cased string.
def snakecase(string): string = re.sub(r"[\-\.\s]", '_', str(string)) if not string: return string return lowercase(string[0]) + re.sub(r"[A-Z]", lambda matched: '_' + lowercase(matched.group(0)), string[1:])
447,741
Bulk operation to directly add record references without making any additional requests Warnings: Does not perform any app, record, or target app/record validation Args: app_id (str): Full App ID string record_id (str): Full parent Record ID string field...
def add_record_references(self, app_id, record_id, field_id, target_record_ids): self._swimlane.request( 'post', 'app/{0}/record/{1}/add-references'.format(app_id, record_id), json={ 'fieldId': field_id, 'targetRecordIds': target_reco...
447,844
Directly add a comment to a record without retrieving the app or record first Warnings: Does not perform any app, record, or field ID validation Args: app_id (str): Full App ID string record_id (str): Full parent Record ID string field_id (str): Full fie...
def add_comment(self, app_id, record_id, field_id, message): self._swimlane.request( 'post', 'app/{0}/record/{1}/{2}/comment'.format( app_id, record_id, field_id ), json={ 'message': message...
447,845
Report instance factory populating boilerplate raw data Args: app (App): Swimlane App instance report_name (str): Generated Report name Keyword Args **kwargs: Kwargs to pass to the Report class
def report_factory(app, report_name, **kwargs): # pylint: disable=protected-access created = pendulum.now().to_rfc3339_string() user_model = app._swimlane.user.as_usergroup_selection() return Report( app, { "$type": Report._type, "groupBys": [], ...
447,911
Adds a filter to report Notes: All filters are currently AND'ed together Args: field_name (str): Target field name to filter on operand (str): Operand used in comparison. See `swimlane.core.search` for options value: Target value used in comparision
def filter(self, field_name, operand, value): if operand not in self._FILTER_OPERANDS: raise ValueError('Operand must be one of {}'.format(', '.join(self._FILTER_OPERANDS))) # Use temp Record instance for target app to translate values into expected API format record_stub =...
447,914
Retrieve report by ID Args: report_id (str): Full report ID Returns: Report: Corresponding Report instance
def get(self, report_id): return Report( self._app, self._swimlane.request('get', "reports/{0}".format(report_id)).json() )
447,917
Download attachment Args: chunk_size (int): Byte-size of chunked download request stream Returns: BytesIO: Stream ready for reading containing the attachment file contents
def download(self, chunk_size=1024): stream = BytesIO() response = self._swimlane.request( 'get', 'attachment/download/{}'.format(self.file_id), stream=True ) for chunk in response.iter_content(chunk_size): stream.write(chunk) ...
447,924
Return a temporary Record instance to be used for field validation and value parsing Args: app (App): Target App to create a transient Record instance for fields (dict): Optional dict of fields and values to set on new Record instance before returning Returns: Record: Unsaved Record in...
def record_factory(app, fields=None): # pylint: disable=line-too-long record = Record(app, { '$type': Record._type, 'isNew': True, 'applicationId': app.id, 'comments': { '$type': 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collectio...
447,958
Return a usable cache lookup key for an already initialized resource Args: resource (APIResource|tuple): APIResource instance or 3-length tuple key returned from this function Raises: TypeError: If resource is not an APIResource instance or acceptable 3-length tuple cache key
def get_cache_index_key(resource): if isinstance(resource, APIResource): attr, attr_value = list(resource.get_cache_index_keys().items())[0] key = (type(resource), attr, attr_value) else: key = tuple(resource) if len(key) != 3: raise TypeError('Cache key must be tuple o...
447,970
Decorator for adapter methods to check cache for resource before normally sending requests to retrieve data Only works with single kwargs, almost always used with @one_of_keyword_only decorator Args: resource_type (type(APIResource)): Subclass of APIResource of cache to be checked when called
def check_cache(resource_type): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: adapter = args[0] key, val = list(kwargs.items())[0] except IndexError: logger.warning("Couldn't generate full ...
447,971
Returns a 2-tuple: 0: bool signifying whether the image was successfully pre-warmed 1: The url of the successfully created image OR the path on storage of the image that was not able to be successfully created. Arguments: `size_key_list`: A list of VersatileImageField size ke...
def _prewarm_versatileimagefield(size_key, versatileimagefieldfile): versatileimagefieldfile.create_on_demand = True try: url = get_url_from_image_key(versatileimagefieldfile, size_key) except Exception: success = False url_or_filepath = versatileimag...
448,547
Receive a PIL Image instance of a GIF and return 2-tuple. Args: * [0]: Original Image instance (passed to `image`) * [1]: Dict with a transparency key (to GIF transparency layer)
def preprocess_GIF(self, image, **kwargs): if 'transparency' in image.info: save_kwargs = {'transparency': image.info['transparency']} else: save_kwargs = {} return (image, save_kwargs)
448,575
Receive a PIL Image instance of a JPEG and returns 2-tuple. Args: * [0]: Image instance, converted to RGB * [1]: Dict with a quality key (mapped to the value of `QUAL` as defined by the `VERSATILEIMAGEFIELD_JPEG_RESIZE_QUALITY` setting)
def preprocess_JPEG(self, image, **kwargs): save_kwargs = { 'progressive': VERSATILEIMAGEFIELD_PROGRESSIVE_JPEG, 'quality': QUAL } if image.mode != 'RGB': image = image.convert('RGB') return (image, save_kwargs)
448,576
Save an image to self.storage at `save_path`. Arguments: `imagefile`: Raw image data, typically a BytesIO instance. `save_path`: The path within self.storage where the image should be saved. `file_ext`: The file extension of the image-to-be-saved. ...
def save_image(self, imagefile, save_path, file_ext, mime_type): file_to_save = InMemoryUploadedFile( imagefile, None, 'foo.%s' % file_ext, mime_type, imagefile.tell(), None ) file_to_save.seek(0) self.stora...
448,578
Return a URL to an image sized according to key. Arguments: * `key`: A string in the following format '[width-in-pixels]x[height-in-pixels]' Example: '400x400'
def __getitem__(self, key): try: width, height = [int(i) for i in key.split('x')] except (KeyError, ValueError): raise MalformedSizedImageKey( "%s keys must be in the following format: " "'`width`x`height`' where both `width` and `height` ...
448,583
Set values for authentication Params: db_alias: The database alias e.g. the default SF alias 'salesforce'. settings_dict: It is only important for the first connecting. It should be taken from django.conf.DATABASES['salesforce'], ...
def __init__(self, db_alias, settings_dict=None, _session=None): self.db_alias = db_alias self.dynamic = None self.settings_dict = settings_dict or connections[db_alias].settings_dict self._session = _session or requests.Session()
450,035
Prepare excetion params or only an exception message parameters: messages: list of strings, that will be separated by new line response: response from a request to SFDC REST API verbs: list of options about verbosity
def prepare_exception(obj, messages=None, response=None, verbs=None): # pylint:disable=too-many-branches verbs = set(verbs or []) known_options = ['method+url'] if messages is None: messages = [] if isinstance(messages, (text_type, str)): messages = [messages] assert isinsta...
450,073
This method will parse a string containing FortiOS config and will load it into the current :class:`~pyFG.forticonfig.FortiConfig` object. Args: - **output** (string) - A string containing a supported version of FortiOS config
def parse_config_output(self, output): regexp = re.compile('^(config |edit |set |end$|next$)(.*)') current_block = self if isinstance(output, py23_compat.string_types): output = output.splitlines() for line in output: if 'uuid' in line: ...
450,539
This method will execute the commands on the device without as if you were just connected to it (it will not enter into any vdom). This method is not recommended unless you are 100% sure of what you are doing. Args: * **command** (str) -- Command to execute. Returns: A...
def execute_command(self, command): logger.debug('Executing commands:\n %s' % command) err_msg = 'Something happened when executing some commands on device' chan = self.ssh.get_transport().open_session() chan.settimeout(5) chan.exec_command(command) error_cha...
450,543
This static method will help reading the result of the commit, command by command. Args: last_log(list): A list containing, line by line, the result of committing the changes. Returns: A list of tuples that went wrong. The tuple will contain (*status_code*, *command*)
def _parse_batch_lastlog(last_log): regexp = re.compile('(-?[0-9]\d*):\W+(.*)') wrong_commands = list() for line in last_log: result = regexp.match(line) if result is not None: status_code = result.group(1) command = result.group(...
450,548
This command will update the running config from the live device. Args: * reload_original_config: * If ``True`` the original config will be loaded with the running config before reloading the\ original config. * If ``False`` the original config will r...
def _reload_config(self, reload_original_config): # We don't want to reload the config under some circumstances if reload_original_config: self.original_config = self.running_config self.original_config.set_name('original') paths = self.running_config.get_paths(...
450,549
Set the API URL and language Args: api_url (str): API URL to use lang (str): Language of the API URL Raises: :py:func:`mediawiki.exceptions.MediaWikiAPIURLError`: if the \ url is not a valid MediaWiki site
def set_api_url(self, api_url="https://{lang}.wikipedia.org/w/api.php", lang="en"): old_api_url = self._api_url old_lang = self._lang self._lang = lang.lower() self._api_url = api_url.format(lang=self._lang) try: self._get_site_info() self.__suppo...
450,973
Request a random page title or list of random titles Args: pages (int): Number of random pages to return Returns: list or int: A list of random page titles or a random page \ title if pages = 1
def random(self, pages=1): if pages is None or pages < 1: raise ValueError("Number of pages must be greater than 0") query_params = {"list": "random", "rnnamespace": 0, "rnlimit": pages} request = self.wiki_request(query_params) titles = [page["title"] for page in ...
450,976
Search for similar titles Args: query (str): Page title results (int): Number of pages to return suggestion (bool): Use suggestion Returns: tuple or list: tuple (list results, suggestion) if \ suggest...
def search(self, query, results=10, suggestion=False): self._check_query(query, "Query must be specified") search_params = { "list": "search", "srprop": "", "srlimit": results, "srsearch": query, } if suggestion: sear...
450,977
Gather suggestions based on the provided title or None if no suggestions found Args: query (str): Page title Returns: String or None: Suggested page title or **None** if no \ suggestion found
def suggest(self, query): res, suggest = self.search(query, results=1, suggestion=True) try: title = suggest or res[0] except IndexError: # page doesn't exist title = None return title
450,978
Make a request to the MediaWiki API using the given search parameters Args: params (dict): Request parameters Returns: A parsed dict of the JSON response Note: Useful when wanting to query the MediaWiki site for some \ ...
def wiki_request(self, params): params["format"] = "json" if "action" not in params: params["action"] = "query" limit = self._rate_limit last_call = self._rate_limit_last_call if limit and last_call and last_call + self._min_wait > datetime.now(): ...
450,986
Parse all links within a section Args: section_title (str): Name of the section to pull Returns: list: List of (title, url) tuples Note: Returns **None** if section title is not found Note: Side effect is to...
def parse_section_links(self, section_title): soup = BeautifulSoup(self.html, "html.parser") headlines = soup.find_all("span", {"class": "mw-headline"}) tmp_soup = BeautifulSoup(section_title, "html.parser") tmp_sec_title = tmp_soup.get_text().lower() id_tag = None ...
451,011
Generate an LLVM module for a list of expressions Arguments: * See :meth:`arybo.lib.exprs_asm.asm_binary` for a description of the list of arguments Output: * An LLVM module with one function named "__arybo", containing the translated expression. See :meth:`arybo.lib.exprs_asm.asm_bin...
def asm_module(exprs, dst_reg, sym_to_reg, triple_or_target=None): if not llvmlite_available: raise RuntimeError("llvmlite module unavailable! can't assemble...") target = llvm_get_target(triple_or_target) M = ll.Module() fntype = ll.FunctionType(ll.VoidType(), []) func = ll.Function...
451,329
Convert a subset of Triton's AST into Arybo's representation Args: e: Triton AST use_esf: use ESFs when creating the final expression context: dictionnary that associates Triton expression ID to arybo expressions Returns: An :class:`arybo.lib.MBAVariable` object
def tritonast2arybo(e, use_exprs=True, use_esf=False, context=None): children_ = e.getChildren() children = (tritonast2arybo(c,use_exprs,use_esf,context) for c in children_) reversed_children = (tritonast2arybo(c,use_exprs,use_esf,context) for c in reversed(children_)) Ty = e.getType() if Ty ...
451,421
Translates a regular Scikit-Learn estimator or pipeline to a PMML pipeline. Parameters: ---------- obj: BaseEstimator The object. active_fields: list of strings, optional Feature names. If missing, "x1", "x2", .., "xn" are assumed. target_fields: list of strings, optional Label name(s). If missing, "y" is...
def make_pmml_pipeline(obj, active_fields = None, target_fields = None): steps = _filter_steps(_get_steps(obj)) pipeline = PMMLPipeline(steps) if active_fields is not None: pipeline.active_fields = numpy.asarray(active_fields) if target_fields is not None: pipeline.target_fields = numpy.asarray(target_fields)...
453,250
Translates a regular TPOT configuration to a PMML-compatible TPOT configuration. Parameters: ---------- obj: config The configuration dictionary. user_classpath: list of strings, optional The paths to JAR files that provide custom Transformer, Selector and/or Estimator converter classes. The JPMML-SkLearn c...
def make_tpot_pmml_config(config, user_classpath = []): tpot_keys = set(config.keys()) classes = _supported_classes(user_classpath) pmml_keys = (set(classes)).union(set([_strip_module(class_) for class_ in classes])) return { key : config[key] for key in (tpot_keys).intersection(pmml_keys)}
453,259
Add a media file to normalize Arguments: input_file {str} -- Path to input file output_file {str} -- Path to output file
def add_media_file(self, input_file, output_file): if not os.path.exists(input_file): raise FFmpegNormalizeError("file " + input_file + " does not exist") ext = os.path.splitext(output_file)[1][1:] if (self.audio_codec is None or 'pcm' in self.audio_codec) and ext in PCM_IN...
454,316
Initialize a media file for later normalization. Arguments: ffmpeg_normalize {FFmpegNormalize} -- reference to overall settings input_file {str} -- Path to input file Keyword Arguments: output_file {str} -- Path to output file (default: {None})
def __init__(self, ffmpeg_normalize, input_file, output_file=None): self.ffmpeg_normalize = ffmpeg_normalize self.skip = False self.input_file = input_file self.output_file = output_file self.streams = { 'audio': {}, 'video': {}, 'subt...
454,326
Set the main attributes and instantiate the writer if given. Args: msg(pandasdmx.model.Message): the SDMX message url(str): the URL, if any, that had been sent to the SDMX server headers(dict): http headers status_code(int): the status code returned by the serve...
def __init__(self, msg, url, headers, status_code, writer=None): self.msg = msg self.url = url self.http_headers = headers self.status_code = status_code self._init_writer(writer)
454,782
Resolve object to one of our internal collection types or generic built-in type. Args: arg: object to resolve
def resolve_type(arg): # type: (object) -> InternalType arg_type = type(arg) if arg_type == list: assert isinstance(arg, list) # this line helps mypy figure out types sample = arg[:min(4, len(arg))] tentative_type = TentativeType() for sample_item in sample: ...
454,817
Write collected information to file. Args: filename: absolute filename
def dump_stats(filename): # type: (str) -> None res = _dump_impl() f = open(filename, 'w') json.dump(res, f, indent=4) f.close()
454,827
Given some type comments, return a single inferred signature. Args: type_comments: Strings of form '(arg1, ... argN) -> ret' Returns: Tuple of (argument types and kinds, return type).
def infer_annotation(type_comments): # type: (List[str]) -> Tuple[List[Argument], AbstractType] assert type_comments args = {} # type: Dict[int, Set[Argument]] returns = set() for comment in type_comments: arg_types, return_type = parse_type_comment(comment) for i, arg_type in ...
454,843
Returns a bitmask in human readable form. This is a private function, used internally. Args: bits (int): The bitmask to be represented. table (Dict[Any,str]): A reverse lookup table. default (Any): A default return value when bits is 0. Returns: str: A printable version of the bit...
def _describe_bitmask( bits: int, table: Dict[Any, str], default: str = "0" ) -> str: result = [] for bit, name in table.items(): if bit & bits: result.append(name) if not result: return default return "|".join(result)
456,029
Capture the screen and save it as a png file. If path is None then the image will be placed in the current folder with the names: ``screenshot001.png, screenshot002.png, ...`` Args: path (Optional[Text]): The file path to save the screenshot.
def screenshot(path=None): if not _rootinitialized: raise TDLError('Initialize first with tdl.init') if isinstance(path, str): _lib.TCOD_sys_save_screenshot(_encodeString(path)) elif path is None: # save to screenshot001.png, screenshot002.png, ... filelist = _os.listdir('.') ...
456,067
Sets the colors to be used with the L{print_str} and draw_* methods. Values of None will only leave the current values unchanged. Args: fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) .. seealso:: :any:...
def set_colors(self, fg=None, bg=None): if fg is not None: self._fg = _format_color(fg, self._fg) if bg is not None: self._bg = _format_color(bg, self._bg)
456,073
This method mimics basic file-like behaviour. Because of this method you can replace sys.stdout or sys.stderr with a :any:`Console` or :any:`Window` instance. This is a convoluted process and behaviour seen now can be excepted to change on later versions. Args: str...
def write(self, string): # some 'basic' line buffer stuff. # there must be an easier way to do this. The textwrap module didn't # help much. x, y = self._normalizeCursor(*self._cursor) width, height = self.get_size() wrapper = _textwrap.TextWrapper(initial_inden...
456,075
Move the virtual cursor. Args: x (int): x-coordinate to place the cursor. y (int): y-coordinate to place the cursor. .. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`
def move(self, x, y): self._cursor = self._normalizePoint(x, y)
456,083
Scroll the contents of the console in the direction of x,y. Uncovered areas will be cleared to the default background color. Does not move the virutal cursor. Args: x (int): Distance to scroll along the x-axis. y (int): Distance to scroll along the y-axis. Retu...
def scroll(self, x, y): assert isinstance(x, _INTTYPES), "x must be an integer, got %s" % repr(x) assert isinstance(y, _INTTYPES), "y must be an integer, got %s" % repr(x) def getSlide(x, length): if x > 0: srcx = 0 length -= x ...
456,084
Return a list of (x, y) steps to reach the goal point, if possible. Args: start_x (int): Starting X position. start_y (int): Starting Y position. goal_x (int): Destination X position. goal_y (int): Destination Y position. Returns: List[Tuple[i...
def get_path( self, start_x: int, start_y: int, goal_x: int, goal_y: int ) -> List[Tuple[int, int]]: lib.TCOD_path_compute(self._path_c, start_x, start_y, goal_x, goal_y) path = [] x = ffi.new("int[2]") y = x + 1 while lib.TCOD_path_walk(self._path_c, x, y, F...
456,119
Return a random integer within the linear range: low <= n <= high. Args: low (int): The lower bound of the random range. high (int): The upper bound of the random range. Returns: int: A random integer.
def randint(self, low: int, high: int) -> int: return int(lib.TCOD_random_get_i(self.random_c, low, high))
456,128
Return a random floating number in the range: low <= n <= high. Args: low (float): The lower bound of the random range. high (float): The upper bound of the random range. Returns: float: A random float.
def uniform(self, low: float, high: float) -> float: return float(lib.TCOD_random_get_double(self.random_c, low, high))
456,129
Return a random number using Gaussian distribution. Args: mu (float): The median returned value. sigma (float): The standard deviation. Returns: float: A random float.
def guass(self, mu: float, sigma: float) -> float: return float( lib.TCOD_random_get_gaussian_double(self.random_c, mu, sigma) )
456,130
Return a random Gaussian number using the Box-Muller transform. Args: mu (float): The median returned value. sigma (float): The standard deviation. Returns: float: A random float.
def inverse_guass(self, mu: float, sigma: float) -> float: return float( lib.TCOD_random_get_gaussian_double_inv(self.random_c, mu, sigma) )
456,131
Return the noise value of a specific position. Example usage: value = noise.getPoint(x, y, z) Args: position (Tuple[float, ...]): The point to sample at. Returns: float: The noise value at position. This will be a floating point in the 0.0-1.0 range.
def get_point(self, *position): #array = self._array #for d, pos in enumerate(position): # array[d] = pos #array = self._cFloatArray(*position) array = _ffi.new(self._arrayType, position) if self._useOctaves: return (self._noiseFunc(self._noise, ar...
456,136
Return the noise value at the (x, y, z, w) point. Args: x (float): The position on the 1st axis. y (float): The position on the 2nd axis. z (float): The position on the 3rd axis. w (float): The position on the 4th axis.
def get_point( self, x: float = 0, y: float = 0, z: float = 0, w: float = 0 ) -> float: return float(lib.NoiseGetSample(self._tdl_noise_c, (x, y, z, w)))
456,147
Wait for an event. Args: timeout (Optional[int]): The time in seconds that this function will wait before giving up and returning None. With the default value of None, this will block forever. flush (bool): If True a call to :any:`tdl.flush` will be made before ...
def wait(timeout=None, flush=True): if timeout is not None: timeout = timeout + _time.clock() # timeout at this time while True: if _eventQueue: return _eventQueue.pop(0) if flush: # a full 'round' of events need to be processed before flushing _t...
456,158
Create a new BSP instance with the given rectangle. Args: x (int): Rectangle left coordinate. y (int): Rectangle top coordinate. w (int): Rectangle width. h (int): Rectangle height. Returns: BSP: A new BSP instance. .. deprecated:: 2.0 Call the :any:`BSP` cl...
def bsp_new_with_size(x: int, y: int, w: int, h: int) -> tcod.bsp.BSP: return Bsp(x, y, w, h)
456,198
Return the linear interpolation between two colors. ``a`` is the interpolation value, with 0 returing ``c1``, 1 returning ``c2``, and 0.5 returing a color halfway between both. Args: c1 (Union[Tuple[int, int, int], Sequence[int]]): The first color. At a=0. c2 (Union[Tuple[int,...
def color_lerp( c1: Tuple[int, int, int], c2: Tuple[int, int, int], a: float ) -> Color: return Color._new_from_cdata(lib.TCOD_color_lerp(c1, c2, a))
456,213
Set a color using: hue, saturation, and value parameters. Does not return a new Color. ``c`` is modified inplace. Args: c (Union[Color, List[Any]]): A Color instance, or a list of any kind. h (float): Hue, from 0 to 360. s (float): Saturation, from 0 to 1. v (float): Value, fr...
def color_set_hsv(c: Color, h: float, s: float, v: float) -> None: new_color = ffi.new("TCOD_color_t*") lib.TCOD_color_set_HSV(new_color, h, s, v) c[:] = new_color.r, new_color.g, new_color.b
456,214
Return the (hue, saturation, value) of a color. Args: c (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. Returns: Tuple[float, float, float]: A tuple with (hue, saturation, value) values, from 0 to 1.
def color_get_hsv(c: Tuple[int, int, int]) -> Tuple[float, float, float]: hsv = ffi.new("float [3]") lib.TCOD_color_get_HSV(c, hsv, hsv + 1, hsv + 2) return hsv[0], hsv[1], hsv[2]
456,215
Scale a color's saturation and value. Does not return a new Color. ``c`` is modified inplace. Args: c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list. scoef (float): Saturation multiplier, from 0 to 1. Use 1 to keep current saturation. vcoef (f...
def color_scale_HSV(c: Color, scoef: float, vcoef: float) -> None: color_p = ffi.new("TCOD_color_t*") color_p.r, color_p.g, color_p.b = c.r, c.g, c.b lib.TCOD_color_scale_HSV(color_p, scoef, vcoef) c[:] = color_p.r, color_p.g, color_p.b
456,216
Return the width of a console. Args: con (Console): Any Console instance. Returns: int: The width of a Console. .. deprecated:: 2.0 Use `Console.width` instead.
def console_get_width(con: tcod.console.Console) -> int: return int(lib.TCOD_console_get_width(_console(con)))
456,220
Return the height of a console. Args: con (Console): Any Console instance. Returns: int: The height of a Console. .. deprecated:: 2.0 Use `Console.height` instead.
def console_get_height(con: tcod.console.Console) -> int: return int(lib.TCOD_console_get_height(_console(con)))
456,221
Remap a string of codes to a contiguous set of tiles. Args: s (AnyStr): A string of character codes to map to new values. The null character `'\\x00'` will prematurely end this function. fontCharX (int): The starting X tile coordinate on the loaded tileset. ...
def console_map_string_to_font(s: str, fontCharX: int, fontCharY: int) -> None: lib.TCOD_console_map_string_to_font_utf(_unicode(s), fontCharX, fontCharY)
456,224
Change the default background color for a console. Args: con (Console): Any Console instance. col (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. .. deprecated:: 8.5 Use :any:`Console.default_bg` instead.
def console_set_default_background( con: tcod.console.Console, col: Tuple[int, int, int] ) -> None: lib.TCOD_console_set_default_background(_console(con), col)
456,226
Change the default foreground color for a console. Args: con (Console): Any Console instance. col (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. .. deprecated:: 8.5 Use :any:`Console.default_fg` instead.
def console_set_default_foreground( con: tcod.console.Console, col: Tuple[int, int, int] ) -> None: lib.TCOD_console_set_default_foreground(_console(con), col)
456,227
Draw the character c at x,y using the default colors and a blend mode. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from the top. c (Union[int, AnyStr]): Character to draw, can be an integer or string. ...
def console_put_char( con: tcod.console.Console, x: int, y: int, c: Union[int, str], flag: int = BKGND_DEFAULT, ) -> None: lib.TCOD_console_put_char(_console(con), x, y, _int(c), flag)
456,228
Change the background color of x,y to col using a blend mode. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from the top. col (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Co...
def console_set_char_background( con: tcod.console.Console, x: int, y: int, col: Tuple[int, int, int], flag: int = BKGND_SET, ) -> None: lib.TCOD_console_set_char_background(_console(con), x, y, col, flag)
456,230
Change the foreground color of x,y to col. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from the top. col (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. ...
def console_set_char_foreground( con: tcod.console.Console, x: int, y: int, col: Tuple[int, int, int] ) -> None: lib.TCOD_console_set_char_foreground(_console(con), x, y, col)
456,231
Change the character at x,y to c, keeping the current colors. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from the top. c (Union[int, AnyStr]): Character to draw, can be an integer or string. .. deprecate...
def console_set_char( con: tcod.console.Console, x: int, y: int, c: Union[int, str] ) -> None: lib.TCOD_console_set_char(_console(con), x, y, _int(c))
456,232
Change the default blend mode for this console. Args: con (Console): Any Console instance. flag (int): Blend mode to use by default. .. deprecated:: 8.5 Set :any:`Console.default_bg_blend` instead.
def console_set_background_flag(con: tcod.console.Console, flag: int) -> None: lib.TCOD_console_set_background_flag(_console(con), flag)
456,233
Return this consoles current blend mode. Args: con (Console): Any Console instance. .. deprecated:: 8.5 Check :any:`Console.default_bg_blend` instead.
def console_get_background_flag(con: tcod.console.Console) -> int: return int(lib.TCOD_console_get_background_flag(_console(con)))
456,234
Change this consoles current alignment mode. * tcod.LEFT * tcod.CENTER * tcod.RIGHT Args: con (Console): Any Console instance. alignment (int): .. deprecated:: 8.5 Set :any:`Console.default_alignment` instead.
def console_set_alignment(con: tcod.console.Console, alignment: int) -> None: lib.TCOD_console_set_alignment(_console(con), alignment)
456,235
Return this consoles current alignment mode. Args: con (Console): Any Console instance. .. deprecated:: 8.5 Check :any:`Console.default_alignment` instead.
def console_get_alignment(con: tcod.console.Console) -> int: return int(lib.TCOD_console_get_alignment(_console(con)))
456,236
Print a color formatted string on a console. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from the top. fmt (AnyStr): A unicode or bytes string optionaly using color codes. .. deprecated:: 8.5 Use ...
def console_print(con: tcod.console.Console, x: int, y: int, fmt: str) -> None: lib.TCOD_console_printf(_console(con), x, y, _fmt(fmt))
456,237
Print a string on a console using a blend mode and alignment mode. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from the top. .. deprecated:: 8.5 Use :any:`Console.print_` instead.
def console_print_ex( con: tcod.console.Console, x: int, y: int, flag: int, alignment: int, fmt: str, ) -> None: lib.TCOD_console_printf_ex(_console(con), x, y, flag, alignment, _fmt(fmt))
456,238
Configure :any:`color controls`. Args: con (int): :any:`Color control` constant to modify. fore (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. back (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color in...
def console_set_color_control( con: int, fore: Tuple[int, int, int], back: Tuple[int, int, int] ) -> None: lib.TCOD_console_set_color_control(con, fore, back)
456,246
Block until the user presses a key, then returns a new Key. Args: flush bool: If True then the event queue is cleared before waiting for the next event. Returns: Key: A new Key instance. .. deprecated:: 9.3 Use the :any:`tcod.event.wait` function to wait for ev...
def console_wait_for_keypress(flush: bool) -> Key: key = Key() lib.TCOD_console_wait_for_keypress_wrapper(key.key_p, flush) return key
456,253
Return a new console object from a filename. The file format is automactially determined. This can load REXPaint `.xp`, ASCII Paint `.apf`, or Non-delimited ASCII `.asc` files. Args: filename (Text): The path to the file, as a string. Returns: A new :any`Console` instance.
def console_from_file(filename: str) -> tcod.console.Console: return tcod.console.Console._from_cdata( lib.TCOD_console_from_file(filename.encode("utf-8")) )
456,256