text
stringlengths
78
104k
score
float64
0
0.18
def _read_packet(self, packet_type=MysqlPacket): """Read an entire "mysql packet" in its entirety from the network and return a MysqlPacket type that represents the results. :raise OperationalError: If the connection to the MySQL server is lost. :raise InternalError: If the packet seque...
0.002377
def map_equal_contributions(contributors): """assign numeric values to each unique equal-contrib id""" equal_contribution_map = {} equal_contribution_keys = [] for contributor in contributors: if contributor.get("references") and "equal-contrib" in contributor.get("references"): for ...
0.002584
def __match_intervals(intervals_from, intervals_to, strict=True): # pragma: no cover '''Numba-accelerated interval matching algorithm. ''' # sort index of the interval starts start_index = np.argsort(intervals_to[:, 0]) # sort index of the interval ends end_index = np.argsort(intervals_to[:, ...
0.004255
def analyze(problem, X, Y, num_resamples=1000, conf_level=0.95, print_to_console=False, seed=None): """Calculates Derivative-based Global Sensitivity Measure on model outputs. Returns a dictionary with keys 'vi', 'vi_std', 'dgsm', and 'dgsm_conf', where each entry is a list of size D (the ...
0.001459
def path_to_geom_dicts(path, skip_invalid=True): """ Converts a Path element into a list of geometry dictionaries, preserving all value dimensions. """ interface = path.interface.datatype if interface == 'geodataframe': return [row.to_dict() for _, row in path.data.iterrows()] elif i...
0.002017
def merge_code(left_code, right_code): """ { relative_line: ((left_abs_line, ((offset, op, args), ...)), (right_abs_line, ((offset, op, args), ...))), ... } """ data = dict() code_lines = (left_code and left_code.iter_code_by_lines()) or tuple() for abs_line, rel_line, dis i...
0.001383
def _collate(self, batch): """ Puts each data field into a tensor. :param batch: The input data batch. :type batch: list of features :return: Preprocessed data. :rtype: torch.Tensor or pair of torch.Tensor """ if isinstance(batch[0], tuple): ...
0.006522
def functional(ifunctional): """ fun(fn) -> function or fun(fn, args...) -> call of fn(args...) :param ifunctional: f :return: decorated function """ @wraps(ifunctional) def wrapper(fn, *args, **kw): fn = ifunctional(fn) if args or kw: return fn(*args, **kw)...
0.00266
def mean(data): """Return the sample arithmetic mean of data. >>> mean([1, 2, 3, 4, 4]) 2.8 >>> from fractions import Fraction as F >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]) Fraction(13, 21) >>> from decimal import Decimal as D >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375...
0.001686
def renew_secret(client, creds, opt): """Renews a secret. This will occur unless the user has specified on the command line that it is not neccesary""" if opt.reuse_token: return seconds = grok_seconds(opt.lease) if not seconds: raise aomi.exceptions.AomiCommand("invalid lease %s" %...
0.000814
def set_trunk_groups(self, intf, value=None, default=False, disable=False): """Configures the switchport trunk group value Args: intf (str): The interface identifier to configure. value (str): The set of values to configure the trunk group default (bool): Configures ...
0.001682
def noam_norm(x, epsilon=1.0, name=None): """One version of layer normalization.""" with tf.name_scope(name, default_name="noam_norm", values=[x]): shape = x.get_shape() ndims = len(shape) return (tf.nn.l2_normalize(x, ndims - 1, epsilon=epsilon) * tf.sqrt( to_float(shape[-1])))
0.009901
def _find_child(self, tag): """Find the child C{etree.Element} with the matching C{tag}. @raises L{WSDLParseError}: If more than one such elements are found. """ tag = self._get_namespace_tag(tag) children = self._root.findall(tag) if len(children) > 1: raise...
0.004494
def ratio(self, operand): """Calculate the ratio of this `Spectrogram` against a reference Parameters ---------- operand : `str`, `FrequencySeries`, `Quantity` a `~gwpy.frequencyseries.FrequencySeries` or `~astropy.units.Quantity` to weight against, or one of ...
0.001638
def graphql_to_gremlin(schema, graphql_query, parameters, type_equivalence_hints=None): """Compile the GraphQL input using the schema into a Gremlin query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_query: the GraphQL que...
0.009182
def add_paginated_grid_widget(self, part_model, delete=False, edit=True, export=True, clone=True, new_instance=False, parent_part_instance=None, max_height=None, custom_title=False, emphasize_edit=False, emphasize_clone=False, emphasize_new_instance=Tr...
0.00392
def get(self): """ Dequeue a state with the max priority """ # A shutdown has been requested if self.is_shutdown(): return None # if not more states in the queue, let's wait for some forks while len(self._states) == 0: # if no worker is running, bail out...
0.002323
def downgrade(): """Downgrade database.""" # Remove 'created' and 'updated' columns op.drop_column('oauthclient_remoteaccount', 'created') op.drop_column('oauthclient_remoteaccount', 'updated') op.drop_column('oauthclient_remotetoken', 'created') op.drop_column('oauthclient_remotetoken', 'updat...
0.002268
def import_plugin(self, plugin): ''' Import plugin by given name, looking at :attr:`namespaces`. :param plugin: plugin module name :type plugin: str :raises PluginNotFoundError: if not found on any namespace ''' names = [ '%s%s%s' % (namespace, '' if ...
0.002255
def _get_center(self): '''Returns the center point of the path, disregarding transforms. ''' w, h = self.layout.get_pixel_size() x = (self.x + w / 2) y = (self.y + h / 2) return x, y
0.008696
def a_torispherical(D, f, k): r'''Calculates depth of a torispherical head according to [1]_. .. math:: a = a_1 + a_2 .. math:: \alpha = \sin^{-1}\frac{1-2k}{2(f-k)} .. math:: a_1 = fD(1-\cos\alpha) .. math:: a_2 = kD\cos\alpha Parameters ---------- D...
0.002022
def linearize(self, index=0): '''Linearize circular DNA at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.DNA :raises: ValueError if the input is linear DNA. ''' ...
0.003091
def compare_files(path1, path2): # type: (str, str) -> List[str] """Returns the delta between two files using -, ?, + format excluding lines that are the same Args: path1 (str): Path to first file path2 (str): Path to second file Returns: List[str]: Delta between the two fi...
0.00216
def change_username(self, username): """ Change username :param username: email or str :return: """ username = username.lower() if self.username != username: if self.get_by_username(username): raise exceptions.AuthError("Username exists...
0.005362
def create_native(self): """ Create the native widget if not already done so. If the widget is already created, this function does nothing. """ if self._backend is not None: return # Make sure that the app is active assert self._app.native # Instantiat...
0.002309
def libvlc_vlm_set_output(p_instance, psz_name, psz_output): '''Set the output for a media. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_output: the output MRL (the parameter to the "sout" variable). @return: 0 on success, -1 on error. ''' f = _Cfunction...
0.003591
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")
0.006452
def ctrl_request_update(_, nl_sock_h): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L37. Positional arguments: nl_sock_h -- nl_sock class instance. Returns: Integer, genl_send_simple() output. """ return int(genl_send_simple(nl_sock_h, GENL_ID_CTRL, CTRL_CMD_GETFAMI...
0.005714
def set_custom_colorset(self): """Defines a colorset with matching colors. Provided by Joachim.""" cmd.set_color('myorange', '[253, 174, 97]') cmd.set_color('mygreen', '[171, 221, 164]') cmd.set_color('myred', '[215, 25, 28]') cmd.set_color('myblue', '[43, 131, 186]') cmd...
0.004751
def parse_last_period(last): """ Parse the --last value and return the time difference in seconds. """ wordmap = { 'hour': '1h', 'day': '1d', 'week': '1w', 'month': '1m' } # seconds multmap = { 'h': 3600, 'd': 86400, 'w': 604800, ...
0.008915
def update_params(self, params): """ update connection params to maximize performance """ if not params.get('BINARY', True): raise Warning('To increase performance please use ElastiCache' ' in binary mode') else: params['BINARY'] ...
0.003521
def most_populated(adf): """ Looks at each column, using the one with the most values Honours the Trump override/failsafe logic. """ # just look at the feeds, ignore overrides and failsafes: feeds_only = adf[adf.columns[1:-1]] # find the most populated feed cnt_...
0.007923
def from_collection_xml(cls, xml_content): """Build a :class:`~zenodio.harvest.Datacite3Collection` from Datecite3-formatted XML. Users should use :func:`zenodio.harvest.harvest_collection` to build a :class:`~zenodio.harvest.Datacite3Collection` for a Community. Parameters ...
0.00241
def setup_hfb_pars(self): """setup non-mult parameters for hfb (yuck!) """ if self.m.hfb6 is None: self.logger.lraise("couldn't find hfb pak") tpl_file,df = pyemu.gw_utils.write_hfb_template(self.m) self.in_files.append(os.path.split(tpl_file.replace(".tpl",""))[-1]...
0.009685
def extend(self, *iterables): """Add all values of all iterables at the end of the list Args: iterables: iterable which content to add at the end Example: >>> from ww import l >>> lst = l([]) >>> lst.extend([1, 2]) [1, 2] ...
0.003442
def abort(bot, config, settings): """Run the abort command of a specified BOT by label e.g. 'MyBot'""" print_options(bot, config, settings) click.echo() bot_task = BotTask(bot, config) bot_task.abort()
0.004525
def round_point_coords(pt, precision): """ Round the coordinates of a shapely Point to some decimal precision. Parameters ---------- pt : shapely Point the Point to round the coordinates of precision : int decimal precision to round coordinates to Returns ------- Po...
0.005025
def _resetFTDI(self): """ reset the FTDI device """ if not self._isFTDI: return txdir = 0 # 0:OUT, 1:IN req_type = 2 # 0:std, 1:class, 2:vendor recipient = 0 # 0:device, 1:interface, 2:endpoint, 3:other req_type = (txdir << 7) + ...
0.003683
def torque_on(self): """ Enable the torques of Herkulex In this mode, position control and velocity control will work. Args: none """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append...
0.004808
def run(self): """Launch the broker(s) and worker(s) assigned on every hosts.""" # Launch the broker(s) for hostname, nb_brokers in self.broker_hosts: for ind in range(nb_brokers): if self.externalHostname in utils.localHostnames: self.brokers.appe...
0.001346
def codemirror_field_js_bundle(field): """ Filter to get CodeMirror Javascript bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_js_bundle }} Arguments: field (django.forms.fields.Field): A form field t...
0.001014
def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(set(iterable)) combs = chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) res = set(frozenset(x) for x in combs) # res = map(frozenset, combs) return res
0.003425
def print_terminal_table(headers, data_list, parse_row_fn): """Uses a set of headers, raw data, and a row parsing function, to print data to the terminal in a table of rows and columns. Args: headers (tuple of strings): The headers for each column of data data_list (list of dicts): Raw resp...
0.000879
def require_server(fn): """ Checks if the user has called the task with a server name. Fabric tasks decorated with this decorator must be called like so:: fab <server name> <task name> If no server name is given, the task will not be executed. """ @wraps(fn) def wrapper(*args, **...
0.001916
def parse(filename): """Parses file content into events stream""" for event, elt in et.iterparse(filename, events= ('start', 'end', 'comment', 'pi'), huge_tree=True): if event == 'start': obj = _elt2obj(elt) obj['type'] = ENTER yield obj if elt.text: ...
0.003989
def delete_network(context, id): """Delete a network. : param context: neutron api request context : param id: UUID representing the network to delete. """ LOG.info("delete_network %s for tenant %s" % (id, context.tenant_id)) with context.session.begin(): net = db_api.network_find(conte...
0.000977
def get(self, sid): """ Constructs a AddressContext :param sid: The unique string that identifies the resource :returns: twilio.rest.api.v2010.account.address.AddressContext :rtype: twilio.rest.api.v2010.account.address.AddressContext """ return AddressContext(s...
0.007752
def unique_row(array, use_columns=None, selected_columns_only=False): '''Takes a numpy array and returns the array reduced to unique rows. If columns are defined only these columns are taken to define a unique row. The returned array can have all columns of the original array or only the columns defined in use_...
0.002328
def upload_files(self, source_paths, dir_name=None): '''批量创建上传任务, 会扫描子目录并依次上传. source_path - 本地文件的绝对路径 dir_name - 文件在服务器上的父目录, 如果为None的话, 会弹出一个 对话框让用户来选择一个目录. ''' def scan_folders(folder_path): file_list = os.listdir(folder_path) ...
0.001461
def set_column_si_format(tree_column, model_column_index, cell_renderer=None, digits=2): ''' Set the text of a numeric cell according to [SI prefixes][1] For example, `1000 -> '1.00k'`. [1]: https://en.wikipedia.org/wiki/Metric_prefix#List_of_SI_prefixes Args: tr...
0.00082
def add_channel(self, chname, workspace=None, num_images=None, settings=None, settings_template=None, settings_share=None, share_keylist=None): """Create a new Ginga channel. Parameters ---------- chname : str The n...
0.001648
def parse_netloc(scheme, netloc): """Parse netloc string.""" auth, _netloc = netloc.split('@') sender, token = auth.split(':') if ':' in _netloc: domain, port = _netloc.split(':') port = int(port) else: domain = _netloc if scheme == 'https': port = 443 ...
0.00237
def gradient(self): r"""Gradient operator of the functional. Notes ----- The derivative is computed using the quotient rule: .. math:: [\nabla (f / g)](p) = (g(p) [\nabla f](p) - f(p) [\nabla g](p)) / g(p)^2 """ fu...
0.002183
def IIR_bsf(f_pass1, f_stop1, f_stop2, f_pass2, Ripple_pass, Atten_stop, fs = 1.00, ftype = 'butter'): """ Design an IIR bandstop filter using scipy.signal.iirdesign. The filter order is determined based on f_pass Hz, f_stop Hz, and the desired stopband attenuation d_stop in dB,...
0.013807
def UpdateOsLogin(self, oslogin_desired, two_factor_desired=False): """Update whether OS Login is enabled and update NSS cache if necessary. Args: oslogin_desired: bool, enable OS Login if True, disable if False. two_factor_desired: bool, enable two factor if True, disable if False. Returns: ...
0.007324
def local_temp_dir(): """ Creates a local temporary directory. The directory is removed when no longer needed. Failure to do so will be ignored. :return: Path to the temporary directory. :rtype: unicode """ path = tempfile.mkdtemp() yield path shutil.rmtree(path, ignore_errors=True)
0.00625
def remove_prefix(self, prefix): """Removes prefix from this set. This is a no-op if the prefix doesn't exist in it. """ if prefix not in self.__prefix_map: return ni = self.__lookup_prefix(prefix) ni.prefixes.discard(prefix) del self.__prefix_map[pr...
0.004049
def update(self, data): '''Updates object information with live data (if live data has different values to stored object information). Changes will be automatically applied, but not persisted in the database. Call `db.session.add(elb)` manually to commit the changes to the DB. A...
0.000947
def send_status_message(self, object_id, status): """Send a message to the `status_queue` to update a job's status. Returns `True` if the message was sent, else `False` Args: object_id (`str`): ID of the job that was executed status (:obj:`SchedulerStatus`): Status of t...
0.002466
def distances(self): """The matrix with the all-pairs shortest path lenghts""" from molmod.ext import graphs_floyd_warshall distances = np.zeros((self.num_vertices,)*2, dtype=int) #distances[:] = -1 # set all -1, which is just a very big integer #distances.ravel()[::len(distances...
0.009398
def _read_mode_tr(self, size, kind): """Read Traceroute option. Positional arguments: size - int, length of option kind - int, 82 (TR) Returns: * dict -- extracted Traceroute (TR) option Structure of Traceroute (TR) option [RFC 1393][RFC 6814]: ...
0.000932
def sort(self, *keys): """ Add sorting information to the search request. If called without arguments it will remove all sort requirements. Otherwise it will replace them. Acceptable arguments are:: 'some.field' '-some.other.field' {'different.field':...
0.00273
def reverse_lazy_with_query(named_url,**kwargs): "Reverse named URL with GET query (lazy version)" q = QueryDict('',mutable=True) q.update(kwargs) return '{}?{}'.format(reverse_lazy(named_url),q.urlencode())
0.017937
def qqplot(x, dist='norm', sparams=(), confidence=.95, figsize=(5, 4), ax=None): """Quantile-Quantile plot. Parameters ---------- x : array_like Sample data. dist : str or stats.distributions instance, optional Distribution or distribution function name. The default is 'n...
0.000163
def make_spondaic(self, scansion: str) -> str: """ If a pentameter line has 12 syllables, then it must start with double spondees. :param scansion: a string of scansion patterns :return: a scansion pattern string starting with two spondees >>> print(PentameterScanner().make_spo...
0.005102
def _create_tree(self, endpoint=None, index=0): """ This will return a string of the endpoint tree structure :param endpoint: Endpoint's Current path of the source :param index: int number of tabs to space over :return: str """ tab = '' # '\t' * index ret...
0.002608
def pad_sentences(sentences, padding_word="</s>"): """Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences. """ sequence_length = max(len(x) for x in sentences) padded_sentences = [] for i, sentence in enumerate(sentences): num_pa...
0.004032
def _get_disksize_MiB(iLOIP, cred): """Reads the dictionary of parsed MIBs and gets the disk size. :param iLOIP: IP address of the server on which SNMP discovery has to be executed. :param snmp_credentials in a dictionary having following mandatory keys. auth_user: S...
0.000845
def make_fileitem_streamlist_stream_name(stream_name, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/StreamList/Stream/Name :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/StreamList/Stream/Name' co...
0.008711
def add_range(self, start, part_len, total_len): """ Add range headers indicating that this a partial response """ content_range = 'bytes {0}-{1}/{2}'.format(start, start + part_len - 1, ...
0.003478
def ser2ber(q,n,d,t,ps): """ Converts symbol error rate to bit error rate. Taken from Ziemer and Tranter page 650. Necessary when comparing different types of block codes. parameters ---------- q: size of the code alphabet for given modulation type (BPSK=2) n: number of channel bits ...
0.017979
def delete_service_group(self, group_id): """Deletes a service group from the loadbal_id. :param int group_id: The id of the service group to delete """ svc = self.client['Network_Application_Delivery_Controller_' 'LoadBalancer_VirtualServer'] return ...
0.005731
def ConfigureUrls(config, external_hostname = None): """Guides the user through configuration of various URLs used by GRR.""" print("\n\n-=GRR URLs=-\n" "For GRR to work each client has to be able to communicate with the\n" "server. To do this we normally need a public dns name or IP address\n" ...
0.010112
def fetch_track(self, track_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches a song track by given ID. :param track_id: the track ID. :type track_id: str :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#tracks-track_id`. ''...
0.005618
def rollback(self): """Cancels any database changes done during the current transaction.""" if self._transaction_nesting_level == 0: raise DBALConnectionError.no_active_transaction() self.ensure_connected() if self._transaction_nesting_level == 1: self._transacti...
0.003802
def name(self) -> str: """Return template's name (includes whitespace).""" h = self._atomic_partition(self._first_arg_sep)[0] if len(h) == len(self.string): return h[2:-2] return h[2:]
0.008772
def get_categories_tree(context, template='zinnia/tags/categories_tree.html'): """ Return the categories as a tree. """ return {'template': template, 'categories': Category.objects.all().annotate( count_entries=Count('entries')), 'context_category': context.get('c...
0.00303
def handle_data(self, data): """Function called for text nodes""" if not self.silent: possible_urls = re.findall( r'(https?://[\w\d:#%/;$()~_?\-=\\\.&]*)', data) # validate possible urls # we'll transform them just in case # they are valid....
0.002747
def set_profiling_level(self, level, slow_ms=None, session=None): """Set the database's profiling level. :Parameters: - `level`: Specifies a profiling level, see list of possible values below. - `slow_ms`: Optionally modify the threshold for the profile to co...
0.001006
def FDMT_iteration(datain, maxDT, nchan0, f_min, f_max, iteration_num, dataType): """ Input: Input - 3d array, with dimensions [nint, N_d0, nbl, nchan, npol] f_min,f_max - are the base-band begin and end frequencies. The frequencies can be entered in both MHz and GHz...
0.00778
async def fetch_logical_load(self, llid): """Lookup details for a given logical load""" url = "https://production.plum.technology/v2/getLogicalLoad" data = {"llid": llid} return await self.__post(url, data)
0.008403
def _check_disabled(self): """Check if health check is disabled. It logs a message if health check is disabled and it also adds an item to the action queue based on 'on_disabled' setting. Returns: True if check is disabled otherwise False. """ if self.confi...
0.001821
def read_creds_from_environment_variables(): """ Read credentials from environment variables :return: """ creds = init_creds() # Check environment variables if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ: creds['AccessKeyId'] = os.environ['AWS_ACCESS_...
0.003774
def concatenate_matrices(*matrices): """Return concatenation of series of transformation matrices. >>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5 >>> numpy.allclose(M, concatenate_matrices(M)) True >>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T)) True """ M = nu...
0.002506
def string( element_name, # type: Text attribute=None, # type: Optional[Text] required=True, # type: bool alias=None, # type: Optional[Text] default='', # type: Optional[Text] omit_empty=False, # type: bool strip_whitespace=True, # type: bool hooks=...
0.002364
def render(self, context, instance, placeholder): ''' Add the cart-specific context to this form ''' context = super(SquareCheckoutFormPlugin, self).render(context, instance, placeholder) context.update({ 'squareApplicationId': getattr(settings,'SQUARE_APPLICATION_ID',''), ...
0.016997
def depth_august_average_ground_temperature(self, value=None): """Corresponds to IDD Field `depth_august_average_ground_temperature` Args: value (float): value for IDD Field `depth_august_average_ground_temperature` Unit: C if `value` is None it will not be c...
0.004711
def extends_(cls, kls): """ A view decorator to extend another view class or function to itself It will inherit all its methods and propeties and use them on itself -- EXAMPLES -- class Index(Pylot): pass index = Index() ::-> As decorator on classe...
0.002172
def find_xml_generator(name="castxml"): """ Try to find a c++ parser (xml generator) Args: name (str): name of the c++ parser (e.g. castxml) Returns: path (str), name (str): path to the xml generator and it's name If no c++ parser is found the function raises an exception. py...
0.00142
def get_year_and_month(self, net, qs, **kwargs): """ Get the year and month. First tries from kwargs, then from querystrings. If none, or if cal_ignore qs is specified, sets year and month to this year and this month. """ now = c.get_now() year = now.year ...
0.001789
def CreateHunt(hunt_obj): """Creates a hunt using a given hunt object.""" data_store.REL_DB.WriteHuntObject(hunt_obj) if hunt_obj.HasField("output_plugins"): output_plugins_states = flow.GetOutputPluginStates( hunt_obj.output_plugins, source="hunts/%s" % hunt_obj.hunt_id, token=access...
0.007874
def explore_genres(self, parent_genre_id=None): """Get a listing of song genres. Parameters: parent_genre_id (str, Optional): A genre ID. If given, a listing of this genre's sub-genres is returned. Returns: list: Genre dicts. """ response = self._call( mc_calls.ExploreGenres, parent_genre_i...
0.038168
def expand_value(self, **kwargs): """ expand the selection to account for wildcards """ selection = [] for v in self.get_value(**kwargs): for choice in self.choices: if v==choice and choice not in selection: selection.append(choice)...
0.006522
def _search(self, model, condition=None, search_field='name', value_field='id', label_field=None, pagination=True): """ Default search function :param search_field: Used for search field, default is 'name' :param value_field: Used for id field, default is id :para...
0.006325
def get_user(self, user_id): """ Get user details. :param user_id: Identification of user by username (str) or user ID (int) :returns: User details as strings in dictionary with these keys for RT users: * Lang ...
0.002967
def from_json(cls, key): """Creates a RFC 7517 JWK from the standard JSON format. :param key: The RFC 7517 representation of a JWK. """ obj = cls() try: jkey = json_decode(key) except Exception as e: # pylint: disable=broad-except raise InvalidJW...
0.005277
def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key )
0.003195
def _parse_input_parameters(self): """ Set the configuration for the Logger """ Global.LOGGER.debug("define and parsing command line arguments") parser = argparse.ArgumentParser( description='A workflow engine for Pythonistas', formatter_class=argparse.RawTextHelpForm...
0.009649
def num_batches(n, batch_size): """Compute the number of mini-batches required to cover a data set of size `n` using batches of size `batch_size`. Parameters ---------- n: int the number of samples in the data set batch_size: int the mini-batch size Returns ------- ...
0.002262
def autobuild_doxygen(tile): """Generate documentation for firmware in this module using doxygen""" iotile = IOTile('.') doxydir = os.path.join('build', 'doc') doxyfile = os.path.join(doxydir, 'doxygen.txt') outfile = os.path.join(doxydir, '%s.timestamp' % tile.unique_id) env = Environment(EN...
0.003254