code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def bulk_modulus(pressure, params): <NEW_LINE> <INDENT> PoverK = _PoverK_from_P(pressure, params) <NEW_LINE> K = params['K_0']*np.power((1. - params['Kprime_inf']*PoverK), - params['Kprime_0']/params['Kprime_inf']) <NEW_LINE> return K
Returns the bulk modulus at a given pressure
625941e53539df3088e2e762
def docs(self, fileids=None): <NEW_LINE> <INDENT> return concat([self.CorpusView(path, self._read_tweets, encoding=enc) for (path, enc, fileid) in self.abspaths(fileids, True, True)])
Returns the full Tweet objects, as specified by `Twitter documentation on Tweets <https://dev.twitter.com/docs/platform-objects/tweets>`_ :return: the given file(s) as a list of dictionaries deserialised from JSON. :rtype: list(dict)
625941e524f1403a92600f7a
def fill_data(file_data, text=None, ntts={}): <NEW_LINE> <INDENT> if text: <NEW_LINE> <INDENT> slug_text = slugify(text) <NEW_LINE> text = (text, slug_text, frozenset(slug_text.split(" "))) <NEW_LINE> <DEDENT> fetch_global_data() <NEW_LINE> f=init_data(file_data, ntts) <NEW_LINE> content_fixes(f["file"]) <NEW_LINE> cho...
Añade los datos necesarios para mostrar los archivos
625941e57c178a314d6ef87d
def update_dataverse_with_worldmap_info(self): <NEW_LINE> <INDENT> print('update_dataverse_with_worldmap_info 1') <NEW_LINE> LOGGER.debug("update_dataverse_with_worldmap_info: %s" % self.worldmap_layerinfo ) <NEW_LINE> if self.worldmap_layerinfo is None: <NEW_LINE> <INDENT> LOGGER.warn("Attempted to send Worldmap info...
Send WorldMap JSON data back to the Dataverse
625941e5090684286d50f102
def xistep(self, i): <NEW_LINE> <INDENT> self.X[..., i] = spl.lu_solve_ATAI(self.A[i], self.rho, self.ATS[i] + self.rho*(self.Y - self.U[..., i]), self.lu[i], self.piv[i])
Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}` component :math:`\mathbf{x}_i`.
625941e59b70327d1c4e11ee
@log_with(log) <NEW_LINE> def get_machine_resolver_class_list(): <NEW_LINE> <INDENT> class_list = [] <NEW_LINE> class_list.append("machines.hosts.HostsMachineResolver") <NEW_LINE> class_list.append("machines.ldap.LdapMachineResolver") <NEW_LINE> return class_list
get the list of the class names of the machine resolvers like "machines.hosts.HostsMachineResolver". :return: list of machine resolver class names from the config file :rtype: list
625941e53539df3088e2e763
def get_links(url): <NEW_LINE> <INDENT> proxies = { "http": "http://101.68.73.54:53281" } <NEW_LINE> links = [] <NEW_LINE> wbdata = requests.get(url,proxies).text <NEW_LINE> soup = BeautifulSoup(wbdata, 'lxml') <NEW_LINE> l = soup.find_all("a", string=re.compile("号楼")) <NEW_LINE> for n in l: <NEW_LINE> <INDENT> link = ...
:param url: :return: links 保存含有“号楼” 从列表中过滤出来
625941e545492302aab5e6df
def abort(self, t): <NEW_LINE> <INDENT> global transactions <NEW_LINE> self._savepoint.abort() <NEW_LINE> if transactions.has_key(t): <NEW_LINE> <INDENT> assert transactions[t] is self <NEW_LINE> del transactions[t]
Called if the transaction has been aborted
625941e58a349b6b435e858a
@pytest.fixture(scope="module") <NEW_LINE> def nrel_api_key(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> demo_key = os.environ["NREL_API_KEY"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> warnings.warn( "WARNING: NREL API KEY environment variable not set! " "Using DEMO_KEY instead. Unexpected failures ma...
Supplies pvlib-python's NREL Developer Network API key. Azure Pipelines CI utilizes a secret variable set to NREL_API_KEY to mitigate failures associated with using the default key of "DEMO_KEY". A user is capable of using their own key this way if desired however the default key should suffice for testing purposes.
625941e5cc40096d61595d67
def test_complete_1_partite_graph(self): <NEW_LINE> <INDENT> G = complete_multipartite_graph(3) <NEW_LINE> H = empty_graph(3) <NEW_LINE> assert_nodes_equal(G, H) <NEW_LINE> assert_edges_equal(G.edges(), H.edges())
Tests that the complete 1-partite graph is the empty graph.
625941e5cad5886f8bd273f0
def test02( self ): <NEW_LINE> <INDENT> nw = igraph.Graph( 2, [], True ) <NEW_LINE> nw.es['sia'] = [] <NEW_LINE> nw.vs['sia'] = ["CP1", "CP2"] <NEW_LINE> g1 = igraph.Graph( 4, [(0,1),(1,2),(2,0),(1,3),(3,0)], True ) <NEW_LINE> g1['name'] = "CP1" <NEW_LINE> g1.es['mode'] = ["?","!","!","!","!"] <NEW_LINE> g1.es['name'] ...
Test2 [live]
625941e5b7558d58953c5323
def get_params(self, *keys): <NEW_LINE> <INDENT> out = {} <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> out[key] = self.params[key] <NEW_LINE> <DEDENT> return out
Return the values of one or more parameters Parameters ---------- *keys : one or more strings Names of parameters Returns ------- dict Dictionary of requested parameters
625941e52ae34c7f2600d548
def blank(wh, color=(0., 0., 0.)): <NEW_LINE> <INDENT> w, h = wh <NEW_LINE> result = np.zeros((h, w, 3)) <NEW_LINE> for i in range(result.shape[0]): <NEW_LINE> <INDENT> for j in range(result.shape[1]): <NEW_LINE> <INDENT> result[i,j,:] = color <NEW_LINE> <DEDENT> <DEDENT> return result
Returns a new blank image of the given width and height.
625941e538b623060ff0b205
def norm_cut(S, T, graph): <NEW_LINE> <INDENT> return float(cut(S,T,graph)/volume(S,graph)+ cut(S,T,graph)/volume(T,graph))
The normalized cut value for the cut S/T. (See lec06.) Params: S.......set of nodes in first subset T.......set of nodes in second subset graph...networkx graph Returns: An float representing the normalized cut value
625941e5097d151d1a22326f
def add_filmography(self, person_name): <NEW_LINE> <INDENT> self._add_person(search_person(person_name).personID)
Add every movie that a specified person has ever been in. Parameters: person_name (str): an actor name to search for in imdbpy.
625941e5e1aae11d1e74a0d3
def nodeType(self): <NEW_LINE> <INDENT> return QDomNode.NodeType()
QDomNode.NodeType QDomDocument.nodeType()
625941e5167d2b6e31218fac
def test_job(test_client): <NEW_LINE> <INDENT> response = test_client.get("job") <NEW_LINE> assert response.status_code == 405
Test job route.
625941e515fb5d323cde0f2d
def _get_supported_versions(self): <NEW_LINE> <INDENT> path = '/api/appliance/1.0.0/services' <NEW_LINE> services = self.conn.json_request('GET', path) <NEW_LINE> for service in services: <NEW_LINE> <INDENT> if service['id'] == self.service: <NEW_LINE> <INDENT> return [APIVersion(v) for v in service['versions']] <NEW_L...
Get the common list of services and versions supported.
625941e5498bea3a759b9ec6
def getLastNode(self): <NEW_LINE> <INDENT> return self._links[-1].getEndNode()
Return the last node in the path
625941e523849d37ff7b34a4
def generate_analysis_cases_port_geometry(): <NEW_LINE> <INDENT> json_interpreter = generate_data_layer("Thermodynamic Data 36 bar OF 0,1 to 8,0 H2O2 87,5.json") <NEW_LINE> chamber_length = 0.3 <NEW_LINE> external_radius = 0.05 <NEW_LINE> internal_radius = 0.01*np.linspace(1, 3, 10) <NEW_LINE> ox_flows = 0.001*np.linsp...
generate analysis cases generates the associated dictionaries that will be used in the run in batch method. :return InitializerCollection
625941e566673b3332b924a9
def __init__(self, universe, sensorSequence, startPosition): <NEW_LINE> <INDENT> super(OneDWorld, self).__init__(universe) <NEW_LINE> self.sensorSequence = sensorSequence <NEW_LINE> self.currentPosition = startPosition
Represents a simple 1D world. @param universe (AbstractUniverse) Universe that the world belongs to. @param sensorSequence (list) List of integers, each specifying a sensor value. Represents spatial configuration of patterns. @param startPosition (int) Initia...
625941e5c432627299f05061
def page19(self): <NEW_LINE> <INDENT> self.token_id = 'OPN.RTNews_1qxMXaC_iUUMYPWyTPh7xg' <NEW_LINE> result = request1901.GET('/th' + '?id=' + self.token_id + '&w=' + self.token_w + '&h=' + self.token_h + '&c=' + self.token_c + '&rs=' + self.token_rs + '&qlt=' + self.token_qlt + '&cdv=' + self.token_cdv + '&pid=' ...
GET th (request 1901).
625941e50a366e3fb873ec36
def _unsupervised_rongauss( self, X, dimension, n_samples, reconstruct, centering, prng_seed, ): <NEW_LINE> <INDENT> prng = np.random.RandomState(prng_seed) <NEW_LINE> (x_bar, mu_dp) = self._data_preprocessing(X, self.epsilon_mean, prng) <NEW_LINE> (x_tilda, proj_matrix) = self._apply_ron_projection(x_bar, dimension, p...
Generate differentially-private dataset using the unsupervised RON-Gauss Parameters ---------- X : numpy.ndarray, shape = [N_samples, M_features] Feature data. dimension : int < M_features The dimension for the data to be reduced to. n_samples : int (default None) The number of samples to be synthesized. If...
625941e50fa83653e46573d0
def merge_single_site(global_nav, site_name, site_nav, unify_sites): <NEW_LINE> <INDENT> unified = False <NEW_LINE> if unify_sites: <NEW_LINE> <INDENT> for page in global_nav: <NEW_LINE> <INDENT> if site_name in page: <NEW_LINE> <INDENT> page[site_name] = page[site_name] + site_nav <NEW_LINE> unified = True <NEW_LINE> ...
Merges a single site's nav to the global nav's data. Supports unification of sub-sites with the same site_name.
625941e56fb2d068a760f4bc
def execute(self, cmd=""): <NEW_LINE> <INDENT> return subprocess.check_output(cmd, shell=True).decode()
shell execution, super dangerous
625941e57b180e01f3dc4c0d
def _createWidgets(self): <NEW_LINE> <INDENT> self.canvas = Canvas(self.master, width=self.screen_w, height=self.screen_h) <NEW_LINE> w,h = (self.screen_w, self.screen_h) <NEW_LINE> self.mouse = MouseLight(settings.mouselight_radius) <NEW_LINE> if (settings.kb_version <= 2 or settings.kb_version > 3): <NEW_LINE> <INDEN...
Create the base canvas, menu/selection elements, mouse/key functions
625941e596565a6dacc8fae2
def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.args = kwargs
Present dictionary of options: name1: value1, name2: value2,... kwargs are name->BasicOption()
625941e555399d3f05588acf
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, JobTypeSpecificationRemovalResponseJSON): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
625941e5d8ef3951e3243956
def process_node( self, node): <NEW_LINE> <INDENT> coref = node.misc[ "Coref" ] <NEW_LINE> drop_coref = node.misc[ "Drop_coref" ] <NEW_LINE> if ( ( coref or drop_coref ) and "cc" in node.deprel ): <NEW_LINE> <INDENT> parent = node.parent <NEW_LINE> if ( node.parent.deprel == "conj" ): <NEW_LINE> <INDENT> grandparent =...
the only proper general proccesing section - normailzation of coreference of coordinated structuers: in UD the first conjunct is the haed of the structure, so the information is written here - although then it is not clear wheather the coreferent is the first conjunct only or the whle structure in some corpora, the is ...
625941e5d6c5a10208144466
def FFT(time, signal, window=None, beta=0, specres=None): <NEW_LINE> <INDENT> if specres: <NEW_LINE> <INDENT> fres = specres <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fres, frstd = sampling(space=time, dev=True, v=True) <NEW_LINE> <DEDENT> fftsize = len(time) <NEW_LINE> if beta: <NEW_LINE> <INDENT> window = lambda ...
Computes Discrete Fourier Transform of signal and its frequency space. Parameters ---------- time : array_like Time interval over which the signal is sampled. signal : array_like The ADC sampled signal (real/complex) to be transformed with fft. window : function, optional Numpy window function with which t...
625941e5a934411ee3751aad
def add_register(parent: Union["SVDPeripheral", "SVDRegisterCluster"], node): <NEW_LINE> <INDENT> if hasattr(node, "dim"): <NEW_LINE> <INDENT> dim = int(str(node.dim), 0) <NEW_LINE> incr = int(str(node.dimIncrement), 0) <NEW_LINE> default_dim_index = ",".join((str(i) for i in range(dim))) <NEW_LINE> dim_index = str(get...
Add a register node to a peripheral Args: parent: Parent SVDPeripheral object node: XML file node fot of the register
625941e53eb6a72ae02ec900
def train_cnn_7layer(data, file_name, params, num_epochs=50, batch_size=256, train_temp=1, init=None, lr=0.01, decay=1e-5, momentum=0.9, activation="relu", optimizer_name="sgd"): <NEW_LINE> <INDENT> model = Sequential() <NEW_LINE> print("training data shape = {}".format(data.train_data.shape)) <NEW_LINE> model.add(Conv...
Train a 7-layer cnn network for MNIST and CIFAR (same as the cnn model in Clever) mnist: 32 32 64 64 200 200 cifar: 64 64 128 128 256 256
625941e573bcbd0ca4b2c48d
def extractNotes(path,anno,verbose=True): <NEW_LINE> <INDENT> from extracthl2 import Anno <NEW_LINE> notes=anno.notes <NEW_LINE> meta=anno.meta <NEW_LINE> nttexts=[] <NEW_LINE> authors=tools.getAuthorList(anno.meta) <NEW_LINE> if len(anno.ntpages)==0: <NEW_LINE> <INDENT> return nttexts <NEW_LINE> <DEDENT> for pp in ann...
Extract notes <path>: str, absolute path to a PDF file. <anno>: FileAnno obj, contains annotations in PDF. Return <nttexts>: list, Anno objs containing annotation info from a PDF. Prepare to be exported to txt files.
625941e55f7d997b87174eb3
def album(self, paths, dir=None): <NEW_LINE> <INDENT> if not paths: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if dir: <NEW_LINE> <INDENT> dirs = [dir] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dirs = list(set(os.path.dirname(p) for p in paths)) <NEW_LINE> <DEDENT> if self.session.already_imported(self.top...
Return `ImportTask` with all media files from paths. `dir` is a common parent directory of all paths.
625941e50c0af96317bb8600
def get_role(env): <NEW_LINE> <INDENT> for role in env.roles: <NEW_LINE> <INDENT> if env.host_string in env.roledefs[role]: <NEW_LINE> <INDENT> return role
Returns the current active role
625941e524f1403a92600f7b
def allCommitHashes(): <NEW_LINE> <INDENT> allhashesline = subprocess.check_output(['git', '--git-dir=' + gitdir, 'log', '--all', '--format=%H']) <NEW_LINE> allhashes = allhashesline.split('\n') <NEW_LINE> return allhashes[0:-1]
Return the hashes of every commit in the repository
625941e557b8e32f524838b6
def make_g12_mask(badframes_list, g12_shape): <NEW_LINE> <INDENT> m, n = g12_shape <NEW_LINE> g12_mask = np.ma.ones((m, n)) <NEW_LINE> g12_mask.mask = False <NEW_LINE> for bdl in badframes_list: <NEW_LINE> <INDENT> g12_mask.mask[:, bdl] = True <NEW_LINE> g12_mask.mask[bdl, :] = True <NEW_LINE> <DEDENT> return g12_mask
Dec 16, 2015, Y.G.@CHX make g12 mask by badlines Parameters: badframes_list: list, contains the bad frame number, like [100, 155, 10000] g12_shape: the shape of one-q two correlation function, shape as ( imgs_length, imgs_length ) Return: g12_mask: a 2-D array, shape as ( imgs_length, imgs_length ) One e...
625941e51f5feb6acb0c4f62
def get_mouse() : <NEW_LINE> <INDENT> mouse = pygame.mouse.get_pos() <NEW_LINE> return Point(mouse[0],mouse[1])
Renvoie la position de la souris Instruction non bloquante
625941e55fdd1c0f98dc064d
@cocotb.test() <NEW_LINE> def alu_not_random(dut): <NEW_LINE> <INDENT> from random import randrange <NEW_LINE> op = 7 <NEW_LINE> for _ in range(1000): <NEW_LINE> <INDENT> a = randrange(0, UINT_MAX) <NEW_LINE> b = randrange(0, UINT_MAX) <NEW_LINE> dut.a = a <NEW_LINE> dut.b = b <NEW_LINE> dut.opcode = op <NEW_LINE> yiel...
alu NOT tests: - random numbers
625941e5009cb60464c637c7
def is_invalid_token(self): <NEW_LINE> <INDENT> return self.name == Token.INVALID_TOKEN_NAME
:return: True iff this is an invalid token, False otherwise.
625941e58e7ae83300e4b3e6
def get_options(self): <NEW_LINE> <INDENT> return self._options
Returns options. @return: str
625941e51b99ca400220aecb
def assemble_FCNN_blocks(inputs, config, dropout_prob): <NEW_LINE> <INDENT> F = assemble_CNN_blocks(inputs, config, dropout_prob) <NEW_LINE> features = F[-1] <NEW_LINE> layer = config.num_layers - 1 <NEW_LINE> r = config.first_subsampling_dl * config.density_parameter * 2 ** layer <NEW_LINE> fdim = config.first_feature...
Definition of all the layers according to config :param inputs: dictionary of inputs with keys [points, neighbors, pools, upsamples, features, batches, labels] :param config: :param dropout_prob: :return:
625941e5c4546d3d9de72e50
def test_idfm_155(self): <NEW_LINE> <INDENT> self.journey( _from="2.3521;48.8381", to="2.3371459999999997;48.794008000000005", datetime="20190307T190000", enable_benchmark=True, **IDFM_PARAMS )
/v1/coverage/idfm/journeys?from=2.3521;48.8381&to=2.3371459999999997;48.794008000000005&datetime=20190307T190000&walking_speed=1.17&_night_bus_filter_max_factor=1.3&_final_line_filter=true
625941e53346ee7daa2b3187
def reverseString(self, s:list) -> None: <NEW_LINE> <INDENT> if not s:return None <NEW_LINE> left,right = 0,len(s)-1 <NEW_LINE> while left < right: <NEW_LINE> <INDENT> s[left],s[right]=s[right],s[left] <NEW_LINE> left +=1 <NEW_LINE> right -=1 <NEW_LINE> <DEDENT> return s
Do not return anything, modify s in-place instead.
625941e5283ffb24f3c55d15
def create_image_lists(filename, testing_percentage, validation_percentage): <NEW_LINE> <INDENT> result = {set_class: {} for set_class in ['validation', 'testing', 'training']} <NEW_LINE> with open(LABELS_DIR + '/' + filename, newline='') as labels_file: <NEW_LINE> <INDENT> reader = csv.reader(labels_file) <NEW_LINE> f...
Create a dictionary of training images from the .csv file. Splits images into stable 'training', 'testing', and 'validation' sets, and returns a data structure describing the images. (The images distribution depends on the file name only --> at any starts the same picture will distributed into the same set) Args: ...
625941e5236d856c2ad44bf8
def quickSort(array): <NEW_LINE> <INDENT> return quickSortHelp(array, 0, len(array) - 1)
Quicksort function calling the helper function Question 6 :param array: Unsorted array :return: Returning the sorted array
625941e576e4537e8c351a8e
def closeSaveFile(self): <NEW_LINE> <INDENT> if self.saveFile != None: <NEW_LINE> <INDENT> self.saveFile.close() <NEW_LINE> self.oP("Closed the save file.") <NEW_LINE> self.saveFile = None
Closes the save file.
625941e563b5f9789fde74fe
def test_housekeeping_with_xclock_satisfied(): <NEW_LINE> <INDENT> xtrigger_mgr = XtriggerManager(suite="sample_suite", user="john-foo") <NEW_LINE> xtrig = SubFuncContext( label="wall_clock", func_name="wall_clock", func_args=[], func_kwargs={} ) <NEW_LINE> xtrig.out = "[\"True\", \"1\"]" <NEW_LINE> xtrigger_mgr.add_cl...
The housekeeping method makes sure only satisfied xclock function are kept.
625941e594891a1f4081bec4
def cat_num_split(self): <NEW_LINE> <INDENT> numeric = ['int_', 'intc', 'intp', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float_', 'float16', 'float64', 'complex_', 'complex64', 'complex128'] <NEW_LINE> df_num = self.select_dtypes(include=numeric) <NEW_LINE> df_cat = self.drop(df_num, a...
Splits a pandas dataframe into seperate numeric and categorical dataframes Returns ------- df_num: DataFrame Dataframe containing columns with only numeric observations df_cat: DataFrame Dataframe containing columns with only categorical observations
625941e567a9b606de4a82d0
def testLayBetStay(self): <NEW_LINE> <INDENT> bet = craps.LayBet(self.player, 'lay', 9) <NEW_LINE> bet.set_wager(6) <NEW_LINE> self.setDice([3, 2]) <NEW_LINE> self.assertEqual(0, bet.resolve(self.dice))
Test a lay bet staying.
625941e5eab8aa0e5d26df72
def test_simple_filter_operators(self): <NEW_LINE> <INDENT> shots = self._mockgun.find( "Shot", [{ "filter_operator": "any", "filters": [ ["code", "is", "shot1"], ["code", "is", "shot2"] ] }] ) <NEW_LINE> self.assertEqual(len(shots), 2) <NEW_LINE> shots = self._mockgun.find( "Shot", [{ "filter_operator": "all", "filter...
Tests a simple use of the filter_operator.
625941e5ab23a570cc25059e
def __init__(self, k, nums): <NEW_LINE> <INDENT> self.k = k <NEW_LINE> self.root = None <NEW_LINE> for n in nums: <NEW_LINE> <INDENT> self.root = self.insertBST(n)
:type k: int :type nums: List[int]
625941e5ab23a570cc25059f
def login_user(self, email='', password=''): <NEW_LINE> <INDENT> return self.client.post( '/user/login', content_type='application/json', json={'email':email, 'password':password})
Helper method for login a user with dummy data :return:
625941e566656f66f7cbc5c5
def setPadding(self, pad): <NEW_LINE> <INDENT> if pad is not None: <NEW_LINE> <INDENT> pad = self._guardAgainstUnicode(pad) <NEW_LINE> <DEDENT> self._padding = pad
setPadding() -> bytes of length 1. Padding character.
625941e50a50d4780f6672ae
def test_attributes_wildcard(): <NEW_LINE> <INDENT> ATTRS = { '*': ['id'], 'img': ['src'], } <NEW_LINE> TAGS = ['img', 'em'] <NEW_LINE> text = 'both <em id="foo" style="color: black">can</em> have <img id="bar" src="foo"/>' <NEW_LINE> assert ( bleach.clean(text, tags=TAGS, attributes=ATTRS) == 'both <em id="foo">can</e...
Verify attributes[*] works
625941e5be7bc26dc91cda11
def save(self, lib_file): <NEW_LINE> <INDENT> rectangle_str = u'S {start_x} {start_y} {end_x} {end_y} {unit} {convert} {thickness} {fill}\n'.format( start_x=self.start_x, start_y=self.start_y, end_x=self.end_x, end_y=self.end_y, unit=self.unit, convert=self.convert, thickness=self.thickness, fill=self.fill ) <NEW_LINE>...
Save description of the rectangle to Schematic library file. Args: lib_file (file) - file for writing.
625941e54f6381625f114e54
def test_match_with_validator(app, simple_record, mocker): <NEW_LINE> <INDENT> from invenio_records import Record <NEW_LINE> mocker.patch('invenio_matcher.engine.search', one_search_result) <NEW_LINE> with app.app_context(): <NEW_LINE> <INDENT> record = Record(simple_record) <NEW_LINE> queries = [{'type': 'exact', 'mat...
Validate results with a validator function.
625941e556b00c62f0f14a74
def timestamp_to_datetime(timestamp): <NEW_LINE> <INDENT> return datetime.datetime.fromtimestamp(timestamp)
时间戳转换为时间对象
625941e57d847024c06be6d8
def test_point_at_angle(): <NEW_LINE> <INDENT> pt = Point3D(2, 0) <NEW_LINE> arc = Arc3D(Plane(o=pt), 1, 1.5 * math.pi, 0.5 * math.pi) <NEW_LINE> assert arc.point_at_angle(0.5 * math.pi).x == pytest.approx(3, rel=1e-2) <NEW_LINE> assert arc.point_at_angle(0.5 * math.pi).y == pytest.approx(0, rel=1e-2)
Test the Arc3D point_at_angle method.
625941e545492302aab5e6e0
def test_version(self): <NEW_LINE> <INDENT> filedelta = get_filedelta() <NEW_LINE> self.assertEquals(filedelta.oldver, "1.1") <NEW_LINE> self.assertEquals(filedelta.newver, "1.2")
Ensures the the version of the file is correct
625941e556ac1b37e62645e0
def send_chatbot_message(username, servers, chatbotquery): <NEW_LINE> <INDENT> message = CHATBOT_MESSAGE.format( savings=1234, servers=456).replace('\n', '\\n') <NEW_LINE> context = RELAY_CONTEXT.format(username=username) <NEW_LINE> body = RELAY_BODY.format(username=username, message=message, context=context, chatbotqu...
Sends one message to the chatbot about a user servers
625941e5ff9c53063f47c60a
def q(self, state): <NEW_LINE> <INDENT> return np.array([0, 0, 0, 0])
Return Q value for all action for a certain state. :return np.ndarray: Q values
625941e54527f215b584c86b
@cli.command(short_help='Initialize Git repo for time tracking') <NEW_LINE> @click.option('--check', is_flag=True, help='Instead of initializing the repo, checks whether it has ' 'been initialized before. If not exits the command with exit code 2') <NEW_LINE> @click.option('--install-hook', is_flag=True, help='If you w...
Initializes the current Git repository.  There are two places where the bootstrapped information can be stored: - internal storage (store) - local config (local) - file in root of the repository It is possible to initialize giTrack without automatic installation of the Git's hook. Then it is your responsibility ...
625941e5ec188e330fd5abb0
def log_last_login_attempt(session, ip_address, username): <NEW_LINE> <INDENT> attempt = LoginAttempt(username, ip_address) <NEW_LINE> attempt = session.merge(attempt) <NEW_LINE> return persist(session, attempt)
"Persist failed login attempt (either insert or update)
625941e563f4b57ef0001526
def __init__(self, embed_size, attention_size, hidden_size, vocab_size, encoder_size=1024, max_seg_length=40): <NEW_LINE> <INDENT> super(DecoderRNNWithAttention, self).__init__() <NEW_LINE> self.attention = Attention(encoder_size=encoder_size, hidden_size=hidden_size, attention_size=attention_size) <NEW_LINE> self.embe...
Set the hyper-parameters and build the layers.
625941e55fcc89381b1e1ada
def __init__(self): <NEW_LINE> <INDENT> self.examquestion_dict = {} <NEW_LINE> self.course_info = None
initialize local variables.
625941e596565a6dacc8fae3
def test_almost_but_not_quite_daophot(): <NEW_LINE> <INDENT> lines = ["# some header info", "#F header info beginning with 'F'", "1 2 3", "4 5 6", "7 8 9"] <NEW_LINE> dat = ascii.read(lines) <NEW_LINE> assert len(dat) == 3
Regression test for #3319. This tables looks so close to a daophot table, that the daophot reader gets quite far before it fails with an AttributeError. Note that this table will actually be read as Commented Header table with the columns ['some', 'header', 'info'].
625941e510dbd63aa1bd2fbb
def get_lamps(self, fitstbl): <NEW_LINE> <INDENT> msgs.error('This spectrograph does not support the use of lamps list from header. ' 'provide a list of lamps using the parameter `lamps` in WavelengthSolutionPar')
Extract the list of arc lamps used from header. This method is not defined for all spectrographs. This base-class method raises an exception.
625941e5460517430c394594
def compute_mtf(self): <NEW_LINE> <INDENT> nyquist_x = 1.0/(2.0*self.pitchx.data) <NEW_LINE> self.nyquist_x = Scalar('nyqx', nyquist_x, '1/' + self.pitchx.units) <NEW_LINE> nyquist_y = 1.0/(2.0*self.pitchy.data) <NEW_LINE> self.nyquist_y = Scalar('nyqy', nyquist_y, '1/' + self.pitchy.units) <NEW_LINE> spf_rel = np.hsta...
Compute the MTF of a FocalPlaneArray. In this model, the FPA is assumed to be a rectangular array having pixels with rectangular aperture. :return:
625941e5d18da76e235328f4
def transform(self, X: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> xlabelenc = grouplabelencode( list(map(str, X)), self.mapping, nastate=False) <NEW_LINE> xonehot = onehotencode(xlabelenc, self.mapping) <NEW_LINE> if self.nastate: <NEW_LINE> <INDENT> xonehot = scipy.sparse.hstack([xonehot, xonehot.sum(axis=1) == 0]...
Convert a nominal variable to an one-hot encoded matrix
625941e550812a4eaa59c737
def handle(self, job): <NEW_LINE> <INDENT> bot, event = job.args <NEW_LINE> logging.warn("got speech from %s" % event.display()) <NEW_LINE> self.starttime = time.time() <NEW_LINE> if not ievent.nolog: logging.debug("long event handler is %s" % str(func)) <NEW_LINE> func = job.func <NEW_LINE> res = callbacks.check(bot, ...
schedule a bot command.
625941e5e1aae11d1e74a0d4
def test_4A5_retreat(self): <NEW_LINE> <INDENT> self.judge.datc.datc_4a3 = 'd' <NEW_LINE> self.judge.datc.datc_4a5 = 'b' <NEW_LINE> steady_state = [ [ENG, AMY, BUR], [ENG, FLT, IRI], [ENG, FLT, NTH], [FRA, FLT, MAO], [RUS, FLT, NWG], [RUS, FLT, NAO], [RUS, AMY, CLY], ] <NEW_LINE> self.init_state(SPR, 1901, steady_state...
4.A.5.b RETREAT WHEN DISLODGED BY CONVOY
625941e5a219f33f34628d7d
def search_messages(self): <NEW_LINE> <INDENT> self._assert_query_is_initialized() <NEW_LINE> msgs_p = Query._search_messages(self._query) <NEW_LINE> if not msgs_p: <NEW_LINE> <INDENT> raise NullPointerError <NEW_LINE> <DEDENT> return Messages(msgs_p, self)
Filter messages according to the query and return :class:`Messages` in the defined sort order :returns: :class:`Messages` :raises: :exc:`NullPointerError` if search_messages failed
625941e5e64d504609d74c59
def energyK(self): <NEW_LINE> <INDENT> return self.linearK() + self.angularK()
Total kinetic energy: sum of linearK and angularK.
625941e523849d37ff7b34a5
def _update(self, oldobj, newobj): <NEW_LINE> <INDENT> if type(oldobj) is not type(newobj): <NEW_LINE> <INDENT> return newobj <NEW_LINE> <DEDENT> new_module = getattr(newobj, '__module__', None) <NEW_LINE> if new_module != self.mod.__name__: <NEW_LINE> <INDENT> return newobj <NEW_LINE> <DEDENT> if isinstance(newobj, zo...
Update oldobj, if possible in place, with newobj. If oldobj is immutable, this simply returns newobj. Args: oldobj: the object to be updated newobj: the object used as the source for the update Returns: either oldobj, updated in place, or newobj.
625941e5cb5e8a47e48b7ebd
def __init__(self, temboo_session): <NEW_LINE> <INDENT> super(ShortenURL, self).__init__(temboo_session, '/Library/Bitly/Links/ShortenURL')
Create a new instance of the ShortenURL Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied.
625941e50a366e3fb873ec37
def get_LCA_in_BT(tree: LinkedBinaryTree, node_1_data, node_2_data): <NEW_LINE> <INDENT> assert node_1_data != node_2_data, 'both nodes should be distinct' <NEW_LINE> is_node_1_found, is_node_2_found = False, False <NEW_LINE> def _get_LCA_in_BT(node: LinkedBinaryTree.BinaryTreeNode): <NEW_LINE> <INDENT> nonlocal is_nod...
Also works when any of queried nodes are not present in tree. One tree traversal if both nodes are present in tree, or both nodes are not present in tree. Two traversals if one node is present and other is either not present, or the child of another queried node. Time Complexity: O(2N) Space Complexity: O(1) :param t...
625941e530bbd722463cc1e1
def create_job_schedule(batch_client, job_schedule_id, vm_size, vm_count, block_blob_client): <NEW_LINE> <INDENT> cloud_service_config = batchmodels.CloudServiceConfiguration(os_family='6') <NEW_LINE> user_id = batchmodels.UserIdentity( auto_user=batchmodels.AutoUserSpecification( elevation_level=_USER_ELEVATION_LEVEL)...
Creates an Azure Batch pool and job schedule with the specified ids. :param batch_client: The batch client to use. :type batch_client: `batchserviceclient.BatchServiceClient` :param str job_schedule_id: The id of the job schedule to create :param str vm_size: vm size (sku) :param int vm_count: number of vms to allocat...
625941e5cdde0d52a9e5344f
def VirtualMachineGuestSummary(vim, *args, **kwargs): <NEW_LINE> <INDENT> obj = vim.client.factory.create('{urn:vim25}VirtualMachineGuestSummary') <NEW_LINE> if (len(args) + len(kwargs)) < 0: <NEW_LINE> <INDENT> raise IndexError('Expected at least 1 arguments got: %d' % len(args)) <NEW_LINE> <DEDENT> required = [ ] <N...
A subset of virtual machine guest information.
625941e526238365f5f0f28d
def get_good_sections(df, max_sample_period, look_ahead=None, previous_chunk_ended_with_open_ended_good_section=False): <NEW_LINE> <INDENT> index = df.dropna().sort_index().index <NEW_LINE> del df <NEW_LINE> if len(index) < 2: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> timedeltas_sec = timedelta64_to_secs(diff(i...
Parameters ---------- df : pd.DataFrame look_ahead : pd.DataFrame max_sample_period : number Returns ------- sections : list of TimeFrame objects Each good section in `df` is marked with a TimeFrame. If this df ends with an open-ended good section (assessed by examining `look_ahead`) then the last TimeFram...
625941e5099cdd3c635f1072
def debug_end(self, yaml_file): <NEW_LINE> <INDENT> raise NotImplementedError
Slot that connects to debugger; raised when the debugger unloaded a file.
625941e566656f66f7cbc5c6
def gitcmd(cmd): <NEW_LINE> <INDENT> if isinstance(cmd,str): <NEW_LINE> <INDENT> return cmd_output('git '+cmd) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cmd_output(['git']+cmd)
Run git command and return output. Use this for git commands that don't produce huge output. A CalledProcessError exception is raised if command has a non-zero exit. The caller should catch and raise GitFail if needed.
625941e5baa26c4b54cb1535
def get_content(self): <NEW_LINE> <INDENT> return self.content
Returnt the tank content type :return:
625941e5ff9c53063f47c60b
def hamming_distance(str1, str2): <NEW_LINE> <INDENT> b1 = get_bits(str1) <NEW_LINE> b2 = get_bits(str2) <NEW_LINE> diff_count = 0 <NEW_LINE> for i in range(len(b1)): <NEW_LINE> <INDENT> if b1[i] != b2[i]: <NEW_LINE> <INDENT> diff_count += 1 <NEW_LINE> <DEDENT> <DEDENT> return diff_count
Get # of different bits between two equal-length strings
625941e5c432627299f05062
def build_net3(): <NEW_LINE> <INDENT> net = tflearn.input_data(shape=[None, time_window, 1]) <NEW_LINE> lstm1 = tflearn.BasicLSTMCell(num_units=lstm_units) <NEW_LINE> lstm2 = tflearn.BasicLSTMCell(num_units=lstm_units) <NEW_LINE> net = tflearn.bidirectional_rnn(net, lstm1, lstm2, return_seq=False) <NEW_LINE> net = tfle...
Bidirectional RNN
625941e5f7d966606f6aa422
def decorate_several_with_validation(func, _out_=None, none_policy=None, **validation_funcs ): <NEW_LINE> <INDENT> if _out_ is not None: <NEW_LINE> <INDENT> func = decorate_with_validation(func, _OUT_KEY, _out_, none_policy=none_policy) <NEW_LINE> <DEDENT> for att_name, att_validation_funcs in validation_funcs.items():...
This method is equivalent to applying `decorate_with_validation` once for each of the provided arguments of the function `func` as well as output `_out_`. validation_funcs keyword arguments are validation functions for each arg name. Note that this method is less flexible than decorate_with_validation since * it does...
625941e54428ac0f6e5bac0f
def email_token(token): <NEW_LINE> <INDENT> logging.info("Emailing the token") <NEW_LINE> body = f"The token to reset your password: {token}" <NEW_LINE> pass
Email the token
625941e53539df3088e2e764
def signed_serialize(data, secret): <NEW_LINE> <INDENT> payload = json.dumps(data).encode('utf-8') <NEW_LINE> sig = hmac.new(secret, payload, hashlib.sha1).hexdigest() <NEW_LINE> return sig.encode('utf-8') + base64.b64encode(payload)
Serialize any pickleable structure (``data``) and sign it using the ``secret`` (must be a string). Return the serialization, which includes the signature as its first 40 bytes. The ``signed_deserialize`` method will deserialize such a value. This function is useful for creating signed cookies. For example: .. code-bl...
625941e526068e7796caf0ff
def entity_id(prefix): <NEW_LINE> <INDENT> current_date = datetime.datetime.now() <NEW_LINE> return "%sID%s" % (prefix, current_date.strftime("%Y%m%d%H%M%S%f"))
Creates a new ID for an entity Args: prefix ([string]): a prefix to add to the ID Returns: A string which represents the entity ID
625941e58c3a8732951587d9
def _build_loss(self): <NEW_LINE> <INDENT> raise NotImplementedError("Please Implement this method")
Should initialize self.loss to be a tensorflow operation that calculates the loss funtion for the current policy
625941e5f7d966606f6aa423
def is_complete(snippet): <NEW_LINE> <INDENT> can_continue = [',', '(', '[', '{', '\\', '"""', '%'] <NEW_LINE> return not any(snippet.strip().endswith(end) for end in can_continue)
Check if a code snippet is complete. >>> is_complete("a = [1, 2, 3]") True >>> is_complete("a = [1,") False >>> is_complete("a = [1, (") False >>> is_complete("a = [") False >>> is_complete("a = [1, {") False >>> is_complete('a = [1, 2, "%d" % \\') False >>> is_complete('a = [1, 2, \"\"\"') False >>> is_complete('"...
625941e545492302aab5e6e1
def is_valid_v4addr(addr): <NEW_LINE> <INDENT> if not addr: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if addr.find('.') != -1: <NEW_LINE> <INDENT> addr_list = addr.split('.') <NEW_LINE> if len(addr_list) != 4: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for each_num in addr_list: <NEW_LINE> <INDENT>...
check is ipv4 addr is valid
625941e58c0ade5d55d3edd8
def inverse_model(measurements, targets, encoder, decoder, encoder_c, wu_c=0.0): <NEW_LINE> <INDENT> cost = cvae_cost(measurements, targets, encoder, decoder, encoder_c, wu_c=0.0) <NEW_LINE> return cost
Cost function for inverse model INPUTS: measurements - the measurements to infer from targets - ground-truths to be eventually reconstructed with the inverse model encoder - the neural network to be used for mapping measurements and targets to mu_z and log_sig_sq_z decoder - the neural network to be use...
625941e58e71fb1e9831dbc1
def get_issues(self, project_id=None, tracker=None, status=None, page=0, custom=None): <NEW_LINE> <INDENT> urlArgs = {'key': self.key, 'page': page} <NEW_LINE> if project_id is not None: <NEW_LINE> <INDENT> urlArgs['project_id'] = project_id <NEW_LINE> <DEDENT> if tracker is not None: <NEW_LINE> <INDENT> urlArgs['track...
Get paginated list of all issues, returns one page at a time GET $base/issues.xml?page=$page&project_id=$project&tracker_id=$tracker&status_id=$status Creating an issue should probably be part of this test... >>> r = RedmineClient('http://redmine.example.com', 'test_username', 'test_password', 'test_key') >>> l = r.ge...
625941e55510c4643540f7f3
def to_table(self): <NEW_LINE> <INDENT> header = QPState.get_fields(exclude=["spin", "kpoint"]) <NEW_LINE> table = [header] <NEW_LINE> for qp in self: <NEW_LINE> <INDENT> d = qp.to_strdict(fmt=None) <NEW_LINE> table.append([d[k] for k in header]) <NEW_LINE> <DEDENT> return tabulate(table, tablefmt="plain")
Return a table (list of list of strings).
625941e50a50d4780f6672af
def create(self, validated_data): <NEW_LINE> <INDENT> if 'polygons' in validated_data and len(validated_data['polygons']): <NEW_LINE> <INDENT> polygon_data = validated_data.pop('polygons') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValidationError('Please provide a valid GeoJSON representation') <NEW_LINE> <DE...
Create and return a new ``Place`` instance, given the validated data.
625941e5cad5886f8bd273f2
def connect(self, root): <NEW_LINE> <INDENT> mostleft = root <NEW_LINE> while mostleft: <NEW_LINE> <INDENT> cur = mostleft <NEW_LINE> while cur: <NEW_LINE> <INDENT> if cur.left: <NEW_LINE> <INDENT> cur.left.next = cur.right <NEW_LINE> <DEDENT> else: return <NEW_LINE> if cur.next: <NEW_LINE> <INDENT> cur.right.next = cu...
:type root: TreeLinkNode :rtype: nothing
625941e529b78933be1e5ac0
def __getitem__(self, key): <NEW_LINE> <INDENT> if isinstance(key , int): <NEW_LINE> <INDENT> if key < 0: <NEW_LINE> <INDENT> key += len(self) <NEW_LINE> <DEDENT> if 0 <= key < len(self): <NEW_LINE> <INDENT> node_ = self._iget_node(key) <NEW_LINE> node_.setParent(self) <NEW_LINE> return node_ <NEW_LINE> <DEDENT> else: ...
@rtype: LocalObsdataNode
625941e52ae34c7f2600d54a
def get_all_possibilities(gamestate: GameState) -> list: <NEW_LINE> <INDENT> possible_positions = [] <NEW_LINE> for index_of_row in range(len(gamestate.board)): <NEW_LINE> <INDENT> for index_of_column in range(len(gamestate.board[index_of_row])): <NEW_LINE> <INDENT> if gamestate.board[index_of_row][index_of_column] == ...
Using the current gamestate to get all the possible positions to move for the exact piece input, and then return them in a list.
625941e5167d2b6e31218fae
def obtain_token(site, request, code): <NEW_LINE> <INDENT> mast_app = MastodonApplication.objects.get(domain_name=site) <NEW_LINE> payload = { 'client_id': mast_app.client_id, 'client_secret': mast_app.client_secret, 'redirect_uri': f"https://{request.get_host()}{reverse('users:OAuth2_login')}", 'grant_type': 'authoriz...
Returns token if success else None.
625941e529b78933be1e5ac1