input
stringlengths
2.65k
237k
output
stringclasses
1 value
> 0: c += self._layer_costs[i] self._budget.consumeBudget(self._layer_costs[i]) try: neighbors = set(list(self._graph[i].neighbors(u))) edges = [(u,v) for v in neighbors] self._sample[i].add_edges_from(edges) except: neighbors = [] self._queried[i].update([u]) self._unqueri...
colisão - ocupante não especificado de um ônibus traumatizado em um acidente não-de-trânsito'), ('V78.4', 'Ocupante de um ônibus traumatizado em um acidente de transporte sem colisão - pessoa traumatizado ao subir ou descer do veículo'), ('V78.5', 'Ocupante de um ônibus traumatizado em um acidente de transporte sem c...
while self.g_chkreplexit: try: if len(grtsps)>0: for key in grtsps: if grtsps[key].child.terminated: pass del grtsps[key] # else: # grtsps[key].write_contents() finally: pass if len(grtsps)>0: for key in grtsps: if grtsps[key].child.terminated: pass del grtsps[key] else: grtsps[key].child.terminate...
<filename>tests/myapp/modelsfinaldb.py # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Rem...
import copy from sqlalchemy import exc as sa_exc from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy import Integer from sqlalchemy import select from sqlalchemy import String from sqlalchemy import testing from sqlalchemy import util from sqlalchemy.orm import attributes from sqlalchemy.orm ...
<reponame>JunhoPark0314/FSCE # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from collections import defaultdict from fsdet.data.catalog import MetadataCatalog import logging from typing import Dict import numpy as np import torch from torch import nn import torch.nn.functional as F from fsdet.l...
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228, 'Renaming Unit/Peak Dynamic': 3.58947, 'Renaming Unit/Runtime Dynamic': 0.0622844, 'Renaming Unit/Subthreshold Leakage': 0.0552466, 'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461, 'Runtime Dynamic': 1.95773, '...
None """ The API OpenID """ openid_structure = None """ The OpenID structure """ diffie_hellman = None """ the Diffie Hellman management structure """ def __init__( self, api_openid_plugin = None, diffie_hellman_plugin = None, random_plugin = None, api_openid = None, openid_structure = Non...
<filename>flash/video/classification/data.py # Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
" Conditions: %s"%str(lc) raise Exception(msg) # Synthdiag-specific if synthdiag is True: ids = self.get_inputs_for_synthsignal(ids=ids, verb=False, returnas=list) lc[1] = True # Prepare dids[name] = {'ids':None/ids, 'needidd':bool} dids = {} if lc[0] or lc[1]: if lc[0]: ids = [ids] for ids_ in ids: if n...
we get the best set of parameters out, even if this error # comes up #def iterCallback(params, iter, resid, *args, **kwargs): # if iter >= maxEvalsList[i]: # Just kidding, I'll just use a try and ignore the error, since I # am pretty sure that the params variable is constantly updated, not just # at the end. t...
sees just theirs but we see both our old and new ones plus those we # have group access to self._asJoeBloggs() response = self._client.get('/tasks/') self.assertEqual(response.status_code, status.HTTP_200_OK) wflows = response.data self.assertEqual(len(wflows["results"]), 2) self._asJaneDoe() response = self._c...
ground_truth[i, :])) fdr_den = np.sum(importance_score[i, :]) fdr[i] = 100 * float(fdr_nom) / float(fdr_den + 1e-8) mean_tpr = np.mean(tpr) std_tpr = np.std(tpr) mean_fdr = np.mean(fdr) std_fdr = np.std(fdr) return mean_tpr, std_tpr, mean_fdr, std_fdr def quantile_discretizer(df, num, cat_cols): quantiles =...
<filename>pesummary/tests/conversion_test.py<gh_stars>1-10 # Licensed under an MIT style license -- see LICENSE.md import os import socket import shutil import numpy as np import h5py import deepdish from pesummary.gw.conversions import * from pesummary.gw.conversions.nrutils import * from pycbc import conversions ...
<gh_stars>0 # coding: utf-8 # In[ ]: """ Microkinetic model for ammonia oxidation Inspired by Grabow, <NAME>. "Computational catalyst screening." Computational Catalysis. RSC Publishing, 2013. 1-58. """ # In[ ]: import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt import pickle...
in time.") if all_equal is None: warnings.warn(f"Rate function {rate.__name__} couldn't be evaluated at more than one point or no point in time {t}") has_time_dependence = False else: has_time_dependence = not all_equal self.rates_have_explicit_time_dependence = \ self.rates_have_explicit_time_dependence or ha...
<reponame>mgiangreco/apartments-scraper import boto3 import csv import datetime import json import re import sys import datetime import requests import os from bs4 import BeautifulSoup # Config parser was renamed in Python 3 try: import configparser except ImportError: import ConfigParser as configparser def create...
############################################################################# # Analysis codes for mBLA_UF code # # # # Used in the paper: # # [1] Park and N{\"a}gele, JCP, 2020 # # doi: 10.1063/5.0020986 # # # # [2] Park and N{\"a}gele, Membranes, 2021 # # doi: https://doi.org/10.3390/membranes11120960 # # # # # # Cod...
# *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* # ** Copyright UCAR (c) 1992 - 2014 # ** University Corporation for Atmospheric Research(UCAR) # ** National Center for Atmospheric Research(NCAR) # ** P.O.Box 3000, Boulder, Colorado, 80307-3000, USA # ** See LICENSE.TXT for license detai...
import calendar from collections import defaultdict from datetime import datetime, timedelta from math import ceil import numpy from django.conf import settings from django.db.models import Count, Sum, F, Avg, FloatField, Case, When, IntegerField, Q, DateTimeField, ExpressionWrapper from django.db.models.functions imp...
""" This is adapt from evennia/evennia/commands/default/unloggedin.py. The licence of Evennia can be found in evennia/LICENSE.txt. """ import re import traceback import time import hashlib from collections import defaultdict from random import getrandbits from django.conf import settings from evennia.accounts.models i...
traced_fn1(x): return torch.neg(x) @_trace(torch.rand(3, 4)) def traced_fn(x): return traced_fn1(x) + 1 FileCheck().check("traced_fn").check("prim::CallFunction").check("aten::add") \ .run(str(traced_fn.graph)) @unittest.skip("error in first class mode") def test_call_traced_mod_from_tracing_fn(self): class...
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify,...
<reponame>jaipradeesh/PyRFC # -*- coding: utf-8 -*- # Copyright 2014 SAP AG. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http: //www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
from torch.nn import LSTM, Linear, BatchNorm1d, Parameter import torch import torch.nn as nn import torch.nn.functional as F class NoOp(nn.Module): def __init__(self): super().__init__() def forward(self, x): return x class STFT(nn.Module): def __init__( self, n_fft=4096, n_hop=1024, center=False ): sup...
# WAE model recon_error = Lambda(mean_reconstruction_l2sq_loss, name='mean_recon_error')([real_image, recon_image]) penalty_e = Lambda(get_qz_trick_loss, name='penalty_e')(q_e) penalty_b = Lambda(get_b_penalty_loss, name='penalty_b', arguments={'sigma':self.b_sd, 'zdim':self.b_z_dim, 'kernel':'RBF', 'p_z':'normal'}...
<reponame>egor5q/OlgaDmitrievna # -*- coding: utf-8 -*- import os import telebot import time import telebot import random import threading from emoji import emojize from telebot import types from pymongo import MongoClient import traceback import re import apiai import json import config from requests.exceptions imp...
<filename>_base/_imf_decomposition/_emd.py import numpy as np import scipy import scipy.interpolate #import Akima1DInterpolator, Rbf, InterpolatedUnivariateSpline, BSpline def emd(x, order,method = 'cubic', max_itter = 100, tol = 0.1): ''' Emperical Mode Decomposition (EMD). The emperical mode deocomposition m...
<reponame>mtik00/invoicer<filename>invoicer/_invoice/__init__.py import os import re from io import BytesIO import json import requests import arrow import pdfkit import htmlmin from pdfkit.configuration import Configuration from flask import ( Blueprint, request, redirect, url_for, render_template, flash, current_a...
<filename>sdk/python/pulumi_gitlab/instance_variable.py # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Map...
i in range(self._data.children_size()) }, self._mask, ) else: return self._fromdata( { self.dtype.fields[i].name: ColumnFromVelox._from_velox( self.device, self.dtype.fields[i].dtype, self._data.child_at(i), True, ) > other for i in range(self._data.children_size()) }, self._mask, ) def __le__(self, ...
support reduce_sum # encoder_out_lens = encoder_mask.squeeze(1).sum(1) encoder_out_lens = encoder_mask.squeeze(1).astype(paddle.int).sum(1) ctc_probs = self.ctc.log_softmax(encoder_out) # (B, maxlen, vocab_size) topk_prob, topk_index = ctc_probs.topk(1, axis=2) # (B, maxlen, 1) topk_index = topk_index.view(batch_...
missing EC files txt = MetabolicGraph.k.get("ec:" + valid_ecs) try: int(txt) except ValueError: open(joinP(dir_ec, "ec_" + name + ".txt"), "w").write(txt) else: #Complete download. Possible improvement (?) : with bash check if number of ec_ files in EC_files/ is the same as 'grep -l "EC:" '+ self.directory + '/*|...
<filename>tests/test_user_display.py import hashlib import hmac import json import uuid from buildpg import V, Values from datetime import date, datetime, timedelta, timezone from foxglove import glove from foxglove.db.helpers import SyncDb from operator import itemgetter from pytest_toolbox.comparison import RegexStr ...
partition_info = [(123, 'pepper', 't1', 4444), (234, 'pepper', 't2', 5555)] expected_output = ['pepper, t1, 10000000000000000', 'pepper, t2, 10000000000000000'] with self.assertRaisesRegexp(Exception, 'Exceeded backup max tuple count of 1 quadrillion rows per table for:'): get_partition_state(master_port, dbname, 'p...
<reponame>pvegdahl/AdventOfCode2021<gh_stars>0 import json import math from typing import Union, Tuple, NamedTuple, Optional, List import pytest @pytest.mark.parametrize( "input_string, expected", [ ("1", [1]), ("[1,2]", [(1, 2)]), ("[[[7,1],2],3]\n[[1,7],7]", [(((7, 1), 2), 3), ((1, 7), 7)]), ], ) def test_pa...
tr_widths=tr_widths, tr_spaces=tr_spaces) # Rows are ordered from bottom to top # To use TrackManager, an ordered list of wiring types and their locations must be provided. # Define two lists, one for the nch rows and one for the pch rows # The lists are composed of dictionaries, one per row. # Each dictionary ha...
species rowid in existing list') previous_species_rowids = None if previous_species_rowids is None: refresh = True current_species_rowids = ibs.get_annot_species_rowids(aid_list) species_count = [ len(current_species_rowids) - current_species_rowids.count(species_rowid) for species_rowid in species_rowids ] ...
+ net['id'])) return ext_net else: epg = self.aim_mgr.get( ctx, aim_res.EndpointGroup.from_dn( net['apic:distinguished_names']['EndpointGroup'])) return epg provider = get_net_group(dst_net, dst_cird) # Verify Flow Classifier mapping contract = self.aim_mgr.get( ctx, aim_res.Contract( tenant_name=apic_tn, ...
from Node import Node class LinkedList: def __init__(self, node=None): self.head = node def insertFront(self, newValue): # Debug toPrint = False newNode = Node(newValue) if toPrint: print("New Node value = " + str(newNode.value)) newNode.next = self.head if toPrint: print("New Node dot next = " + str(n...
'XA/XRF GRAYSCALE SOFTCOPY PRESENTATION STATE IOD': ['Patient'], 'RT DOSE IOD': ['Patient'], 'AMBULATORY ECG IOD': ['Patient'], 'SURFACE SEGMENTATION IOD': ['Patient'], 'MAMMOGRAPHY CAD SR IOD': ['Patient'], 'VL MICROSCOPIC IMAGE IOD': ['Patient'], 'RT BEAMS TREATMENT RECORD IOD': ['Patient'], 'DEFORMABLE SPATIA...
Citation.reference.startswith(q)) return jsonify([ { "text": citation.reference, "id": citation.id, } for citation in citations ]) @api_blueprint.route('/api/evidence/<int:evidence_id>') def get_evidence_by_id(evidence_id): """Get an evidence by its identifier as JSON.""" evidence = manager.get_evidence_by_...
<reponame>kmader/qbi-2019-py #!/usr/bin/env python # coding: utf-8 # # ETHZ: 227-0966-00L # # Quantitative Big Imaging # # March 28, 2019 # # ## Shape Analysis # In[1]: import seaborn as sns import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (8, 8) plt.rcParams["figure.dpi"] = 150 plt.rcParams["font....
<filename>src/franz/openrdf/tests/tests.py # coding=utf-8 ################################################################################ # Copyright (c) 2006-2017 Franz Inc. # All rights reserved. This program and the accompanying materials are # made available under the terms of the MIT License which accompanies # ...
<reponame>renatomello/qibo """Test special features of core gates.""" import pytest import numpy as np from qibo import K, gates from qibo.models import Circuit from qibo.tests.utils import random_state ####################### Test `_construct_unitary` feature ####################### GATES = [ ("H", (0,), np.array([...
= -1000. # This is the default reaction.upper_bound = 1000. # This is the default reaction.add_metabolites({glyc_SFOe: -1.0, glyc_e: SFO_Abnd}) model.add_reactions([reaction]) #glyc_SFOe <-> glyc_SFOc glyc_SFOc = Metabolite('glyc_SFOc', formula='C3H8O3', name='Glycerol', compartment='SFOc', charge= 0) react...
= \ harmonic_oscillator_continuous_prior_mean_Michelangelo_deriv dyn_GP_prior_mean = \ harmonic_oscillator_continuous_prior_mean_Michelangelo_u dyn_GP_prior_mean_deriv = \ harmonic_oscillator_continuous_prior_mean_Michelangelo_deriv_u elif 'No_observer' in system: observer = None observer_prior_mean = None dyn...
name_='Src_Link_Addr') showIndent(outfile, level) outfile.write('),\n') def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed...
import torch from torch.jit import script, trace import torch.nn as nn from torch import optim import torch.nn.functional as F import csv import random import re import os import unicodedata import codecs from io import open import itertools import math USE_CUDA = torch.cuda.is_available() device = torch.device("cuda...
<reponame>luismesas/MYNT-EYE-D-SDK<filename>tools/analytics/imu_analytics.py #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2018 Slightech Co., Ltd. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Yo...
# -*- coding: utf-8 -*- # create a function from_table_to_page_object to generate code for page objects # name (str), id (str), set (bool), get(bool), click(bool), advance(bool), check(bool) # from this table, generate code in .py file # separate page objects from higher level functions # define a decorator to try aga...
'404151004', '404152006', '404153001', '404154007', '404155008', '404157000', '404169008', '404172001', '413389003', '413441006', '413442004', '413537009', '413656006', '413842007', '413843002', '413847001', '414166008', '414780005', '414785000', '414791003', '415112005', '415283002', '415284008',...
self._scalar_dict[tag] = [] self._scalar_dict[tag].append([timestamp, global_step, float(scalar_value)]) def get_logdir(self): """Returns the logging directory associated with this `SummaryWriter`.""" return self._file_writer.get_logdir() def add_scalar(self, tag, value, global_step=None): """Adds scalar data t...
gas = CEOSGas(PRMIX, eos_kwargs=eos_kwargs, HeatCapacityGases=properties.HeatCapacityGases) >>> liquid = CEOSLiquid(PRMIX, eos_kwargs=eos_kwargs, HeatCapacityGases=properties.HeatCapacityGases) >>> flasher = FlashVL(constants, properties, liquid=liquid, gas=gas) >>> zs = [0.965, 0.018, 0.017] >>> PT = flasher.flash...
score is the best returns: chosen_play: tuple of: play: tuple of two ints play3d: tuple of three ints score: float diag: list of tuples of tree ints """ # initiallization o_scores = [] n_o_scores = [] d_scores = [] n_d_scores = [] diags = [] centroid = np.array([(self.size - 1) / 2. for _ in range(3)]) # ...
#---------------------------------------------------------------------------------------# # Name : FLP.py # Author: T.K.R.Arvind # Date : 27th December 2020 # CLI : FLP.py # # This program is for floating point computation and related opeartions and is # mainly written to cross-check the result produced on har...
the last header of the raw chunk is before the checkpoint height then it has been checked for validity. ''' headers_obj = app_state.headers checkpoint = headers_obj.checkpoint coin = headers_obj.coin end_height = start_height + len(raw_chunk) // HEADER_SIZE def extract_header(height): start = (height - start_h...
from __future__ import annotations import discord from discord import Embed, HTTPException, Forbidden, NotFound, Client, Message from ....cfg import bbData, cfg from .... import lib from .. import criminal from ....botState import logger import asyncio from .. import bounty from typing import Dict, Union, List from ......
import logging import string import datetime import json import uuid import urllib.request, urllib.parse, urllib.error import base64 import requests import os.path import sys import random import re from pyramid.config import Configurator from pyramid.renderers import JSONP, render from pyramid.response import Response...
- 40: I1ii11iIi11i * iIii1I11I1II1 % OoOoOO00 if 50 - 50: i11iIiiIii + ooOoO0o if 41 - 41: I1IiiI * OoO0O00 + IiII / OoO0O00 . I1Ii111 if 2 - 2: O0 % o0oOOo0O0Ooo O000oOOoOOO = self . eid . afi if ( self . eid . instance_id == 0 ) else LISP_AFI_LCAF if ( O000oOOoOOO < 0 ) : O000oOOoOOO = LISP_AFI_LCAF iiI1 = ( se...
<gh_stars>1-10 """ This module provides functionality to generate simulations of confined systems. """ import os import numpy as np import mdevaluate as md from .utils import save_open, write_gro from .mdgenerate import env POSRE_LINE = '{ind:>6d} {func} {params[0]:e} {params[1]:e} {params[2]:e}\n' def write_posre(...
'type': 'str'}, 'ssl_configuration': {'key': 'sslConfiguration', 'type': 'SslConfiguration'}, 'aks_networking_configuration': {'key': 'aksNetworkingConfiguration', 'type': 'AksNetworkingConfiguration'}, } def __init__( self, *, cluster_fqdn: Optional[str] = None, agent_count: Optional[int] = None, agent_vm_si...
import datetime import uuid import copy from django.test import Client, TestCase from django.contrib.auth.models import User, Permission from django.urls import reverse from majora2 import models from majora2 import forms from majora2.test.test_basic_api import BasicAPIBase, OAuthAPIClientBase from tatl import model...
# (c) 2021 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is dis...
""" pyLUT Authored by <NAME> Updated and modified by <NAME> MIT License """ #####Import necessary modules##### import os import math import struct """ The following modules are installed via pip. The program will check if they exist. If the module doesn't exist, then the program exits early. """ #NumPy try: i...
from __future__ import division from collections import deque import os import warnings import numpy as np import keras.backend as K import keras.layers as layers import keras.optimizers as optimizers from rl.core import Agent from rl.util import * def mean_q(y_true, y_pred): return K.mean(K.max(y_pred, axis=-1)) ...
are converted to | while resolving future annotations so we can't consistently # assert the message. @pytest.mark.anyio() async def test_call_with_async_di_with_defaulting_union_type_dependency(context: alluka.BasicContext): mock_type: typing.Any = mock.Mock() mock_other_type: typing.Any = mock.Mock() mock_value ...
""" Extract, combine, and correct chamber sensor data. For pre-processing only, not intended for general-purpose use. Hyytiälä COS campaign, April-November 2016 (c) 2016-2017 <NAME> <<EMAIL>> Revision history ---------------- 26 May 2016, W.S. - The two PAR sensors are now called 'PAR_ch_1' and 'PAR_ch_2', because t...
This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.study_get_tenant_study_statistics_with_http_info(tenant_id, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str tenant_i...
test info' 'For example: "LRGM Mic", "LRMG Mic"', default=''), Arg('mic_jack_type', str, 'Microphone jack Type: nocheck, lrgm, lrmg', default='nocheck'), Arg('audiofuntest_run_delay', (int, float), 'Delay between consecutive calls to audiofuntest', default=None), Arg( 'tests_to_conduct', list, 'A list of dicts....
did not count this sideband") if consecutive_null_odd == 1 and no_more_odds == False: # print "I'm done looking for odd sidebands" no_more_odds = True if consecutive_null_sb == 2: # print "I can't find any more sidebands" break if verbose: print("I found these sidebands:", self.sb_list) print('-' * 15) print...
== 0) m.c5837 = Constraint(expr= - m.b7050 + m.b7154 + m.b7155 + m.b7156 == 0) m.c5838 = Constraint(expr= - m.b7051 + m.b7157 + m.b7158 + m.b7159 == 0) m.c5839 = Constraint(expr= - m.b7052 + m.b7160 + m.b7161 + m.b7162 == 0) m.c5840 = Constraint(expr= - m.b7053 + m.b7163 + m.b7164 + m.b7165 == 0) m.c5841 = Constra...
(self.request,) class PersistentTimestampEmptyError(BadRequestError): def __init__(self, request): self.request = request super(Exception, self).__init__('Persistent timestamp empty' + self._fmt_request(self.request)) def __reduce__(self): return type(self), (self.request,) class PersistentTimestampInvalidErr...
= get_close_matches('_'.join(tproduct),strippedMolecules) rclose2 = [x.split('_') for x in rclose] rclose2 = ['_'.join([y for y in x if y != '']) for x in rclose2] pclose2 = [x.split('_') for x in pclose] pclose2 = ['_'.join([y for y in x if y != '']) for x in pclose2] trueReactant = None trueProduct = None try:...
**State** *(string) --* The state of the directory's registration with Amazon WorkSpaces - **WorkspaceCreationProperties** *(dict) --* The default creation properties for all WorkSpaces in the directory. - **EnableWorkDocs** *(boolean) --* Specifies whether the directory is enabled for Amazon WorkDocs. - **Ena...
STV_Drop_Index(USING PARAMETERS index ='{name}') OVER ();" elif method == "text": query = f"DROP TEXT INDEX {name};" elif method == "schema": query = f"DROP SCHEMA {name} CASCADE;" if query: try: executeSQL(query, title="Deleting the relation.") result = True except: if raise_error: raise result = False el...
<reponame>passteinforth/eNMRpy """ Here, you can find the SpecModel Class for creating a fit model to analyse the eNMR spectra. You can also use the wrapper function set_peaks() to create a fit model from a matplotlib-based GUI input You can also Simulate Spectra with Phase shifts. """ import numpy as np import matpl...
<gh_stars>0 ''' Written by: <NAME> Last Update: October 16th 2020 ''' import numpy as np import copy import ctypes import socket import time ########## Parameters if socket.gethostname() == "ph-photonbec5": dll_file = r"D:\Control\EMCCD\atmcd32d.dll" class EMCCD(): ##### Error Codes emccd_return_codes = d...
<gh_stars>1-10 # Copyright (c) 2012 The Foundry Visionmongers Ltd. All Rights Reserved. import maya.cmds as cmds import sys import os.path import scenegraphXML # Make sure the Alembic plugin is loaded cmds.loadPlugin('AbcExport', quiet=True) # Module level global used to hold animating bounds data from alembic callb...
test_weibull_mocked(self): self._test_sampling_func("weibull", a=1.0, size=(1,)) def test_zipf_mocked(self): self._test_sampling_func("zipf", a=1.0, size=(1,)) @classmethod def _test_sampling_func(cls, fname, *args, **kwargs): mock_gen = mock.MagicMock() getattr(mock_gen, fname).return_value = "foo" rng = iar...
6, 9], s.get_spans(vals).tolist()) dst = s.open_dataset(bio, "w", "src") ds = dst.create_dataframe('ds') vals_f = s.create_numeric(ds, "vals", "int32") vals_f.data.write(vals) self.assertListEqual([0, 1, 3, 5, 6, 9], s.get_spans(s.get(ds['vals'])).tolist()) def test_get_spans_two_fields(self): vals_1 = np.asar...
"""Abstract base class for API-type streams.""" import abc import copy import logging from datetime import datetime from typing import Any, Callable, Dict, Iterable, List, Optional, Union import backoff import requests from singer.schema import Schema from singer_sdk.authenticators import APIAuthenticatorBase, Simpl...
<reponame>samcom12/anuga_core """ Function which can be useful when setting quantities """ import copy import os import anuga.utilities.spatialInputUtil as su def make_nearestNeighbour_quantity_function( quantity_xyValueIn, domain, threshold_distance=9.0e+100, background_value=9.0e+100, k_nearest_neighbours=1...
+ diff ) pointersUpdated += 1 print 'length of defined section:', headerInfo['rtEnd'] - headerInfo['rtStart'], ' lenght of actual section:', len(rtDataBytes) datDataBytes[headerInfo['rtStart']:headerInfo['rtEnd']] = rtDataBytes # rtData (the global variable isn't later merged. so we need to do this here) ...
# USAGE # python opencv-optical-flow.py # python opencv-optical-flow.py --video PATH/example_01.mp4 import numpy import cv2 import argparse import time import random import math import imutils from collections import Counter TRACKER_POINTS = 500 # How many points will be used to track the optical flow CRAZY_LINE_DIST...
always need to do this, because it might be the case that some transcriptions don't have a date set. """ gamma = get_user_gamma(user, self.blossom_api) if before_time is not None: # We need to get the offset from the API offset_response = self.blossom_api.get( "submission/", params={ "completed_by__...
self._s: return False self._s.pop() state, param = self.backtrack, None while len(self._s) > 0 and len(self.currstate().decsglstk) > 0: state, param = state() if param is None else state(param) if len(self._s) == 0: return False elif len(self.currstate().decsglstk) == 0: return True def select...
operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_created_at must be specified if op_created_at is specified. :type val_c_created_at: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_defau...
score in pssm.search(splice_site, threshold=minthresh): try: pwm_scores[spliceend][splicetype].append((position, score)) except KeyError: pwm_scores[spliceend][splicetype]=[(position, score)] matching_end_classifications=None for key in pwm_scores["acceptor"].keys(): if key in pwm_scores["donor"]: thistuple =...
def enterParallel_path_description(self, ctx:SystemVerilogParser.Parallel_path_descriptionContext): pass # Exit a parse tree produced by SystemVerilogParser#parallel_path_description. def exitParallel_path_description(self, ctx:SystemVerilogParser.Parallel_path_descriptionContext): pass # Enter a parse ...
import discord from discord import Option, OptionChoice from discord.ext import commands, pages import random from Utilities import Checks, Vars, PlayerObject, ItemObject from Utilities.Analytics import stringify_gains from Utilities.Finances import Transaction from Utilities.AyeshaBot import Ayesha cla...
#/************************************************************************************************************************ # Copyright (c) 2016, Imagination Technologies Limited and/or its affiliated group companies. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modificat...
<gh_stars>1-10 from itertools import groupby import pandas as pd from pymatgen import MPRester, Structure from pymatgen.core.composition import Composition from pymatgen.analysis.reaction_calculator import ComputedReaction from pymatgen.core.units import FloatWithUnit from pymatgen.analysis.elasticity import ElasticTen...
if elem.length != 0.0: lattice.append(_drift_name(elem.name, 2), "drift", ('L', elem.length / 2.0), ('aper', elem.aperture / 2.0)) elif isinstance(elem, WedgeElement): if elem.length != 0.0: lattice.append(_drift_name(elem.name, 1), "drift", ('L', elem.length / 2.0), ('aper', elem.aperture / 2.0)) lattice.appen...
for polygon in polylist: count = 0 for point in polygon: points.append(point) count += 1 polycounts.append(count) bounds = self._getBounds(points) if self._useShort(bounds): e = cls16(points, polycounts, bounds) else: e = cls(points, polycounts, bounds) if not self._append(e): return 0 return 1 def _app...
<reponame>Mikuana/oops_fhir from pathlib import Path from fhir.resources.codesystem import CodeSystem from oops_fhir.utils import CodeSystemConcept __all__ = ["OperationOutcomeCodes"] _resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json")) class OperationOutcomeCodes: """ Operation Outcome Codes...
from pathlib import Path import pytest from graviton.blackbox import ( DryRunEncoder as Encoder, DryRunExecutor as Executor, DryRunProperty as DRProp, DryRunInspector as Inspector, ExecutionMode, mode_has_property, ) from graviton.invariant import Invariant from tests.clients import get_algod TESTS_DIR = Path...
# -*- coding: utf-8 -*- # # Copyright (c) 2018 Leland Stanford Junior University # Copyright (c) 2018 The Regents of the University of California # # This file is part of the SimCenter Backend Applications # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that...
"""EdgeTransformer class to convert edges to edge embeddings.""" from typing import List, Union, Optional import numpy as np import pandas as pd from userinput.utils import closest from ensmallen import express_measures from embiggen.utils.abstract_models import format_list from embiggen.embedding_transformers.node_tr...
numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from pysurvival.models.simulations import SimulationModel from pysurvival.models.multi_task import LinearMultiTaskModel from pysurvival.utils.metrics import concordance_index #%matplotlib inl...