Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
388,600
def green(fn=None, consume_green_mode=True): def decorator(fn): @wraps(fn) def greener(obj, *args, **kwargs): args = (obj,) + args wait = kwargs.pop(, None) timeout = kwargs.pop(, None) access = kwargs.pop if consume_green_mode else kwargs.get ...
Make a function green. Can be used as a decorator.
388,601
def get(self, measurementId): logger.info( + measurementId) measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.COMPLETE) if measurement is not None: if measurement.inflate(): data = { name: { ...
Analyses the measurement with the given parameters :param measurementId: :return:
388,602
def _handle_sub_action(self, input_dict, handler): if not self.can_handle(input_dict): return input_dict key = self.intrinsic_name sub_value = input_dict[key] input_dict[key] = self._handle_sub_value(sub_value, handler) return input_dict
Handles resolving replacements in the Sub action based on the handler that is passed as an input. :param input_dict: Dictionary to be resolved :param supported_values: One of several different objects that contain the supported values that need to be changed. See each method above for speci...
388,603
def search(self, **kwargs): return super(ApiV4Neighbor, self).get(self.prepare_url( , kwargs))
Method to search neighbors based on extends search. :param search: Dict containing QuerySets to find neighbors. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to over...
388,604
def namedb_create(path, genesis_block): global BLOCKSTACK_DB_SCRIPT if os.path.exists( path ): raise Exception("Database already exists" % path) lines = [l + ";" for l in BLOCKSTACK_DB_SCRIPT.split(";")] con = sqlite3.connect( path, isolation_level=None, timeout=2**30 ) for line in...
Create a sqlite3 db at the given path. Create all the tables and indexes we need.
388,605
def generate_id_name_map(sdk, reverse=False): global_id_name_dict = {} global_name_id_dict = {} system_list = [] if_id_to_name = {} global_swi_id = {} global_ln_id = {} swi_to_wan_network_dict = {} swi_to_site_dict = {} wan_network_to_swi_dict = {} all_anynets ...
Generate the ID-NAME map dict :param sdk: CloudGenix API constructor :param reverse: Generate reverse name-> ID map as well, return tuple with both. :return: ID Name dictionary
388,606
def qs(schema): def wrapper(func): setattr(func, QS, schema) return func return wrapper
Decorate a function with a query string schema.
388,607
def fractional(value): 1/31 3/101/31 try: number = float(value) except (TypeError, ValueError): return value wholeNumber = int(number) frac = Fraction(number - wholeNumber).limit_denominator(1000) numerator = frac._numerator denominator = frac._denominator if wholeNumber ...
There will be some cases where one might not want to show ugly decimal places for floats and decimals. This function returns a human readable fractional number in form of fractions and mixed fractions. Pass in a string, or a number or a float, and this function returns a string represent...
388,608
def _GetDiscoveryDocFromFlags(args): if args.discovery_url: try: return util.FetchDiscoveryDoc(args.discovery_url) except exceptions.CommunicationError: raise exceptions.GeneratedClientError( ) infile = os.path.expanduser(args.infile) or with io...
Get the discovery doc from flags.
388,609
def get_trace(self, frame, tb): import linecache frames = [] stack, _ = self.get_stack(frame, tb) current = 0 for i, (stack_frame, lno) in enumerate(stack): code = stack_frame.f_code filename = code.co_filename or line = None ...
Get a dict of the traceback for wdb.js use
388,610
def setref(graphtable=None, comptable=None, thermtable=None, area=None, waveset=None): global GRAPHTABLE, COMPTABLE, THERMTABLE, PRIMARY_AREA, GRAPHDICT, COMPDICT, THERMDICT GRAPHDICT = {} COMPDICT = {} THERMDICT = {} kwds=set([graphtable,comptable,thermtable,area,waveset]) ...
Set default graph and component tables, primary area, and wavelength set. This is similar to setting ``refdata`` in IRAF STSDAS SYNPHOT. If all parameters set to `None`, they are reverted to software default. If any of the parameters are not `None`, they are set to desired values while the rest (if...
388,611
def _resolve_input(variable, variable_name, config_key, config): if variable is None: try: variable = config.get(PROFILE, config_key) except NoOptionError: raise ValueError(( ).format(variable_name)) return variable
Resolve input entered as option values with config values If option values are provided (passed in as `variable`), then they are returned unchanged. If `variable` is None, then we first look for a config value to use. If no config value is found, then raise an error. Parameters ---------- ...
388,612
def view_packages(self, *args): ver = GetFromInstalled(args[1]).version() print(" {0}{1}{2}{3} {4}{5} {6}{7}{8}{9}{10}{11:>11}{12}".format( args[0], args[1] + ver, self.meta.color["ENDC"], " " * (23-len(args[1] + ver)), args[2], " " * (18-len(args[2])), args...
:View slackbuild packages with version and arch args[0] package color args[1] package args[2] version args[3] arch
388,613
def _mark_image_file_deleted(cls, mapper, connection, target): cls._deleted_images.add((target, get_current_store()))
When the session flushes, marks images as deleted. The files of this marked images will be actually deleted in the image storage when the ongoing transaction succeeds. If it fails the :attr:`_deleted_images` queue will be just empty.
388,614
def pivot(self): self.op_data = [list(i) for i in zip(*self.ip_data)]
transposes rows and columns
388,615
def fill_view(self, view): other = view.hist _other_x_center = other.axis(0).GetBinCenter _other_y_center = other.axis(1).GetBinCenter _other_z_center = other.axis(2).GetBinCenter _other_get = other.GetBinContent _other_get_bin = super(_HistBase, other).GetBin ...
Fill this histogram from a view of another histogram
388,616
def total_branches(self): exit_counts = self.parser.exit_counts() return sum([count for count in exit_counts.values() if count > 1])
How many total branches are there?
388,617
def call_fn(fn: TransitionOperator, args: Union[Tuple[Any], Any]) -> Any: if isinstance(args, (list, tuple)) and not mcmc_util.is_namedtuple_like(args): args = args return fn(*args) else: return fn(args)
Calls a transition operator with args, unpacking args if its a sequence. Args: fn: A `TransitionOperator`. args: Arguments to `fn` Returns: ret: Return value of `fn`.
388,618
def identify_needed_data(curr_exe_job, link_job_instance=None): data_lengths, valid_chunks = curr_exe_job.get_valid_times() valid_lengths = [abs(valid_chunk) for valid_chunk in valid_chunks] if link_job_instance: start_data...
This function will identify the length of data that a specific executable needs to analyse and what part of that data is valid (ie. inspiral doesn't analyse the first or last 64+8s of data it reads in). In addition you can supply a second job instance to "link" to, which will ensure that the two jobs w...
388,619
def find_out_var(self, varnames=[]): if self.wdir != : stdout = "%s/%s"%(self.wdir, self.stdout) else: stdout = self.stdout response = [None]*len(varnames) if os.path.exists(stdout): with open_(stdout, ) as f: for line in f: if ...
This function will read the standard out of the program, catch variables and return the values EG. #varname=value
388,620
def handle(self): database = self.option("database") self.resolver.set_default_connection(database) repository = DatabaseMigrationRepository(self.resolver, "migrations") migrator = Migrator(repository, self.resolver) if not migrator.repository_exists(): r...
Executes the command.
388,621
def rate_of_return(period_ret, base_period): period_len = period_ret.name conversion_factor = (pd.Timedelta(base_period) / pd.Timedelta(period_len)) return period_ret.add(1).pow(conversion_factor).sub(1)
Convert returns to 'one_period_len' rate of returns: that is the value the returns would have every 'one_period_len' if they had grown at a steady rate Parameters ---------- period_ret: pd.DataFrame DataFrame containing returns values with column headings representing the return per...
388,622
def read(self, size=-1): if self.connected is None: return None data = self._get_input(size) return data
! @brief Return bytes read from the connection.
388,623
def find_or_graft(self, board): is_duplicate_board = True node = self for p, new_tile in board.positions_with_tile(): found_tile = False for child in node.children: if child.tile == new_tile: n...
Build a tree with each level corresponding to a fixed position on board. A path of tiles is stored for each board. If any two boards have the same path, then they are the same board. If there is any difference, a new branch will be created to store that path. Return: True if board alrea...
388,624
def InitUI(self): self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.init_grid_headers() self.grid_builder = GridBuilder(self.er_magic, self.grid_type, self.grid_headers, self.panel, self.parent_type) self.grid = self.grid_builder.make_grid()...
initialize window
388,625
def code_from_ipynb(nb, markdown=False): code = PREAMBLE for cell in nb[]: if cell[] == : code += .join(cell[]) if cell[] == : code += + .join(cell[]) code += return code
Get the code for a given notebook nb is passed in as a dictionary that's a parsed ipynb file
388,626
def animation_dialog(images, delay_s=1., loop=True, **kwargs): def _as_pixbuf(image): if isinstance(image, types.StringTypes): return gtk.gdk.pixbuf_new_from_file(image) else: return image pixbufs = map(_as_pixbuf, images) gtk.gdk.threads_init() dialo...
.. versionadded:: v0.19 Parameters ---------- images : list Filepaths to images or :class:`gtk.Pixbuf` instances. delay_s : float, optional Number of seconds to display each frame. Default: ``1.0``. loop : bool, optional If ``True``, restart animation after last ima...
388,627
def write_puml(self, filename=): def get_type(o): type = if isinstance(o, AbstractSensor): type = elif isinstance(o, AbstractActuator): type = return type if filename: s = open(filename, ) el...
Writes PUML from the system. If filename is given, stores result in the file. Otherwise returns result as a string.
388,628
def encrypt(passwd): m = sha1() salt = hexlify(os.urandom(salt_len)) m.update(unicode2bytes(passwd) + salt) crypted = bytes2unicode(salt) + m.hexdigest() return crypted
Encrypts the incoming password after adding some salt to store it in the database. @param passwd: password portion of user credentials @type passwd: string @returns: encrypted/salted string
388,629
def find_first_file_with_ext(base_paths, prefix, exts): for base_path in base_paths: for ext in exts: filename = os.path.join(base_path, "%s%s" % (prefix, ext)) if os.path.exists(filename) and os.path.isfile(filename): logger.debug("Found first file with relevant...
Runs through the given list of file extensions and returns the first file with the given base path and extension combination that actually exists. Args: base_paths: The base paths in which to search for files. prefix: The filename prefix of the file for which to search. exts: An ordered...
388,630
def update(self, dt): self.translate(dt * self.velocity) self.rotate(dt * self.angular_velocity)
Update the shape's position by moving it forward according to its velocity. Parameters ---------- dt : float
388,631
def parse_bug_activity(raw_html): def is_activity_empty(bs): EMPTY_ACTIVITY = "No changes have been made to this (?:bug|issue) yet." tag = bs.find(text=re.compile(EMPTY_ACTIVITY)) return tag is not None def find_activity_table(bs): t...
Parse a Bugzilla bug activity HTML stream. This method extracts the information about activity from the given HTML stream. The bug activity is stored into a HTML table. Each parsed activity event is returned into a dictionary. If the given HTML is invalid, the method will raise a Parse...
388,632
def respond(self, output): response = {: output.code, : output.log} self.send_response(200) self.send_header(, ) self.end_headers() self.wfile.write(bytes(json.dumps(response), "utf8"))
Generates server response.
388,633
def V(self, brightest=False): mags = self.get_photometry(brightest=brightest, convert=False) VT, dVT = mags[] BT, dBT = mags[] if (-0.25 < BT - VT < 2.0): (a, b, c, d) = (0.00097, 0.1334, 0.05486, 0.01998) V = (VT + a - b * (BT - VT) + c * (BT - VT)**2 - ...
http://www.aerith.net/astro/color_conversion.html
388,634
def extend(self, *args, **kwargs): if len(args) > 1: raise TypeError("extend() takes at most 1 positional " "arguments ({0} given)".format(len(args))) other = args[0] if len(args) >= 1 else () if isinstance(other, HTTPHeaderDict): for...
Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__
388,635
def isclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False): def within_tol(x, y, atol, rtol): with np.errstate(invalid=): result = np.less_equal(abs(x-y), atol + rtol * abs(y)) if np.isscalar(a) and np.isscalar(b): result = bool(result) return resul...
Returns a boolean array where two arrays are element-wise equal within a tolerance. This function is essentially a copy of the `numpy.isclose` function, with different default tolerances and one minor changes necessary to deal correctly with quaternions. The tolerance values are positive, typicall...
388,636
def create(cls, second_line, name_on_card, alias=None, type_=None, pin_code_assignment=None, monetary_account_id_fallback=None, custom_headers=None): if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_SECOND_LINE: sec...
Create a new debit card request. :type user_id: int :param second_line: The second line of text on the card, used as name/description for it. It can contain at most 17 characters and it can be empty. :type second_line: str :param name_on_card: The user's name as it will ...
388,637
def H(self, phase, T): try: return self._phases[phase].H(T) except KeyError: raise Exception("The phase was not found in compound ." .format(phase, self.formula))
Calculate the enthalpy of a phase of the compound at a specified temperature. :param phase: A phase of the compound, e.g. 'S', 'L', 'G'. :param T: [K] temperature :returns: [J/mol] Enthalpy.
388,638
def add_entity(self): post_data = self.get_post_data() if in post_data: if post_data[] == : self.add_pic(post_data) elif post_data[] == : self.add_pdf(post_data) elif post_data[] == : self.add_url(post_data) ...
Add the entity. All the information got from the post data.
388,639
def __construct_claim_json(self): def handle_qualifiers(old_item, new_item): if not new_item.check_qualifier_equality: old_item.set_qualifiers(new_item.get_qualifiers()) def is_good_ref(ref_block): if len(WDItemEngine.databases) == 0: W...
Writes the properties from self.data to a new or existing json in self.wd_json_representation :return: None
388,640
def isNonPairTag(self, isnonpair=None): if isnonpair is None: return self._isnonpairtag if not self._istag: return if isnonpair: self.endtag = None self.childs = [] self._isnonpairtag = isnonpair
True if element is listed in nonpair tag table (``br`` for example) or if it ends with ``/>`` (``<hr />`` for example). You can also change state from pair to nonpair if you use this as setter. Args: isnonpair (bool, default None): If set, internal nonpair state is ...
388,641
def save(self, sc, path): java_model = sc._jvm.org.apache.spark.mllib.classification.LogisticRegressionModel( _py2java(sc, self._coeff), self.intercept, self.numFeatures, self.numClasses) java_model.save(sc._jsc.sc(), path)
Save this model to the given path.
388,642
def get_rup_array(ebruptures, srcfilter=nofilter): if not BaseRupture._code: BaseRupture.init() rups = [] geoms = [] nbytes = 0 offset = 0 for ebrupture in ebruptures: rup = ebrupture.rupture mesh = surface_to_array(rup.surface) sy, sz = mesh.shape[1:] ...
Convert a list of EBRuptures into a numpy composite array, by filtering out the ruptures far away from every site
388,643
def fixed_poch(a, n): if (int(n) != n) or (n < 0): raise ValueError("Parameter n must be a nonnegative int!") n = int(n) terms = [a + k for k in range(0, n)] return scipy.prod(terms)
Implementation of the Pochhammer symbol :math:`(a)_n` which handles negative integer arguments properly. Need conditional statement because scipy's impelementation of the Pochhammer symbol is wrong for negative integer arguments. This function uses the definition from http://functions.wolfram.com/G...
388,644
def calculate_start_time(df): if "time" in df: df["time_arr"] = pd.Series(df["time"], dtype=) elif "timestamp" in df: df["time_arr"] = pd.Series(df["timestamp"], dtype="datetime64[ns]") else: return df if "dataset" in df: for dset in df["dataset"].unique(): ...
Calculate the star_time per read. Time data is either a "time" (in seconds, derived from summary files) or a "timestamp" (in UTC, derived from fastq_rich format) and has to be converted appropriately in a datetime format time_arr For both the time_zero is the minimal value of the time_arr, whi...
388,645
def load_time_series(filename, delimiter=r): r times, values = load_delimited(filename, [float, float], delimiter) times = np.array(times) values = np.array(values) return times, values
r"""Import a time series from an annotation file. The file should consist of two columns of numeric values corresponding to the time and value of each sample of the time series. Parameters ---------- filename : str Path to the annotation file delimiter : str Separator regular e...
388,646
def find_category(self, parent_alias, title): found = None child_ids = self.get_child_ids(parent_alias) for cid in child_ids: category = self.get_category_by_id(cid) if category.title.lower() == title.lower(): found = category brea...
Searches parent category children for the given title (case independent). :param str parent_alias: :param str title: :rtype: Category|None :return: None if not found; otherwise - found Category
388,647
def init( dist=, minver=None, maxver=None, use_markdown_readme=True, use_stdeb=False, use_distribute=False, ): if not minver == maxver == None: import sys if not minver <= sys.version < (maxver or ): sys.stderr.write( % ( ...
Imports and returns a setup function. If use_markdown_readme is set, then README.md is added to setuptools READMES list. If use_stdeb is set on a Debian based system, then module stdeb is imported. Stdeb supports building deb packages on Debian based systems. The package should only be install...
388,648
def calc_percentile_interval(self, conf_percentage): alpha = bc.get_alpha_from_conf_percentage(conf_percentage) single_column_names =\ [.format(alpha / 2.0), .format(100 - alpha / 2.0)] conf_intervals =\ bc.calc_percentile_...
Calculates percentile bootstrap confidence intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. ...
388,649
def monkey_patch(enabled=True): if enabled: Image.open = imdirect_open else: Image.open = pil_open
Monkey patching PIL.Image.open method Args: enabled (bool): If the monkey patch should be activated or deactivated.
388,650
def _variants(self, case_id, gemini_query): individuals = [] case_obj = self.case(case_id) for individual in case_obj.individuals: individuals.append(individual) self.db = case_obj.variant_source self.variant_type = case_obj.variant_type gq...
Return variants found in the gemini database Args: case_id (str): The case for which we want to see information gemini_query (str): What variants should be chosen filters (dict): A dictionary with filters Yields: variant_obj (dict...
388,651
def init(self, force_deploy=False, client=None): _force_deploy = self.provider_conf.force_deploy self.provider_conf.force_deploy = _force_deploy or force_deploy self._provider_conf = self.provider_conf.to_dict() r = api.Resources(self._provider_conf, client=client) r.lau...
Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be redeployed Raises: MissingNetworkError: If ...
388,652
def path(self): if self._root_dir is None: override_buildroot = os.environ.get(, None) if override_buildroot: self._root_dir = override_buildroot else: self._root_dir = os.path.realpath(self.find_buildroot()) if PY2: self._root_dir = self._root_dir.decode(...
Returns the build root for the current workspace.
388,653
def _check_params(self,params): overridden_object_params = list(self._overridden.param) for item in params: if item not in overridden_object_params: self.param.warning(" will be ignored (not a Parameter).",item)
Print a warning if params contains something that is not a Parameter of the overridden object.
388,654
def validate_backup_window(window): hour = r minute = r r = ("(?P<start_hour>%s):(?P<start_minute>%s)-" "(?P<end_hour>%s):(?P<end_minute>%s)") % (hour, minute, hour, minute) range_regex = re.compile(r) m = range_regex.match(window) if not m: raise ValueError("DBInstance Pr...
Validate PreferredBackupWindow for DBInstance
388,655
def get_message_headers(self, section: Sequence[int] = None, subset: Collection[bytes] = None, inverse: bool = False) -> Writeable: ...
Get the headers from the message or a ``message/rfc822`` sub-part of the message.. The ``section`` argument can index a nested sub-part of the message. For example, ``[2, 3]`` would get the 2nd sub-part of the message and then index it for its 3rd sub-part. Args: se...
388,656
def get_stack_refs(refs: list): refs = list(refs) refs.reverse() stack_refs = [] last_stack = None while refs: ref = refs.pop() if last_stack is not None and re.compile(r).match(ref): stack_refs.append(StackReference(last_stack, ref)) else: try:...
Returns a list of stack references with name and version.
388,657
def getBinding(self): wsdl = self.getService().getWSDL() return wsdl.bindings[self.binding]
Return the Binding object that is referenced by this port.
388,658
def ReadClientCrashInfo(self, client_id): history = self.crash_history.get(client_id, None) if not history: return None ts = max(history) res = rdf_client.ClientCrash.FromSerializedString(history[ts]) res.timestamp = ts return res
Reads the latest client crash record for a single client.
388,659
def _objective_decorator(func): def inner(preds, dmatrix): labels = dmatrix.get_label() return func(labels, preds) return inner
Decorate an objective function Converts an objective function using the typical sklearn metrics signature so that it is usable with ``xgboost.training.train`` Parameters ---------- func: callable Expects a callable with signature ``func(y_true, y_pred)``: y_true: array_like of sha...
388,660
def almost_unitary(gate: Gate) -> bool: res = (gate @ gate.H).asoperator() N = gate.qubit_nb return np.allclose(asarray(res), np.eye(2**N), atol=TOLERANCE)
Return true if gate tensor is (almost) unitary
388,661
def zsymDecorator(odd): def wrapper(func): @wraps(func) def zsym_wrapper(*args,**kwargs): if args[0]._zsym: out= func(args[0],args[1],numpy.fabs(args[2]),**kwargs) else: out= func(*args,**kwargs) if odd and args[0]._zsym: ...
Decorator to deal with zsym=True input; set odd=True if the function is an odd function of z (like zforce)
388,662
def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False): sections = [] optional_header_offset = imageDosHeader.header.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER) offset = optional_header_offset + imageNtHeaders.header.FileHeader.SizeOfOptionalHeader ...
Parses the sections in the memory and returns a list of them
388,663
def see(obj=DEFAULT_ARG, *args, **kwargs): use_locals = obj is DEFAULT_ARG if use_locals: try: prop = getattr(obj, attr) except (AttributeError, Exception): prop = SeeError() action = output.display_name(name=attr, obj=prop, local=use_locals) ...
see(obj=anything) Show the features and attributes of an object. This function takes a single argument, ``obj``, which can be of any type. A summary of the object is printed immediately in the Python interpreter. For example:: >>> see([]) [] in + ...
388,664
def set_evernote_spec(): spec = NoteStore.NotesMetadataResultSpec() spec.includeTitle = True spec.includeAttributes = True return spec
set the spec of the notes :return: spec
388,665
def _firmware_update(firmwarefile=, host=, directory=): dest = os.path.join(directory, firmwarefile[7:]) __salt__[](firmwarefile, dest) username = __pillar__[][] password = __pillar__[][] __salt__[](dest, host=host, ...
Update firmware for a single host
388,666
def vm_detach_nic(name, kwargs=None, call=None): if call != : raise SaltCloudSystemExit( ) if kwargs is None: kwargs = {} nic_id = kwargs.get(, None) if nic_id is None: raise SaltCloudSystemExit( nic_id\ ) server, user, passwor...
Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1
388,667
def calculate_z2pt5_ngaw2(vs30): NGA-West2 ground motion model for the average horizontal components of PGA, PGV, and 5pct damped linear acceleration response spectra. c1 = 7.089 c2 = -1.144 z2pt5 = numpy.exp(c1 + numpy.log(vs30) * c2) return z2pt5
Reads an array of vs30 values (in m/s) and returns the depth to the 2.5 km/s velocity horizon (in km) Ref: Campbell, K.W. & Bozorgnia, Y., 2014. 'NGA-West2 ground motion model for the average horizontal components of PGA, PGV, and 5pct damped linear acceleration response spectra.' Earthquake Spectra...
388,668
def crick_angles(p, reference_axis, tag=True, reference_axis_name=): if not len(p) == len(reference_axis): raise ValueError( "The reference axis must contain the same number of points" " as the Polymer primitive.") prim_cas = p.primitive.coordinates p_cas = p.get_referen...
Returns the Crick angle for each CA atom in the `Polymer`. Notes ----- The final value is in the returned list is `None`, since the angle calculation requires pairs of points on both the primitive and reference_axis. Parameters ---------- p : ampal.Polymer Reference `Polymer`. ...
388,669
def digest(self): A = self.A B = self.B C = self.C D = self.D input = [] + self.input count = [] + self.count index = (self.count[0] >> 3) & 0x3f if index < 56: padLen = 56 - index else: padLen = 120 - index padding = [b] + [b] * 63 self.update(padding[:p...
Terminate the message-digest computation and return digest. Return the digest of the strings passed to the update() method so far. This is a 16-byte string which may contain non-ASCII characters, including null bytes.
388,670
def canonicalize_id(reference_id): if u in reference_id: return reference_id.replace(u, u) m = _C14N_PATTERN.match(reference_id) if m: origin = m.group(1) return reference_id.replace(origin, _C14N_FIXES[origin]) return MALFORMED_CABLE_IDS.get(reference_id, INVALID_CABLE_IDS....
\ Returns the canonicalized form of the provided reference_id. WikiLeaks provides some malformed cable identifiers. If the provided `reference_id` is not valid, this method returns the valid reference identifier equivalent. If the reference identifier is valid, the reference id is returned unchanged. ...
388,671
def decode_list(self, integers): integers = list(np.squeeze(integers)) return self.encoders["inputs"].decode_list(integers)
List of ints to list of str.
388,672
def encode(self, raw=False): buf = b"" if raw: for tag, value in self.pairs: buf += tag + b + value + SOH_STR return buf for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue ...
Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type ...
388,673
def destroyTempFiles(self): os.system("rm -rf %s" % self.rootDir) logger.debug("Temp files created: %s, temp files actively destroyed: %s" % (self.tempFilesCreated, self.tempFilesDestroyed))
Destroys all temp temp file hierarchy, getting rid of all files.
388,674
def forward(self, src_seq, tgt_seq, src_valid_length=None, tgt_valid_length=None): additional_outputs = [] encoder_outputs, encoder_additional_outputs = self.encode(src_seq, valid_length=src_valid_length) decoder_states...
Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArray src_valid_length : NDArray or None tgt_valid_length : NDArray or None Returns ------- ...
388,675
def returner(ret): librato_conn = _get_librato(ret) q = librato_conn.new_queue() if ret[] == : log.debug() stats = _calculate_runtimes(ret[]) log.debug(, ret[]) q.add(, ret[], tags={: ret[]}) log.debug( , stats[] ...
Parse the return data and return metrics to Librato.
388,676
def extractInputForTP(self, tm): burstingColumns = tm.activeState["t"].sum(axis=1) burstingColumns[ burstingColumns < tm.cellsPerColumn ] = 0 burstingColumns[ burstingColumns == tm.cellsPerColumn ] = 1 correctlyPredictedCells = numpy.zeros(self._inputDimensions).astype(realDType) ...
Extract inputs for TP from the state of temporal memory three information are extracted 1. correctly predicted cells 2. all active cells 3. bursting cells (unpredicted input)
388,677
def fromfits(infile, hdu = 0, verbose = True): pixelarray, hdr = ft.getdata(infile, hdu, header=True) pixelarray = np.asarray(pixelarray).transpose() pixelarrayshape = pixelarray.shape if verbose : print "Input shape : (%i, %i)" % (pixelarrayshape[0], pixelarrayshape[1]) ...
Factory function that reads a FITS file and returns a f2nimage object. Use hdu to specify which HDU you want (primary = 0)
388,678
def rpush(self, key, value, *values): return self.execute(b, key, value, *values)
Insert all the specified values at the tail of the list stored at key.
388,679
def connection_from_promised_list(data_promise, args=None, **kwargs): return data_promise.then(lambda data: connection_from_list(data, args, **kwargs))
A version of `connectionFromArray` that takes a promised array, and returns a promised connection.
388,680
def get_endpoint_path(self, endpoint_id): s home from the globus config file. This function is fragile but I don config = os.path.expanduser("~/.globusonline/lta/config-paths") if not os.path.exists(config): bot.error() sys.exit(1) path = None config = [x.split()[0] fo...
return the first fullpath to a folder in the endpoint based on expanding the user's home from the globus config file. This function is fragile but I don't see any other way to do it. Parameters ========== endpoint_id: the endpoint id to look up the path for
388,681
def on_disconnect(self, client, userdata, result_code): self.log_info("Disconnected with result code " + str(result_code)) self.state_handler.set_state(State.goodbye) time.sleep(5) self.thread_handler.run(target=self.start_blocking)
Callback when the MQTT client is disconnected. In this case, the server waits five seconds before trying to reconnected. :param client: the client being disconnected. :param userdata: unused. :param result_code: result code.
388,682
def shutdown(): global _sdk_ref_count global _sdk_instance global _should_shutdown with _sdk_ref_lk: logger.debug("shutdown: ref count = %d, should_shutdown = %s", \ _sdk_ref_count, _should_shutdown) nsdk = nativeagent.try_get_sdk() if not nsdk: ...
Shut down the SDK. :returns: An exception object if an error occurred, a falsy value otherwise. :rtype: Exception
388,683
def getmembers_static(cls): names = set() for scope in cls.scopes: names.update(structured.getmembers_static(scope)) return names
Gets members (vars) from all scopes using ONLY static information. You most likely want to use ScopeStack.getmembers instead. Returns: Set of available vars. Raises: NotImplementedError if any scope fails to implement 'getmembers'.
388,684
def html_to_rgb(html): html = html.strip().lower() if html[0]==: html = html[1:] elif html in NAMED_COLOR: html = NAMED_COLOR[html][1:] if len(html)==6: rgb = html[:2], html[2:4], html[4:] elif len(html)==3: rgb = [ % (v,v) for v in html] else: raise ValueError("input return tupl...
Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither a known color name or a hex...
388,685
def _impl(lexer): p = _sumterm(lexer) tok = next(lexer) if isinstance(tok, OP_rarrow): q = _impl(lexer) return (, p, q) elif isinstance(tok, OP_lrarrow): q = _impl(lexer) return (, p, q) else: lexer.unpop_token(tok) return p
Return an Implies expression.
388,686
def tracebacks_from_lines(lines_iter): tbgrep = TracebackGrep() for line in lines_iter: tb = tbgrep.process(line) if tb: yield tb
Generator that yields tracebacks found in a lines iterator The lines iterator can be: - a file-like object - a list (or deque) of lines. - any other iterable sequence of strings
388,687
def get_command(self, ctx, name): if not hasattr(self.resource, name): return None method = getattr(self.resource, name) attrs = getattr(method, , {}) help_text = inspect.getdoc(method) ...
Retrieve the appropriate method from the Resource, decorate it as a click command, and return that method.
388,688
def isVideo(self): val=False if self.__dict__[]: if self.codec_type == : val=True return val
Is the stream labelled as a video stream.
388,689
def geometry_from_grid(self, grid, pixel_centres, pixel_neighbors, pixel_neighbors_size, buffer=1e-8): y_min = np.min(grid[:, 0]) - buffer y_max = np.max(grid[:, 0]) + buffer x_min = np.min(grid[:, 1]) - buffer x_max = np.max(grid[:, 1]) + buffer shape_arcsec = (y_max - ...
Determine the geometry of the Voronoi pixelization, by alligning it with the outer-most coordinates on a \ grid plus a small buffer. Parameters ----------- grid : ndarray The (y,x) grid of coordinates which determine the Voronoi pixelization's geometry. pixel_centres...
388,690
def set_site_energies( self, energies ): self.site_energies = energies for site_label in energies: for site in self.sites: if site.label == site_label: site.energy = energies[ site_label ]
Set the energies for every site in the lattice according to the site labels. Args: energies (Dict(Str:Float): Dictionary of energies for each site label, e.g.:: { 'A' : 1.0, 'B', 0.0 } Returns: None
388,691
def ReadFileObject(self, file_object): json_definitions = json.loads(file_object.read()) last_artifact_definition = None for json_definition in json_definitions: try: artifact_definition = self.ReadArtifactDefinitionValues(json_definition) except errors.FormatError as exceptio...
Reads artifact definitions from a file-like object. Args: file_object (file): file-like object to read from. Yields: ArtifactDefinition: an artifact definition. Raises: FormatError: if the format of the JSON artifact definition is not set or incorrect.
388,692
def unfreeze(self): for idx, child in enumerate(self.model.children()): mu.unfreeze_layer(child)
Unfreeze model layers
388,693
def start(self): resource_list = getattr(self, f) resource_action = getattr(resource_list, self.resource_action) resource_action(self.resource_name)
Execution happening on jhubctl.
388,694
def _make_3d(field, twod): shp = list(field.shape) if twod and in twod: shp.insert(1, 1) elif twod: shp.insert(0, 1) return field.reshape(shp)
Add a dimension to field if necessary. Args: field (numpy.array): the field that need to be 3d. twod (str): 'XZ', 'YZ' or None depending on what is relevant. Returns: numpy.array: reshaped field.
388,695
def mlp(feature, hparams, name="mlp"): with tf.variable_scope(name, "mlp", values=[feature]): num_mlp_layers = hparams.num_mlp_layers mlp_dim = hparams.mlp_dim for _ in range(num_mlp_layers): feature = common_layers.dense(feature, mlp_dim, activation=tf.nn.relu) feature = tf.nn.dropout(feat...
Multi layer perceptron with dropout and relu activation.
388,696
def typing(self, *, channel: str): payload = {"id": self._next_msg_id(), "type": "typing", "channel": channel} self.send_over_websocket(payload=payload)
Sends a typing indicator to the specified channel. This indicates that this app is currently writing a message to send to a channel. Args: channel (str): The channel id. e.g. 'C024BE91L' Raises: SlackClientNotConnectedError: Websocket connection is closed.
388,697
def getJson(url): site = urllib2.urlopen(url, timeout=300) return json.load(site)
Download json and return simplejson object
388,698
def create_vpn_gateway(self, type, availability_zone=None): params = { : type} if availability_zone: params[] = availability_zone return self.get_object(, params, VpnGateway)
Create a new Vpn Gateway :type type: str :param type: Type of VPN Connection. Only valid valid currently is 'ipsec.1' :type availability_zone: str :param availability_zone: The Availability Zone where you want the VPN gateway. :rtype: The newly created VpnGateway :ret...
388,699
def create_blocking_connection(host): return pika.BlockingConnection( amqpdaemon.getConParams( settings.get_amqp_settings()[host.lower()]["vhost"] ) )
Return properly created blocking connection. Args: host (str): Host as it is defined in :func:`.get_amqp_settings`. Uses :func:`edeposit.amqp.amqpdaemon.getConParams`.