text
stringlengths
78
104k
score
float64
0
0.18
def collection_list(self, resource_id, resource_type="collection"): """ Fetches a list of all resource and component IDs within the specified resource. :param long resource_id: The ID of the resource to fetch children from. :param string resource_type: Specifies whether the resource to ...
0.005604
def _need_update(self): 'Returns whether the ProgressBar should redraw the line.' if self.currval >= self.next_update or self.finished: return True delta = time.time() - self.last_update_time return self._time_sensitive and delta > self.poll
0.010949
def explore_server(server_url, username, password): """ Demo of exploring a cim server for characteristics defined by the server class """ print("WBEM server URL:\n %s" % server_url) conn = WBEMConnection(server_url, (username, password), no_verification=True) se...
0.000818
def _random_best_expander(fringe, iteration, viewer): ''' Expander that expands one randomly chosen nodes on the fringe that is better than the current (first) node. ''' current = fringe[0] neighbors = current.expand(local_search=True) if viewer: viewer.event('expanded', [current], [...
0.001773
def validate_any(prop, value, xpath_map=None): """ Validates any metadata property, complex or simple (string or array) """ if value is not None: if prop in (ATTRIBUTES, CONTACTS, DIGITAL_FORMS): validate_complex_list(prop, value, xpath_map) elif prop in (BOUNDING_BOX, LARGER_WORKS...
0.002235
def lock_parameter(self, name, par, lock=True): """Set parameter to locked/unlocked state. A locked parameter will be ignored when running methods that free/fix sources or parameters. Parameters ---------- name : str Source name. par : str ...
0.005063
def opt(parser: Union[Parser, Sequence[Input]]) -> OptionalParser: """Optionally match a parser. An ``OptionalParser`` attempts to match ``parser``. If it succeeds, it returns a list of length one with the value returned by the parser as the only element. If it fails, it returns an empty list. Arg...
0.002179
def cache_key(working_directory, arguments, configure_kwargs): """Compute a `TensorBoardInfo.cache_key` field. The format returned by this function is opaque. Clients may only inspect it by comparing it for equality with other results from this function. Args: working_directory: The directory from which...
0.0041
def _ConstructReference(cls, pairs=None, flat=None, reference=None, serialized=None, urlsafe=None, app=None, namespace=None, parent=None): """Construct a Reference; the signature is the same as for Key.""" if cls is not Key: raise TypeError('Cannot construct Key r...
0.008722
def get_metrics(metrics_description): """Get metrics from a list of dictionaries. """ return utils.get_objectlist(metrics_description, config_key='data_analyzation_plugins', module=sys.modules[__name__])
0.003636
def get_notables(self, id_num): """Return the notables of the activity with the given id. """ url = self._build_url('my', 'activities', id_num, 'notables') return self._json(url)
0.009524
def render_summary(self, include_title=True, request=None): """Render the traceback for the interactive console.""" title = '' frames = [] classes = ['traceback'] if not self.frames: classes.append('noframe-traceback') if include_title: if self.is...
0.002028
def proxy_callback_allowed(service, pgturl): """Check if a given proxy callback is allowed for the given service identifier.""" if hasattr(settings, 'MAMA_CAS_SERVICES'): return _is_allowed('proxy_callback_allowed', service, pgturl) return _is_valid_service_url(service)
0.006897
def group_records_by_type(records, update_events): """Break records into two lists; create/update events and delete events. :param records: :param update_events: :return update_records, delete_records: """ update_records, delete_records = [], [] for record in records: if record.get(...
0.002053
def getOneMessage ( self ): """ I pull one complete message off the buffer and return it decoded as a dict. If there is no complete message in the buffer, I return None. Note that the buffer can contain more than once message. You should therefore call me in a loop until...
0.017823
def parse(self, format_string): """Parse color syntax from a formatted string.""" txt, state = '', 0 colorstack = [(None, None)] itokens = self.tokenize(format_string) for token, escaped in itokens: if token == self._START_TOKEN and not escaped: if tx...
0.001191
def block_sep1(self, Y): r"""Separate variable into component corresponding to :math:`\mathbf{y}_1` in :math:`\mathbf{y}\;\;`. """ return Y[(slice(None),)*self.blkaxis + (slice(self.blkidx, None),)]
0.008658
def get_readable_time(t): """ Format the time to a readable format. Parameters ---------- t : int Time in ms Returns ------- string The time splitted to highest used time (minutes, hours, ...) """ ms = t % 1000 t -= ms t /= 1000 s = t % 60 t -= ...
0.00158
def search_hits(self, sort_by='CreationTime', sort_direction='Ascending', page_size=10, page_number=1, response_groups=None): """ Return a page of a Requester's HITs, on behalf of the Requester. The operation returns HITs of any status, except for HITs that have been...
0.011905
def get_table_from_csv(filename='ssg_report_aarons_returns.csv', delimiter=',', dos=False): """Dictionary of sequences from CSV file""" table = [] with open(filename, 'rb') as f: reader = csv.reader(f, dialect='excel', delimiter=delimiter) for row in reader: table += [row] if...
0.005222
def from_mpl(fig, savefig_kw=None): """Create a SVG figure from a ``matplotlib`` figure. Parameters ---------- fig : matplotlib.Figure instance savefig_kw : dict keyword arguments to be passed to matplotlib's `savefig` Returns ------- SVGFigure newly create...
0.000805
def read_frvect(vect, epoch, start, end, name=None, series_class=TimeSeries): """Read an array from an `FrVect` structure Parameters ---------- vect : `LDASTools.frameCPP.FrVect` the frame vector structur to read start : `float` the GPS start time of the request end : `float` ...
0.000446
def _read_utf(cls, data, pos, kind=None): """ :param kind: Optional; a human-friendly identifier for the kind of UTF-8 data we're loading (e.g. is it a keystore alias? an algorithm identifier? something else?). Used to construct more informative exception messages when a decoding er...
0.009198
async def _on_event(self, event_): """Receive a hangouts_pb2.Event and fan out to Conversations. Args: event_: hangouts_pb2.Event instance """ conv_id = event_.conversation_id.id try: conv = await self._get_or_fetch_conversation(conv_id) except ex...
0.002401
def multi_map(key, iterable, *, default_dict=False): """Collect data into a multi-map. Arguments ---------- key : function A function that accepts an element retrieved from the iterable and returns the key to be used in the multi-map iterable : ite...
0.001074
def unban_chat_member( self, chat_id: Union[int, str], user_id: Union[int, str] ) -> bool: """Use this method to unban a previously kicked user in a supergroup or channel. The user will **not** return to the group or channel automatically, but will be able to join via link, e...
0.005761
def rename(self, from_symbol, to_symbol, audit=None): """ Rename a symbol Parameters ---------- from_symbol: str the existing symbol that will be renamed to_symbol: str the new symbol name audit: dict audit information ...
0.002147
def buy_open_order_quantity(self): """ [int] 买方向挂单量 """ return sum(order.unfilled_quantity for order in self.open_orders if order.side == SIDE.BUY and order.position_effect == POSITION_EFFECT.OPEN)
0.012097
def _update_history(self): """Save the current test information to history json.""" ipa_utils.update_history_log( self.history_log, description=self.description, test_log=self.log_file )
0.00813
def installOrResume(self, userstore): """ Install this product on a user store. If this product has been installed on the user store already and the installation is suspended, it will be resumed. If it exists and is not suspended, an error will be raised. """ for ...
0.004298
def render_template(self, template_path, context=None): """ This function has been deprecated. It calls render_django_template to support backwards compatibility. """ warnings.warn( "ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_t...
0.009877
def add_exploration(traj): """Explores different values of `I` and `tau_ref`.""" print('Adding exploration of I and tau_ref') explore_dict = {'neuron.I': np.arange(0, 1.01, 0.01).tolist(), 'neuron.tau_ref': [5.0, 7.5, 10.0]} explore_dict = cartesian_product(explore_dict, ('neuron....
0.005155
def limit(self, limit): """ Set absolute limit on number of images to return, or set to None to return as many results as needed; default 50 posts. """ params = join_params(self.parameters, {"limit": limit}) return self.__class__(**params)
0.003788
def get_all(): ''' Return all installed services CLI Example: .. code-block:: bash salt '*' service.get_all ''' cmd = 'launchctl list' service_lines = [ line for line in __salt__['cmd.run'](cmd).splitlines() if not line.startswith('PID') ] service_labels_...
0.001838
def sort_by_preference(options, prefer): """ :param options: List of options :param prefer: Prefered options :return: Pass in a list of options, return options in 'prefer' first >>> sort_by_preference(["cairo", "cairocffi"], ["cairocffi"]) ["cairocffi", "cairo"] """ if not prefer: ...
0.002427
def _compute_heating_rates(self): """Computes energy flux convergences to get heating rates in :math:`W/m^2`. """ for varname, value in self.state.items(): self.heating_rate[varname] = - self.b * (value - global_mean(value))
0.015326
def return_hdr(self): """Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str ...
0.000675
def dump(self, dest_pattern="{id}.jpg", override=True, max_size=None, bits=8, contrast=None, gamma=None, colormap=None, inverse=None): """ Download the image with optional image modifications. Parameters ---------- dest_pattern : str, optional Destinatio...
0.004029
def onSave(self, grid):#, age_data_type='site'): """ Save grid data in the data object """ # deselect column, including remove 'EDIT ALL' label if self.drop_down_menu: self.drop_down_menu.clean_up() # save all changes to er_magic data object self.grid...
0.00817
def debug_print(*message): """Output debug messages to stdout""" warnings.warn("debug_print is deprecated; use the logging module instead.") if get_debug_level(): ss = STDOUT if PY3: # This is needed after restarting and using debug_print for m in message: ...
0.002188
def mappedPolygon(self, polygon, path=None, percent=0.5): """ Maps the inputed polygon to the inputed path \ used when drawing items along the path. If no \ specific path is supplied, then this object's own \ path will be used. It will rotate and move the \ polygon acco...
0.002618
def expected_h(nvals, fit="RANSAC"): """ Uses expected_rs to calculate the expected value for the Hurst exponent h based on the values of n used for the calculation. Args: nvals (iterable of int): the values of n used to calculate the individual (R/S)_n KWargs: fit (str): the fitting met...
0.007519
def visit_html(self, node): """ Generate html elements and schematic json """ parentClsNode = node.parent.parent assert parentClsNode.attributes['objtype'] == 'class' assert parentClsNode.attributes['domain'] == 'py' sign = node.parent.parent.children[0] a...
0.003756
def get_groundings(entity): """Return groundings as db_refs for an entity.""" def get_grounding_entries(grounding): if not grounding: return None entries = [] values = grounding.get('values', []) # Values could still have been a None entry...
0.001498
def closeSession(self): """ C_CloseSession """ rv = self.lib.C_CloseSession(self.session) if rv != CKR_OK: raise PyKCS11Error(rv)
0.01105
def build(self, output_path=""): """method that should be inherited by all vis classes""" self.output_path = self.checkOutputPath(output_path) self._buildStaticFiles() self.final_url = self._buildTemplates() printDebug("Done.", "comment") printDebug("=> %s" % (self.final...
0.00545
def in_words_float(amount, _gender=FEMALE): """ Float in words @param amount: float numeral @type amount: C{float} or C{Decimal} @return: in-words reprsentation of float numeral @rtype: C{unicode} @raise ValueError: when ammount is negative """ check_positive(amount) pts = []...
0.00152
def fromexcel(cls, path, sheet_name_or_num=0, headers=None): """ Constructs a new DataTable from an Excel file. Specify sheet_name_or_number to load that specific sheet. Headers will be inferred automatically, but if you'd prefer to load only a subset of all the headers, pass i...
0.002911
def clear(self): """ Calls `_clear` abstract method which must be implemented by descendants. :raises: GPflowError exception when parent of the node is built. """ parent = self.parent if parent is not self and parent.is_built_coherence(self.graph) is Build.YES: ...
0.011905
def cut_cross(self, x, y, radius, data): """Cut two data subarrays that have a center at (x, y) and with radius (radius) from (data). Returns the starting pixel (x0, y0) of each cut and the respective arrays (xarr, yarr). """ n = int(round(radius)) ht, wd = data.shape ...
0.003407
def create_subscribe(self, access_token, show_id): """doc: http://open.youku.com/docs/doc?id=29 """ url = 'https://openapi.youku.com/v2/users/subscribe/create.json' params = { 'client_id': self.client_id, 'access_token': access_token, 'show_id': show_i...
0.004566
def on_resize(self, event): """Resize handler Parameters ---------- event : instance of Event The resize event. """ self._update_transforms() if self._central_widget is not None: self._central_widget.size = self.size ...
0.009501
def verification_list(self, limit=10): """ Get list of verifications. Uses GET to /verifications interface. :Returns: (list) Verification list as specified `here <https://cloud.knuverse.com/docs/api/#api-Verifications-Get_verification_list>`_. """ # TODO add arguments for pagi...
0.005357
def init(name, *args, **kwargs): """Instantiate a plugin from the catalog. """ if name in _PLUGIN_CATALOG: if rapport.config.get_int("rapport", "verbosity") >= 2: print("Initialize plugin {0}: {1} {2}".format(name, args, kwargs)) try: return _PLUGIN_CATALOG[name](*arg...
0.005217
def content(self, file_relpath): """Returns the content for file at path. Raises exception if path is ignored. Raises exception if path is ignored. """ if self.isignored(file_relpath): self._raise_access_ignored(file_relpath) return self._content_raw(file_relpath)
0.010274
def process_request(self, request_object): """Process Create Resource Request""" resource = request_object.entity_cls.create(**request_object.data) return ResponseSuccessCreated(resource)
0.009434
def lower_folded_outputs(ir_blocks): """Lower standard folded output fields into GremlinFoldedContextField objects.""" folds, remaining_ir_blocks = extract_folds_from_ir_blocks(ir_blocks) if not remaining_ir_blocks: raise AssertionError(u'Expected at least one non-folded block to remain: {} {} ' ...
0.005171
def put(self, items, panic=True): """ Load a single row into the target table. :param list items: A list of values in the row corresponding to the fields specified by :code:`self.columns` :param bool panic: If :code:`True`, when an error is encountered it will be ...
0.004484
def entities(self, subject_id): """ Returns all the entities of assertions for a subject, disregarding whether the assertion still is valid or not. :param subject_id: The identifier of the subject :return: A possibly empty list of entity identifiers """ res = self._cache...
0.004556
def system_switch_attributes_chassis_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") system = ET.SubElement(config, "system", xmlns="urn:brocade.com:mgmt:brocade-ras") switch_attributes = ET.SubElement(system, "switch-attributes") chassis_na...
0.00578
def build_model(input_shape): """Create a compiled Keras model. Parameters ---------- input_shape : tuple, len=3 Shape of each image sample. Returns ------- model : keras.Model Constructed model. """ model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3),...
0.001111
def list_available_events(self, event_ids=None, event_type_ids=None, event_status=None, session=None, lightweight=None): """ Search for events that have live score data available. :param list event_ids: Optionally restricts the results to the specified event IDs ...
0.008114
def Lastovka_solid(T, similarity_variable): r'''Calculate solid constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. .. math:: C_p = 3(A_1\alpha + A_2\alpha^2)R\left(\frac{\theta}{T}\right)^2 \frac{\exp(\theta/T)}{[\exp(\theta/T)-1]^2} +...
0.002103
async def get_word(self, term: str) -> 'asyncurban.word.Word': """Gets the first matching word available. Args: term: The word to be defined. Returns: The closest matching :class:`Word` from UrbanDictionary. Raises: UrbanConn...
0.010889
def axis_bounds(self) -> Dict[str, Tuple[float, float]]: """ The (minimum, maximum) bounds for each axis. """ return {ax: (0, pos+0.5) for ax, pos in _HOME_POSITION.items() if ax not in 'BC'}
0.008969
def _process_morbidmap(self, limit): """ This will process the morbidmap file to get the links between omim genes and diseases. Here, we create anonymous nodes for some variant loci that are variants of the gene that causes the disease. Triples created: <some_anonymous_va...
0.001704
def GetEnabledInterfaces(): """Gives a list of enabled interfaces. Should work on all windows versions. Returns: interfaces: Names of interfaces found enabled. """ interfaces = [] show_args = ['/c', 'netsh', 'show', 'interface'] # pylint: disable=undefined-variable res = client_utils_common.Execute( ...
0.016367
def abort(message, *args): '''Raise an AbortException, halting task execution and exiting.''' if args: raise _AbortException(message.format(*args)) raise _AbortException(message)
0.027174
def create_single_poll(self, polls_question, polls_description=None): """ Create a single poll. Create a new poll for the current user """ path = {} data = {} params = {} # REQUIRED - polls[question] """The title of the poll.""" ...
0.004802
def write_interactions(G, path, delimiter=' ', encoding='utf-8'): """Write a DyNetx graph in interaction list format. Parameters ---------- G : graph A DyNetx graph. path : basestring The desired output filename delimiter : character ...
0.002155
def _createunbound(kls, **info): """Create a new UnboundNode representing a given class.""" if issubclass(kls, Bitfield): nodetype = UnboundBitfieldNode elif hasattr(kls, '_fields_'): nodetype = UnboundStructureNode elif issubclass(kls, ctypes.Array): nodetype = UnboundArray...
0.007194
def bytes_dict_cast(dict_, include_keys=True, include_vals=True, **kwargs): """ Converts any string-like items in input dict to bytes-like values, with respect to python version Parameters ---------- dict_ : dict any string-like objects contained in the dict will be converted to bytes ...
0.004667
def _draw_rectangle(context, width, height): """Draw a rectangle Assertion: The current point is the center point of the rectangle :param context: Cairo context :param width: Width of the rectangle :param height: Height of the rectangle """ c = context #...
0.00361
def load_lc_data(filename, indep, dep, indweight=None, mzero=None, dir='./'): """ load dictionary with lc data """ if '/' in filename: path, filename = os.path.split(filename) else: # TODO: this needs to change to be directory of the .phoebe file path = dir load_file = ...
0.009116
def apply(self, resource): """ Apply filter to resource :param resource: Image :return: Image """ if not isinstance(resource, Image.Image): raise ValueError('Unknown resource format') original_width, original_height = resource.size if self.st...
0.002083
def process_config_dict(self, key, d, level): """ Process the CONFIG block """ lines = [] for k, v in d.items(): k = "CONFIG {}".format(self.quoter.add_quotes(k.upper())) v = self.quoter.add_quotes(v) lines.append(self.__format_line(self.whites...
0.00551
def find_parents(root, path, names): """Find files matching the given names relative to the given path. Args: path (str): The file path to start searching up from. names (List[str]): The file/directory names to look for. root (str): The directory at which to stop recursing upwards. ...
0.003481
def login(username): """ return user """ from uliweb.utils.date import now from uliweb import request User = get_model('user') if isinstance(username, (str, unicode)): user = User.get(User.c.username==username) else: user = username user.last_login = no...
0.005195
def plot_discrete_cdf(xs, ys, ax=None, xlabel=None, ylabel=None, label=None): """ Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-axis shows the cumulative probability. Parameters ---------- xs : list-like of scalars ...
0.000768
def add(name, password=None, fullname=None, description=None, groups=None, home=None, homedrive=None, profile=None, logonscript=None): ''' Add a user to the minion. Args: name (str): User name password (str, optional): User's ...
0.000827
def wavg(datalist, fast=False, prior=None, **fitterargs): """ Weighted average of |GVar|\s or arrays/dicts of |GVar|\s. The weighted average of ``N`` |GVar|\s :: xavg = wavg([g1, g2 ... gN]) is what one obtains from a weighted least-squares fit of the collection of |GVar|\s to the one-paramet...
0.003538
def exec_command(attr, cmd): """Runs a subproc to calculate a package attribute. """ import subprocess p = popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode: from rez.exceptions import InvalidPackageError raise InvalidPackageE...
0.002288
def _varscan_paired(align_bams, ref_file, items, target_regions, out_file): """Run a paired VarScan analysis, also known as "somatic". """ max_read_depth = "1000" config = items[0]["config"] paired = get_paired_bams(align_bams, items) if not paired.normal_bam: affected_batch = items[0]["me...
0.003331
def add_item(self, item, **options): """ Add a layer or table item to the export. :param Layer|Table item: The Layer or Table to add :rtype: self """ export_item = { "item": item.url, } export_item.update(options) self.items.append(exp...
0.005731
def generate_index_file(filename): """Constructs a default home page for the project.""" with open(filename, 'w') as file: content = open(os.path.join(os.path.dirname(__file__), 'templates/index_page.html'), 'r').read() file.write(content)
0.007605
def call(self, url, func, data=None, headers=None, return_json=True, stream=False, retry=True, default_headers=True, quiet=False): '''call will issue the cal...
0.006102
def vap(x, a, b, c): """Vapor pressure model Parameters ---------- x: int a: float b: float c: float Returns ------- float np.exp(a+b/x+c*np.log(x)) """ return np.exp(a+b/x+c*np.log(x))
0.008097
def extract_session_details(request_headers, session_header, secret_key): ''' a method to extract and validate jwt session token from request headers :param request_headers: dictionary with header fields from request :param session_header: string with name of session token header key :p...
0.002123
def expand(self, url): """Base expand method. Only visits the link, and return the response url""" url = self.clean_url(url) response = self._get(url) if response.ok: return response.url raise ExpandingErrorException
0.007246
def _lookup_model(cls, kind, default_model=None): """Get the model class for the kind. Args: kind: A string representing the name of the kind to lookup. default_model: The model class to use if the kind can't be found. Returns: The model class for the requested kind. Raises: Ki...
0.003241
def juliandate(time: datetime) -> float: """ Python datetime to Julian time from D.Vallado Fundamentals of Astrodynamics and Applications p.187 and J. Meeus Astronomical Algorithms 1991 Eqn. 7.1 pg. 61 Parameters ---------- time : datetime.datetime time to convert Results ...
0.001085
def get_vm_full_path(self, si, vm): """ :param vm: vim.VirtualMachine :return: """ folder_name = None folder = vm.parent if folder: folder_name = folder.name folder_parent = folder.parent while folder_parent and folder_parent....
0.00485
def generate_map(map, name='url_map'): """ Generates a JavaScript function containing the rules defined in this map, to be used with a MapAdapter's generate_javascript method. If you don't pass a name the returned JavaScript code is an expression that returns a function. Otherwise it's a standalon...
0.000556
def deformat(value): """ REMOVE NON-ALPHANUMERIC CHARACTERS FOR SOME REASON translate CAN NOT BE CALLED: ERROR: translate() takes exactly one argument (2 given) File "C:\Python27\lib\string.py", line 493, in translate """ output = [] for c in value: if c in delchars: ...
0.010283
def float_str(value, order="pprpr", size=[4, 5, 3, 6, 4], after=False, max_denominator=1000000): """ Pretty string from int/float. "Almost" automatic string formatter for integer fractions, fractions of :math:`\pi` and float numbers with small number of digits. Outputs a representation among `...
0.004603
def _get_repos(self): """Gets a list of all the installed repositories in this server. """ result = {} for xmlpath in self.installed: repo = RepositorySettings(self, xmlpath) result[repo.name.lower()] = repo return result
0.006993
def add_analysis_attributes(self, group_name, attrs, clear=False): """ Add attributes on the group or dataset specified. :param group_name: The name of the group (or dataset). :param attrs: A dictionary representing the attributes to add. :param clear: If set, any existing attri...
0.00638
def process_view(self, request, view_func, *args, **kwargs): """Process view is executed before the view function, here we get the function name add set it as the span name. """ # Do not trace if the url is blacklisted if utils.disable_tracing_url(request.path, self.blacklist_pa...
0.002766
def SensorsDataPost(self, parameters): """ Post sensor data to multiple sensors in CommonSense simultaneously. @param parameters (dictionary) - Data to post to the sensors. @note - http://www.sense-os.nl/59?nodeId=59&selectedId=11887 ...
0.014129
def format_citation(citation, citation_type=None): """ This method may be built to support elements from different Tag Suite versions with the following tag names: citation, element-citation, mixed-citation, and nlm-citation The citation-type attribute is optional, and may also be empty; if it ...
0.003197