docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Perform a Yelp Neighborhood API Search based on a location specifier. Args: location - textual location specifier of form: "address, city, state or zip, optional country" cc - ISO 3166-1 alpha-2 country code. (Optional)
def by_location(self, location, cc=None): header, content = self._http_request(self.BASE_URL, location=location, cc=cc) return json.loads(content)
882,784
Initialize Profile object with Riminder client. Args: client: Riminder client instance <Riminder object> Returns Profile instance object.
def __init__(self, client): self.client = client self.stage = ProfileStage(self.client) self.document = ProfileDocument(self.client) self.parsing = ProfileParsing(self.client) self.scoring = ProfileScoring(self.client) self.rating = ProfileRating(self.client) ...
883,509
Retrieve the profile information associated with profile id. Args: source_id: <string> source id profile_id: <string> profile id Returns profile information
def get(self, source_id=None, profile_id=None, profile_reference=None): query_params = {} query_params["source_id"] = _validate_source_id(source_id) if profile_id: query_params["profile_id"] = _validate_profile_id(profile_id) if profile_reference: query_p...
883,513
Retrieve the interpretability information. Args: source_id: <string> source id profile_id: <string> profile id filter_id: <string> ...
def get(self, source_id=None, profile_id=None, profile_reference=None, filter_id=None, filter_reference=None): query_params = {} query_params["source_id"] = _validate_source_id(source_id) if profile_id: query_params["profile_id"] = _validate_profile_id(profile_id) if...
883,515
md5sums a file, returning the hex digest Parameters: - f filename string
def md5sum(self, f): m = hashlib.md5() fh = open(f, 'r') while 1: chunk = fh.read(BUF_SIZE) if not chunk: break m.update(chunk) fh.close() return m.hexdigest()
883,560
streaming item iterator with low overhead duplicate file detection Parameters: - compare compare function between files (defaults to md5sum)
def iterdupes(self, compare=None, filt=None): if not compare: compare = self.md5sum seen_siz = {} ## store size -> first seen filename seen_sum = {} ## store chksum -> first seen filename size_func = lambda x: os.stat(x).st_size for (fsize, f) in self.iteri...
883,562
Returns sampled action fluents for the current `state` and `timestep`. Args: state (Sequence[tf.Tensor]): The current state fluents. timestep (tf.Tensor): The current timestep. Returns: Sequence[tf.Tensor]: A tuple of action fluents.
def __call__(self, state: Sequence[tf.Tensor], timestep: tf.Tensor) -> Sequence[tf.Tensor]: action, _, _ = self._sample_actions(state) return action
883,649
Returns sampled action fluents and tensors related to the sampling. Args: state (Sequence[tf.Tensor]): A list of state fluents. Returns: Tuple[Sequence[tf.Tensor], tf.Tensor, tf.Tensor]: A tuple with action fluents, an integer tensor for the number of samples, and ...
def _sample_actions(self, state: Sequence[tf.Tensor]) -> Tuple[Sequence[tf.Tensor], tf.Tensor, tf.Tensor]: default = self.compiler.compile_default_action(self.batch_size) bound_constraints = self.compiler.compile_action_bound_constraints(state) action = self._sample_action(b...
883,650
Returns the dimensions of an image tensor. Args: images: 4-D Tensor of shape [batch, height, width, channels] dynamic_shape: Whether the input image has undertermined shape. If set to `True`, shape information will be retrieved at run time. Default to `False`. Returns: list of integers [bat...
def _ImageDimensions(images, dynamic_shape=False): # A simple abstraction to provide names for each dimension. This abstraction # should make it simpler to switch dimensions in the future (e.g. if we ever # want to switch height and width.) if dynamic_shape: return array_ops.unpack(array_ops.shape(images...
884,024
Assert that we are working with properly shaped image. Args: image: 3-D Tensor of shape [height, width, channels] require_static: If `True`, requires that all dimensions of `image` are known and non-zero. Raises: ValueError: if image.shape is not a [3] vector.
def _Check3DImage(image, require_static=True): try: image_shape = image.get_shape().with_rank(3) except ValueError: raise ValueError('\'image\' must be three-dimensional.') if require_static and not image_shape.is_fully_defined(): raise ValueError('\'image\' must be fully defined.') if any(x == 0...
884,025
Load configuration for the service Args: config_file: Configuration file path
def load_config(self): logger.debug('loading config file: %s', self.config_file) if os.path.exists(self.config_file): with open(self.config_file) as file_handle: return json.load(file_handle) else: logger.error('configuration file is required for ...
884,042
method to query a URL with the given parameters Parameters: url -> URL to query params -> dictionary with parameter values Returns: HTTP response code, headers If an exception occurred, headers fields are None
def _query(self, url=None, params=""): if url is None: raise NoUrlError("No URL was provided.") # return values headers = {'location': None, 'title': None} headerdata = urllib.urlencode(params) try: request = urllib2.Request(url, headerdata) ...
884,468
Format an error message for missing positional arguments. Args: name: The function name. sig: The function's signature. num_params: The number of function parameters. Returns: str: A formatted error message.
def _format_parameter_error_message(name: str, sig: Signature, num_params: int) -> str: if num_params == 0: plural = 's' missing = 2 arguments = "'slack' and 'event'" else: plural = '' missing = 1 arguments = "'event'" ...
885,789
Propagate 'debug' wrapper into inner function calls if needed. Args: node (ast.AST): node statement to surround.
def visit_Call(self, node): if self.depth == 0: return node if self.ignore_exceptions is None: ignore_exceptions = ast.Name("None", ast.Load()) else: ignore_exceptions = ast.List(self.ignore_exceptions, ast.Load()) catch_exception_type = se...
886,154
Surround node statement with a try/except block to catch errors. This method is called for every node of the parsed code, and only changes statement lines. Args: node (ast.AST): node statement to surround.
def generic_visit(self, node): if (isinstance(node, ast.stmt) and not isinstance(node, ast.FunctionDef)): new_node = self.wrap_with_try(node) # handling try except statement if isinstance(node, self.ast_try_except): self.try_except_h...
886,155
Logs a message to the console, with optional level paramater Args: - msg (str): message to send to console - level (int): log level; 0 for info, 1 for error (default = 0)
def log(msg, level=0): red = '\033[91m' endc = '\033[0m' # configure the logging module cfg = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'stdout': { 'format': '[%(levelname)s]: %(asctime)s - %(message)s', ...
886,969
Connect to an assembly that points to the assembly specified with the url. Args: - url (str): The url of the onshape item
def __init__(self, url): # Accept either a url OR uri if isinstance(url, Uri): self.uri = url else: self.uri = Uri(url)
886,973
Insert a part into this assembly. Args: - part (onshapepy.part.Part) A Part instance that will be inserted. Returns: - requests.Response: Onshape response data
def insert(self, part): params = {k: str(v) for k,v in part.params.items()} res=c.create_assembly_instance(self.uri.as_dict(), part.uri.as_dict(), params) return res
886,974
Creates a new instance of the Service. Args: executable_path: Path to the AndroidDriver. port: Port the service is running on. env: Environment variables. service_args: List of args to pass to the androiddriver service.
def __init__(self, executable_path: _PATH = 'default', port: Union[int, str] = 5037, env: Dict = None, service_args: Union[list, tuple] = None) -> None: self._service_args = service_args or [] super(Service, self).__init__(executable_path, port=port, env=env)
886,999
Check whether the given function is a lambda function. .. testsetup:: from proso.func import is_lambda .. testcode:: def not_lambda_fun(): return 1 lambda_fun = lambda: 1 print( is_lambda(not_lambda_fun), is_lambda(lambda_fun) ) ...
def is_lambda(fun): return isinstance(fun, type(LAMBDA)) and fun.__name__ == LAMBDA.__name__
887,074
Init a sonic visualiser environment structure based on the attributes of the main audio file Args: samplerate(int): media sample rate (Hz) nframes(int): number of samples wavpath(str): Full path to the wav file used in the current environment
def __init__(self, samplerate, nframes, wavpath): imp = minidom.getDOMImplementation() dt = imp.createDocumentType('sonic-visualiser', None, None) self.doc = doc = imp.createDocument(None,'sv', dt) root = doc.documentElement self.__dname = dict() self.data = roo...
887,331
Init a sonic visualiser environment structure based the analysis of the main audio file. The audio file have to be encoded in wave Args: wavpath(str): the full path to the wavfile
def init_from_wave_file(wavpath): try: samplerate, data = SW.read(wavpath) nframes = data.shape[0] except: # scipy cannot handle 24 bit wav files # and wave cannot handle 32 bit wav files try: w = wave.open(wavpath) ...
887,332
add a continous annotation layer Args: x (float iterable): temporal indices of the dataset y (float iterable): values of the dataset Kwargs: view (<DOM Element: view>): environment view used to display the spectrogram, if set to None, a new view is created Return...
def add_continuous_annotations(self, x, y, colourName='Purple', colour='#c832ff', name='', view=None, vscale=None, presentationName=None): model = self.data.appendChild(self.doc.createElement('model')) imodel = self.nbdata for atname, atval in [('id', imodel + 1), ...
887,335
add a labelled interval annotation layer Args: temp_idx (float iterable): The temporal indices of invervals durations (float iterable): intervals durations labels (string iterable): interval labels values (int iterable): interval numeric values, if set to None, values ar...
def add_interval_annotations(self, temp_idx, durations, labels, values=None, colourName='Purple', colour='#c832ff', name='', view=None, presentationName = None): model = self.data.appendChild(self.doc.createElement('model')) imodel = self.nbdata for atname, atval in [('id', imodel + 1)...
887,336
Save the environment of a sv file to be used with soniv visualiser Args: outfname(str): full path to the file storing the environment
def save(self, outfname): f = BZ2File(outfname, 'w') self.doc.writexml(f, addindent=' ', newl='\n') f.close()
887,337
Provides the same functionality as .. py:method:: ItemManager.filter_all_reachable_leaves(), but for more filters in the same time. Args: identifier_filters: list of identifier filters language (str): language used for further filtering (some objects for differen...
def filter_all_reachable_leaves_many(self, identifier_filters, language, forbidden_identifiers=None): for i, identifier_filter in enumerate(identifier_filters): if len(identifier_filter) == 1 and not isinstance(identifier_filter[0], list): identifier_filters[i] = [identifier...
887,461
Get a subgraph of items reachable from the given set of items through the 'child' relation. Args: item_ids (list): items which are taken as roots for the reachability language (str): if specified, filter out items which are not available in the given language ...
def get_children_graph(self, item_ids=None, language=None, forbidden_item_ids=None): if forbidden_item_ids is None: forbidden_item_ids = set() def _children(item_ids): if item_ids is None: items = Item.objects.filter(active=True).prefetch_related('childr...
887,463
Get a subgraph of items reachable from the given set of items through the 'parent' relation. Args: item_ids (list): items which are taken as roots for the reachability language (str): if specified, filter out items which are not available in the given language ...
def get_parents_graph(self, item_ids, language=None): def _parents(item_ids): if item_ids is None: items = Item.objects.filter(active=True).prefetch_related('parents') else: item_ids = [ii for iis in item_ids.values() for ii in iis] ...
887,465
Get a subgraph of items reachable from the given set of items through any relation. Args: item_ids (list): items which are taken as roots for the reachability language (str): if specified, filter out items which are not available in the given language Re...
def get_graph(self, item_ids, language=None): def _related(item_ids): if item_ids is None: items = Item.objects.filter(active=True).prefetch_related('parents', 'children') else: item_ids = [ii for iis in item_ids.values() for ii in iis] ...
887,466
Translate a list of item ids to JSON objects which reference them. Args: item_ids (list[int]): item ids language (str): language used for further filtering (some objects for different languages share the same item) is_nested (function): mapping from item ids ...
def translate_item_ids(self, item_ids, language, is_nested=None): if is_nested is None: def is_nested_fun(x): return True elif isinstance(is_nested, bool): def is_nested_fun(x): return is_nested else: is_nested_fun = is...
887,470
Get mapping of items to their reachable leaves. Leaves having inactive relations to other items are omitted. Args: item_ids (list): items which are taken as roots for the reachability language (str): if specified, filter out items which are not available in the g...
def get_leaves(self, item_ids=None, language=None, forbidden_item_ids=None): forbidden_item_ids = set() if forbidden_item_ids is None else set(forbidden_item_ids) children = self.get_children_graph(item_ids, language=language, forbidden_item_ids=forbidden_item_ids) counts = self.get_chi...
887,471
Get all leaves reachable from the given set of items. Leaves having inactive relations to other items are omitted. Args: item_ids (list): items which are taken as roots for the reachability language (str): if specified, filter out items which are not available in...
def get_all_leaves(self, item_ids=None, language=None, forbidden_item_ids=None): return sorted(set(flatten(self.get_leaves(item_ids, language=language, forbidden_item_ids=forbidden_item_ids).values())))
887,472
Get all items with outcoming edges from the given subgraph, drop all their parent relations, and then add parents according to the given subgraph. Args: parent_subgraph (dict): item id -> list of parents(item ids) invisible_edges (list|set): set of (from, to) tuples spec...
def override_parent_subgraph(self, parent_subgraph, invisible_edges=None): with transaction.atomic(): if invisible_edges is None: invisible_edges = set() children = list(parent_subgraph.keys()) all_old_relations = dict(proso.list.group_by( ...
887,474
Generate a basic image using the auto-image endpoint of weeb.sh. This function is a coroutine. Parameters: imgtype: str - type of the generation to create, possible types are awooo, eyes, or won. face: str - only used with awooo type, defines color of face hair: str...
async def generate_image(self, imgtype, face=None, hair=None): if not isinstance(imgtype, str): raise TypeError("type of 'imgtype' must be str.") if face and not isinstance(face, str): raise TypeError("type of 'face' must be str.") if hair and not isinstance(hair...
887,497
Generate a discord status icon below the image provided. This function is a coroutine. Parameters: status: str - a discord status, must be online, idle, dnd, or streaming avatar: str - http/s url pointing to an avatar, has to have proper headers and be a direct link to an image...
async def generate_status(self, status, avatar=None): if not isinstance(status, str): raise TypeError("type of 'status' must be str.") if avatar and not isinstance(avatar, str): raise TypeError("type of 'avatar' must be str.") url = f'https://api.weeb.sh/auto-ima...
887,498
Generate a waifu insult image. This function is a coroutine. Parameters: avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image Return Type: image data
async def generate_waifu_insult(self, avatar): if not isinstance(avatar, str): raise TypeError("type of 'avatar' must be str.") async with aiohttp.ClientSession() as session: async with session.post("https://api.weeb.sh/auto-image/waifu-insult", headers=self.__headers, d...
887,499
Generate a license. This function is a coroutine. Parameters: title: str - title of the license avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image badges: list - list of 1-3 direct image urls. Same requirements...
async def generate_license(self, title, avatar, badges=None, widgets=None): if not isinstance(title, str): raise TypeError("type of 'title' must be str.") if not isinstance(avatar, str): raise TypeError("type of 'avatar' must be str.") if badges and not isinstanc...
887,500
Generate a love ship. This function is a coroutine. Parameters: target_one: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image, image will be on the left side. target_two: str - http/s url pointing to an image, has to have proper ...
async def generate_love_ship(self, target_one, target_two): if not isinstance(target_one, str): raise TypeError("type of 'target_one' must be str.") if not isinstance(target_two, str): raise TypeError("type of 'target_two' must be str.") data = {"targetOne": targ...
887,501
Sync a local build from $ANDROID_PRODUCT_OUT to the device (default all). Args: option: 'system', 'vendor', 'oem', 'data', 'all'
def sync(self, option: str = 'all') -> None: if option in ['system', 'vendor', 'oem', 'data', 'all']: self._execute('-s', self.device_sn, 'sync', option) else: raise ValueError(f'There is no option named: {option!r}.')
887,788
List but don't copy. Args: option: 'system', 'vendor', 'oem', 'data', 'all'
def sync_l(self, option: str = 'all') -> None: if option in ['system', 'vendor', 'oem', 'data', 'all']: self._execute('-s', self.device_sn, 'sync', '-l', option) else: raise ValueError('There is no option named: {!r}.'.format(option))
887,789
Push package to the device and install it. Args: option: -l: forward lock application -r: replace existing application -t: allow test packages -s: install application on sdcard -d: allow version code downgrade (debuggab...
def install(self, package: str, option: str = '-r') -> None: if not os.path.isfile(package): raise FileNotFoundError(f'{package!r} does not exist.') for i in option: if i not in '-lrtsdg': raise ValueError(f'There is no option named: {option!r}.') ...
887,790
Trim memory. Args: level: HIDDEN | RUNNING_MODERATE | BACKGROUNDRUNNING_LOW | \ MODERATE | RUNNING_CRITICAL | COMPLETE
def app_trim_memory(self, pid: int or str, level: str = 'RUNNING_LOW') -> None: _, error = self._execute('-s', self.device_sn, 'shell', 'am', 'send-trim-memory', str(pid), level) if error and error.startswith('Error'): raise ApplicationsException(err...
887,802
Recording the display of devices running Android 4.4 (API level 19) and higher. Args: bit_rate:You can increase the bit rate to improve video quality, but doing so results in larger movie files. time_limit: Sets the maximum recording time, in seconds, and the maximum value is 180 (3 min...
def screenrecord(self, bit_rate: int = 5000000, time_limit: int = 180, filename: _PATH = '/sdcard/demo.mp4') -> None: self._execute('-s', self.device_sn, 'shell', 'screenrecord', '--bit-rate', str(bit_rate), '--time-limit', str(time_limit), filename)
887,806
Recording the display of devices running Android 4.4 (API level 19) and higher. Then copy it to your computer. Args: bit_rate:You can increase the bit rate to improve video quality, but doing so results in larger movie files. time_limit: Sets the maximum recording time, in seconds, and ...
def pull_screenrecord(self, bit_rate: int = 5000000, time_limit: int = 180, remote: _PATH = '/sdcard/demo.mp4', local: _PATH = 'demo.mp4') -> None: self.screenrecord(bit_rate, time_limit, filename=remote) self.pull(remote, local)
887,807
Finds an element by id. Args: id_: The id of the element to be found. update: If the interface has changed, this option should be True. Returns: The element if it was found. Raises: NoSuchElementException - If the element wasn't found. ...
def find_element_by_id(self, id_, update=False) -> Elements: return self.find_element(by=By.ID, value=id_, update=update)
887,816
Finds multiple elements by id. Args: id_: The id of the elements to be found. update: If the interface has changed, this option should be True. Returns: A list with elements if any was found. An empty list if not. Raises: NoSuchElementException ...
def find_elements_by_id(self, id_, update=False) -> Elements: return self.find_elements(by=By.ID, value=id_, update=update)
887,817
Finds an element by name. Args: name: The name of the element to be found. update: If the interface has changed, this option should be True. Returns: The element if it was found. Raises: NoSuchElementException - If the element wasn't found. ...
def find_element_by_name(self, name, update=False) -> Elements: return self.find_element(by=By.NAME, value=name, update=update)
887,818
Finds multiple elements by name. Args: name: The name of the elements to be found. update: If the interface has changed, this option should be True. Returns: A list with elements if any was found. An empty list if not. Raises: NoSuchElementExcep...
def find_elements_by_name(self, name, update=False) -> Elements: return self.find_elements(by=By.NAME, value=name, update=update)
887,819
Finds an element by class. Args: class_: The class of the element to be found. update: If the interface has changed, this option should be True. Returns: The element if it was found. Raises: NoSuchElementException - If the element wasn't found. ...
def find_element_by_class(self, class_, update=False) -> Elements: return self.find_element(by=By.CLASS, value=class_, update=update)
887,820
Finds multiple elements by class. Args: class_: The class of the elements to be found. update: If the interface has changed, this option should be True. Returns: A list with elements if any was found. An empty list if not. Raises: NoSuchElementE...
def find_elements_by_class(self, class_, update=False) -> Elements: return self.find_elements(by=By.CLASS, value=class_, update=update)
887,821
Creates a new instance of the Commands. Args: executable_path: Path to the AndroidDriver. On the Windows platform, the best choice is default.
def __init__(self, executable: _PATH = 'default') -> None: _default_path = os.path.join( os.path.dirname(__file__), 'executable', 'adb.exe') if executable == 'default': self.path = _default_path elif executable.endswith('adb.exe'): if not os.path.is...
887,992
Enrich the given list of objects, so they have URL. Args: request (django.http.request.HttpRequest): request which is currently processed json_list (list): list of dicts (JSON objects to be enriched) url_name (str|fun): pattern to create a url name taking object_type ignore_get (lis...
def url(request, json_list, nested, url_name='show_{}', ignore_get=None): if not ignore_get: ignore_get = [] if isinstance(url_name, str): url_string = str(url_name) url_name = lambda x: url_string.format(x) urls = cache.get('proso_urls') if urls is None: urls = {} ...
888,147
Print translate result in a better format Args: data(str): result
def print_res(data): print('===================================') main_part = data['data'] print(main_part['word_name']) symbols = main_part['symbols'][0] print("美式音标:[" + symbols['ph_am'] + "]") print("英式音标:[" + symbols['ph_en'] + "]") print('-----------------------------------') p...
888,169
Generate and set identifier of concept before saving object to DB Args: sender (class): should be Concept instance (Concept): saving concept
def generate_identifier(sender, instance, **kwargs): identifier = Concept.create_identifier(instance.query) qs = Concept.objects.filter(identifier=identifier, lang=instance.lang) if instance.pk: qs = qs.exclude(pk=instance.pk) if qs.count() > 0: raise ValueError("Concept identifier ...
888,481
Get mapping of concepts to items belonging to concept. Args: concepts (list of Concept): Defaults to None meaning all concepts lang (str): language of concepts, if None use language of concepts Returns: dict: concept (int) -> list of item ids (int)
def get_concept_item_mapping(self, concepts=None, lang=None): if concepts is None: concepts = self.filter(active=True) if lang is not None: concepts = concepts.filter(lang=lang) if lang is None: languages = set([concept.lang for concept in con...
888,483
Get mapping of items_ids to concepts containing these items Args: lang (str): language of concepts Returns: dict: item (int) -> set of concepts (int)
def get_item_concept_mapping(self, lang): concepts = self.filter(active=True, lang=lang) return group_keys_by_value_lists(Concept.objects.get_concept_item_mapping(concepts, lang))
888,484
Recalculated given concepts for given users Args: concepts (dict): user id (int -> set of concepts to recalculate) lang(Optional[str]): language used to get items in all concepts (cached). Defaults to None, in that case are get items only in used concepts
def recalculate_concepts(self, concepts, lang=None): if len(concepts) == 0: return if lang is None: items = Concept.objects.get_concept_item_mapping(concepts=Concept.objects.filter(pk__in=set(flatten(concepts.values())))) else: items = Concept.object...
888,489
Instantiates an instance of the Onshape class. Args: - stack (str): Base URL - creds (str): Credentials dict
def __init__(self, stack, creds, logging): self._url = stack try: self._access_key = creds['access_key'].encode('utf-8') self._secret_key = creds['secret_key'].encode('utf-8') except TypeError as e: raise UserWarning("Specify a correct access key and...
888,643
Create the request signature to authenticate Args: - method (str): HTTP method - date (str): HTTP date header string - nonce (str): Cryptographic nonce - path (str): URL pathname - query (dict, default={}): URL query string in key-value pairs ...
def _make_auth(self, method, date, nonce, path, query={}, ctype='application/json'): query = urlencode(query) hmac_str = (method + '\n' + nonce + '\n' + date + '\n' + ctype + '\n' + path + '\n' + query + '\n').lower().encode('utf-8') signature = base64.b64encode(h...
888,645
Creates a headers object to sign the request Args: - method (str): HTTP method - path (str): Request path, e.g. /api/documents. No query string - query (dict, default={}): Query string in key-value format - headers (dict, default={}): Other headers to pass in ...
def _make_headers(self, method, path, query={}, headers={}): date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT') nonce = self._make_nonce() ctype = headers.get('Content-Type') if headers.get('Content-Type') else 'application/json' auth = self._make_auth(met...
888,646
Find an elemnent in the document with the given name - could be a PartStudio, Assembly or blob. Args: name: str the name of the element. Returns: - onshapepy.uri of the element
def find_element(self, name, type=ElementType.ANY): for e in self.e_list: # if a type is specified and this isn't it, move to the next loop. if type.value and not e['elementType'] == type: continue if e["name"] == name: uri = self.uri...
889,106
Take the given value and start enrichment by object_type. The va Args: request (django.http.request.HttpRequest): request which is currently processed value (dict|list|django.db.models.Model): in case of django.db.models.Model object (or list of these objects), to_json metho...
def enrich_json_objects_by_object_type(request, value): time_start_globally = time() if isinstance(value, list): json = [x.to_json() if hasattr(x, "to_json") else x for x in value] else: if isinstance(value, dict): json = value else: json = value.to_json(...
889,293
Instantiates a new Onshape client. Attributes: - conf: the configuration that generated this client. This is read-only and for testing purposes. Args: - configuration (dict, optional): a dictionary of configuration options. Default behavior is to load this from a YAML file that...
def __init__(self, conf=None, conf_file=".onshapepy"): default_conf = { 'stack': 'https://cad.onshape.com', 'logging': False, 'creds': None } try: user_conf = yaml.load(Path.home().joinpath(conf_file)) default_conf.update(use...
889,446
Create a new document. Args: - name (str, default='Test Document'): The doc name - owner_type (int, default=0): 0 for user, 1 for company, 2 for team - public (bool, default=False): Whether or not to make doc public Returns: - requests.Response: Onshape ...
def create_document(self, name='Test Document', owner_type=0, public=True): payload = { 'name': name, 'ownerType': owner_type, 'isPublic': public } return self._api.request('post', '/api/documents', body=payload)
889,447
Renames the specified document. Args: - did (str): Document ID - name (str): New document name Returns: - requests.Response: Onshape response data
def rename_document(self, did, name): payload = { 'name': name } return self._api.request('post', '/api/documents/' + did, body=payload)
889,448
Copy the current workspace. Args: - uri (dict): the uri of the workspace being copied. Needs to have a did and wid key. - new_name (str): the new name of the copied workspace. Returns: - requests.Response: Onshape response data
def copy_workspace(self, uri, new_name): payload = { 'isPublic': True, 'newName': new_name } return self._api.request('post', '/api/documents/' + uri['did'] + '/workspaces/' + uri['wvm'] + '/copy', body=payload)
889,449
Create a workspace in the specified document. Args: - did (str): the document id of where to create the new workspace - name (str): the new name of the copied workspace. - version_id (str): the ID of the version to be copied into a new workspace Returns: ...
def create_workspace(self, did, name, version_id=None): payload = { 'isPublic': True, 'name': name, } if version_id: payload['versionId'] = version_id return self._api.request('post', '/api/documents/d/' + did + '/workspaces', body=payload)
889,450
Creates a new assembly element in the specified document / workspace. Args: - did (str): Document ID - wid (str): Workspace ID - name (str, default='My Assembly') Returns: - requests.Response: Onshape response data
def create_assembly(self, did, wid, name='My Assembly'): payload = { 'name': name } return self._api.request('post', '/api/assemblies/d/' + did + '/w/' + wid, body=payload)
889,451
Gets the feature list for specified document / workspace / part studio. Args: - did (str): Document ID - wid (str): Workspace ID - eid (str): Element ID Returns: - requests.Response: Onshape response data
def get_features(self, did, wid, eid): return self._api.request('get', '/api/partstudios/d/' + did + '/w/' + wid + '/e/' + eid + '/features')
889,452
Gets the tessellation of the edges of all parts in a part studio. Args: - did (str): Document ID - wid (str): Workspace ID - eid (str): Element ID Returns: - requests.Response: Onshape response data
def get_partstudio_tessellatededges(self, did, wid, eid): return self._api.request('get', '/api/partstudios/d/' + did + '/w/' + wid + '/e/' + eid + '/tessellatededges')
889,453
Uploads a file to a new blob element in the specified doc. Args: - did (str): Document ID - wid (str): Workspace ID - filepath (str, default='./blob.json'): Blob element location Returns: - requests.Response: Onshape response data
def upload_blob(self, did, wid, filepath='./blob.json'): chars = string.ascii_letters + string.digits boundary_key = ''.join(random.choice(chars) for i in range(8)) mimetype = mimetypes.guess_type(filepath)[0] encoded_filename = os.path.basename(filepath) file_content_...
889,454
Exports STL export from a part studio Args: - did (str): Document ID - wid (str): Workspace ID - eid (str): Element ID Returns: - requests.Response: Onshape response data
def part_studio_stl(self, did, wid, eid): req_headers = { 'Accept': 'application/vnd.onshape.v1+octet-stream' } return self._api.request('get', '/api/partstudios/d/' + did + '/w/' + wid + '/e/' + eid + '/stl', headers=req_headers)
889,455
Insert a configurable part into an assembly. Args: - assembly (dict): eid, wid, and did of the assembly into which will be inserted - part (dict): eid and did of the configurable part - configuration (dict): the configuration Returns: - requests.Response...
def create_assembly_instance(self, assembly_uri, part_uri, configuration): payload = { "documentId": part_uri["did"], "elementId": part_uri["eid"], # could be added if needed: # "partId": "String", # "featureId": "String", # "microversionId":...
889,456
Encode parameters as a URL-ready string Args: - did (str): Document ID - eid (str): Element ID - parameters (dict): key-value pairs of the parameters to be encoded Returns: - configuration (str): the url-ready configuration string.
def encode_configuration(self, did, eid, parameters): # change to the type of list the API is expecting parameters = [{"parameterId": k, "parameterValue": v} for (k,v) in parameters.items()] payload = { 'parameters':parameters } req_headers = { ...
889,457
get the configuration of a PartStudio Args: - uri (dict): points to a particular element Returns: - requests.Response: Onshape response data
def get_configuration(self, uri): req_headers = { 'Accept': 'application/vnd.onshape.v1+json', 'Content-Type': 'application/json' } return self._api.request('get', '/api/partstudios/d/' + uri["did"] + '/' + uri["wvm_type"] + '/' + uri["wvm"] + '/e/' + uri["eid"]...
889,458
Update the configuration specified in the payload Args: - did (str): Document ID - eid (str): Element ID - payload (json): the request body Returns: - configuration (str): the url-ready configuration string.
def update_configuration(self, did, wid, eid, payload): req_headers = { 'Accept': 'application/vnd.onshape.v1+json', 'Content-Type': 'application/json' } res = self._api.request('post', '/api/partstudios/d/' + did + '/w/' + wid + '/e/' + eid + '/configuration',...
889,459
Tries to connect to the device to see if it is connectable. Args: host: The host to connect. port: The port to connect. Returns: True or False.
def is_connectable(host: str, port: Union[int, str]) -> bool: socket_ = None try: socket_ = socket.create_connection((host, port), 1) result = True except socket.timeout: result = False finally: if socket_: socket_.close() return result
889,827
Initialization method. Args: name (str): name of the vertex.
def __init__(self, name): self.name = name self.edges_in = set() self.edges_out = set()
890,427
Connect this vertex to another one. Args: vertex (Vertex): vertex to connect to. weight (int): weight of the edge. Returns: Edge: the newly created edge.
def connect_to(self, vertex, weight=1): for edge in self.edges_out: if vertex == edge.vertex_in: return edge return Edge(self, vertex, weight)
890,428
Connect another vertex to this one. Args: vertex (Vertex): vertex to connect from. weight (int): weight of the edge. Returns: Edge: the newly created edge.
def connect_from(self, vertex, weight=1): for edge in self.edges_in: if vertex == edge.vertex_out: return edge return Edge(vertex, self, weight)
890,429
Initialization method. Args: vertex_out (Vertex): source vertex (edge going out). vertex_in (Vertex): target vertex (edge going in). weight (int): weight of the edge.
def __init__(self, vertex_out, vertex_in, weight=1): self.vertex_out = None self.vertex_in = None self.weight = weight self.go_from(vertex_out) self.go_in(vertex_in)
890,430
Tell the edge to go out from this vertex. Args: vertex (Vertex): vertex to go from.
def go_from(self, vertex): if self.vertex_out: self.vertex_out.edges_out.remove(self) self.vertex_out = vertex vertex.edges_out.add(self)
890,432
Tell the edge to go into this vertex. Args: vertex (Vertex): vertex to go into.
def go_in(self, vertex): if self.vertex_in: self.vertex_in.edges_in.remove(self) self.vertex_in = vertex vertex.edges_in.add(self)
890,433
Initialization method. An intermediary matrix is built to ease the creation of the graph. Args: *nodes (list of DSM/Package/Module): the nodes on which to build the graph. depth (int): the depth of the intermediary matrix. See the documentation f...
def __init__(self, *nodes, depth=0): self.edges = set() vertices = [] matrix = Matrix(*nodes, depth=depth) for key in matrix.keys: vertices.append(Vertex(key)) for l, line in enumerate(matrix.data): for c, cell in enumerate(line): ...
890,434
Guess the optimal depth to use for the given list of arguments. Args: packages (list of str): list of packages. Returns: int: guessed depth to use.
def guess_depth(packages): if len(packages) == 1: return packages[0].count('.') + 2 return min(p.count('.') for p in packages) + 1
890,633
Print the object in a file or on standard output by default. Args: format (str): output format (csv, json or text). output (file): descriptor to an opened file (default to standard output). **kwargs (): additional arguments.
def print(self, format=TEXT, output=sys.stdout, **kwargs): if format is None: format = TEXT if format == TEXT: print(self._to_text(**kwargs), file=output) elif format == CSV: print(self._to_csv(**kwargs), file=output) elif format == JSON: ...
890,634
Given an id, get the corresponding file info as the following:\n (relative path joined with file name, file info dict) Parameters: #. id (string): The file unique id string. :Returns: #. relativePath (string): The file relative path joined with file name. ...
def get_file_info_by_id(self, id): for path, info in self.walk_files_info(): if info['id']==id: return path, info # none was found return None, None
890,816
Given an id, get the corresponding file info relative path joined with file name. Parameters: #. id (string): The file unique id string. :Returns: #. relativePath (string): The file relative path joined with file name. If None, it means file was not found.
def get_file_relative_path_by_id(self, id): for path, info in self.walk_files_info(): if info['id']==id: return path # none was found return None
890,817
Removes all files matching the search path Arguments: search_path -- The path you would like to remove, can contain wildcards Example: self._remove_files("output/*.html")
def _remove_files(self, directory, pattern): for root, dirnames, file_names in os.walk(directory): for file_name in fnmatch.filter(file_names, pattern): os.remove(os.path.join(root, file_name))
890,871
Add a user to the specified LDAP group. Args: group: Name of group to update username: Username of user to add Raises: ldap_tools.exceptions.InvalidResult: Results of the query were invalid. The actual exception raised inherits from ...
def add_user(self, group, username): try: self.lookup_id(group) except ldap_tools.exceptions.InvalidResult as err: # pragma: no cover raise err from None operation = {'memberUid': [(ldap3.MODIFY_ADD, [username])]} self.client.modify(self.__distinguished...
890,928
Remove a user from the specified LDAP group. Args: group: Name of group to update username: Username of user to remove Raises: ldap_tools.exceptions.InvalidResult: Results of the query were invalid. The actual exception raised inheri...
def remove_user(self, group, username): try: self.lookup_id(group) except ldap_tools.exceptions.InvalidResult as err: # pragma: no cover raise err from None operation = {'memberUid': [(ldap3.MODIFY_DELETE, [username])]} self.client.modify(self.__disting...
890,929
Lookup GID for the given group. Args: group: Name of group whose ID needs to be looked up Returns: A bytestring representation of the group ID (gid) for the group specified Raises: ldap_tools.exceptions.NoGroupsFound: No Groups w...
def lookup_id(self, group): filter = ["(cn={})".format(group), "(objectclass=posixGroup)"] results = self.client.search(filter, ['gidNumber']) if len(results) < 1: raise ldap_tools.exceptions.NoGroupsFound( 'No Groups Returned by LDAP') elif len(resu...
890,930
Add object to LDAP. Args: distinguished_name: the DN of the LDAP record to be added object_class: The objectClass of the record to be added. This is a list of length >= 1. attributes: a dictionary of LDAP attributes to add See ldap_tools.api.g...
def add(self, distinguished_name, object_class, attributes): self.conn.add(distinguished_name, object_class, attributes)
890,992
Decorate a function so that print arguments before calling it. Args: output: writable to print args. (Default: sys.stdout)
def print_args(output=sys.stdout): def decorator(func): @wraps(func) def _(*args, **kwargs): output.write( "Args: {0}, KwArgs: {1}\n".format(str(args), str(kwargs))) return func(*args, **kwargs) return _ return decorator
891,043
Word-level n-grams in a string By default, whitespace is assumed to be a word boundary. >>> ng.word_ngrams('This is not a test!') [('This', 'is', 'not'), ('is', 'not', 'a'), ('not', 'a', 'test!')] If the sequence's length is less than or equal to n, the n-grams are simply the ...
def word_ngrams(s, n=3, token_fn=tokens.on_whitespace): tokens = token_fn(s) return __ngrams(tokens, n=min(len(tokens), n))
891,132
Returns the n-grams that match between two sequences See also: SequenceMatcher.get_matching_blocks Args: s1: a string s2: another string n: an int for the n in n-gram Returns: set:
def __matches(s1, s2, ngrams_fn, n=3): ngrams1, ngrams2 = set(ngrams_fn(s1, n=n)), set(ngrams_fn(s2, n=n)) return ngrams1.intersection(ngrams2)
891,134
Character-level n-grams that match between two strings Args: s1: a string s2: another string n: an int for the n in n-gram Returns: set: the n-grams found in both strings
def char_matches(s1, s2, n=3): return __matches(s1, s2, char_ngrams, n=n)
891,135
Word-level n-grams that match between two strings Args: s1: a string s2: another string n: an int for the n in n-gram Returns: set: the n-grams found in both strings
def word_matches(s1, s2, n=3): return __matches(s1, s2, word_ngrams, n=n)
891,136
The fraction of n-grams matching between two sequences Args: s1: a string s2: another string n: an int for the n in n-gram Returns: float: the fraction of n-grams matching
def __similarity(s1, s2, ngrams_fn, n=3): ngrams1, ngrams2 = set(ngrams_fn(s1, n=n)), set(ngrams_fn(s2, n=n)) matches = ngrams1.intersection(ngrams2) return 2 * len(matches) / (len(ngrams1) + len(ngrams2))
891,137
Add limitations of given spec to self's. Args: spec (PackageSpec): another spec.
def add(self, spec): for limit in spec.limit_to: if limit not in self.limit_to: self.limit_to.append(limit)
891,175