code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def aos_as_list(self): <NEW_LINE> <INDENT> return sorted( chain.from_iterable([self.aos[el] * int(self.composition[el]) for el in self.elements]), key=lambda x: x[2], )
Returns: A list of atomic orbitals, sorted from lowest to highest energy. The orbitals energies in eV are represented as [['O', '1s', -18.758245], ['O', '2s', -0.871362], ['O', '2p', -0.338381]] Data is obtained from https://www.nist.gov/pml/data/atomic-reference-data-electronic-structure-calcu...
625941d2627d3e7fe0d69004
def split_candidate(fuzzy_candidate, precise_candidate_list): <NEW_LINE> <INDENT> LOG.debug("Candidate to split: %s" % fuzzy_candidate) <NEW_LINE> LOG.debug("Candidates to split among: %s" % precise_candidate_list) <NEW_LINE> norm_constant = sum([candidate.score for candidate in precise_candidate_list]) <NEW_LINE> LOG....
This method takes as input a single DateCandidate and a list of DateCandidates, divides the score of the single candidate among the candidates in the list proportionally according to their scores, and augments their scores accordingly. It is intended to be used to collapse a fuzzy candidate across multiple more-precise...
625941d21b99ca400220ac65
def testApplyMissingDep(self): <NEW_LINE> <INDENT> series = self.GetPatchSeries() <NEW_LINE> patch1, patch2 = self.GetPatches(2) <NEW_LINE> self.SetPatchDeps(patch2, [patch1.id]) <NEW_LINE> self._SetQuery(series, patch1).AndReturn(patch1) <NEW_LINE> self.mox.ReplayAll() <NEW_LINE> self.assertResults(series, [patch2], [...
Test that we don't try to apply a change without met dependencies. Patch2 is in the validation pool that depends on Patch1 (which is not) Nothing should get applied.
625941d2099cdd3c635f0e0f
def csm_indptr(csm): <NEW_LINE> <INDENT> return csm_properties(csm)[2]
Return the indptr field of the sparse variable.
625941d2e1aae11d1e749e6c
def match_c_top_matter(out, name): <NEW_LINE> <INDENT> c_code_gen.common_top_matter(out, name) <NEW_LINE> out.write("#include \"loci_log.h\"\n") <NEW_LINE> out.write("#include <loci/loci.h>\n")
Generate top matter for match C file @param name The name of the output file @param out The output file object
625941d24e4d5625662d458a
def test_binarate_2(self): <NEW_LINE> <INDENT> self.s.time_mask_binarate("start") <NEW_LINE> m = self.s.f['workup/time/mask/binarate'] <NEW_LINE> self.assertEqual(np.count_nonzero(m),32*1024)
Binarate mask start; test length is 2^n
625941d26fb2d068a760f253
def copy(self): <NEW_LINE> <INDENT> return Parameter(self._expreval.text, high=self.high, low=self.low, scaler=self.scaler, adder=self.adder, start=self.start, fd_step=self.fd_step, scope=self._get_scope(), name=self.name)
Return a copy of this Parameter.
625941d257b8e32f52483650
def test_compile_circuit_with_readout_correction(): <NEW_LINE> <INDENT> compiler_mock = MagicMock(side_effect=lambda circuit: circuit) <NEW_LINE> router_mock = MagicMock(side_effect=lambda circuit, network: ccr.SwapNetwork(circuit, {})) <NEW_LINE> a, b, c = cirq.LineQubit.range(3) <NEW_LINE> ap, bp, cp = cirq.LineQubit...
Tests that we are able to compile a model circuit with readout error correction.
625941d2ff9c53063f47c3a7
def tabuleiro_celulas(t): <NEW_LINE> <INDENT> if not( e_tabuleiro(t) ): <NEW_LINE> <INDENT> raise ValueError('tabuleiro_celulas: argumentos invalidos') <NEW_LINE> <DEDENT> celulas = t.get_celulas() <NEW_LINE> return [[elemento for elemento in linha] for linha in celulas]
tabuleiro_celulas : tabuleiro -> lista tabuleiro_celulas(t) recebe como argumento um elemento t do tipo tabuleiro e devolve uma lista composta por tantas listas quantas linhas o tabuleiro tiver. Cada lista contem o valor das celulas correspondentes a respetiva linha.
625941d24428ac0f6e5ba9a7
def solve1(input): <NEW_LINE> <INDENT> G = graph(input) <NEW_LINE> return len(accumulate_predecessors(G, "shiny gold", set()))
Solves part 1.
625941d2566aa707497f471b
def message_ports_in(self): <NEW_LINE> <INDENT> return _blocks_swig4.patterned_interleaver_sptr_message_ports_in(self)
message_ports_in(patterned_interleaver_sptr self) -> swig_int_ptr
625941d26fece00bbac2d8f4
def findDisappearedNumbers(self, A): <NEW_LINE> <INDENT> for idx in range(len(A)): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> target = A[idx] - 1 <NEW_LINE> if idx == target or A[idx] == A[target]: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> A[idx], A[target] = A[target], A[idx] <NEW_LINE> <DEDENT> <DEDENT> ...
You can use hash map with extra space O(n). To use without extra space, notice the additional constraints that: 1. 1 ≤ a[i] ≤ n 2. appear twice or once => use original array as storage with a[i] (- 1) as the index :type A: List[int] :rtype: List[int]
625941d2711fe17d8254251e
def get_guest_customization_section(self): <NEW_LINE> <INDENT> self.get_resource() <NEW_LINE> uri = self.href + '/guestCustomizationSection/' <NEW_LINE> return self.client.get_resource(uri)
Get guest customization section. :return: returns lxml.objectify.ObjectifiedElement resource: object containing EntityType.GUESTCUSTOMIZATIONSECTION XML data representing the guestcustomizationsection. :rtype: lxml.objectify.ObjectifiedElement
625941d2ab23a570cc250337
def _decode_json(self, file_handler): <NEW_LINE> <INDENT> json_content = self.json_content = ''.join(file_handler.readlines()) <NEW_LINE> match = self.no_comment_regex.search(json_content) <NEW_LINE> while match: <NEW_LINE> <INDENT> json_content = json_content[:match.start()] + json_content[match.end():] <NEW_LINE> mat...
Ignore les commentaires du fichiers et le parse le json en dictionnaire.
625941d2baa26c4b54cb12d3
def test_210_rabbitmq_amqp_relation(self): <NEW_LINE> <INDENT> u.log.debug('Checking rmq:n-c-c amqp relation data...') <NEW_LINE> unit = self.rabbitmq_sentry <NEW_LINE> relation = ['amqp', 'nova-cloud-controller:amqp'] <NEW_LINE> expected = { 'private-address': u.valid_ip, 'password': u.not_null, 'hostname': u.valid_ip...
Verify the rabbitmq-server to nova-cc amqp relation data
625941d2a79ad161976cc2fa
def imread_and_crop(fpath, inp_size, margin=0, random_crop=False): <NEW_LINE> <INDENT> data = tf.read_file(fpath) <NEW_LINE> img = tf.image.decode_jpeg(data, channels=3) <NEW_LINE> img = tf.image.convert_image_dtype(img, dtype=tf.float32) <NEW_LINE> shape = tf.shape(img) <NEW_LINE> crop_size = tf.minimum(shape[0], shap...
Construct TF graph for image preparation: Read the file, crop and resize -> fpath: path to the JPEG image file (TF node) -> inp_size: size of the network input (e.g. 224) -> margin: cropping margin -> random_crop: perform random crop or central crop <- prepared image (TF node)
625941d29b70327d1c4e0f8a
def do_mstep(self, rho, other, extra_pass=False): <NEW_LINE> <INDENT> logger.debug("updating topics") <NEW_LINE> previous_Elogbeta = self.state.get_Elogbeta() <NEW_LINE> self.state.blend(rho, other) <NEW_LINE> current_Elogbeta = self.state.get_Elogbeta() <NEW_LINE> self.sync_state(current_Elogbeta) <NEW_LINE> self.prin...
Maximization step: use linear interpolation between the existing topics and collected sufficient statistics in `other` to update the topics. Parameters ---------- rho : float Learning rate. other : :class:`~gensim.models.ldamodel.LdaModel` The model whose sufficient statistics will be used to update the topics...
625941d20fa83653e465716f
def bernoulli(p, decimals=2): <NEW_LINE> <INDENT> if p < 0 or p > 1: <NEW_LINE> <INDENT> raise ValueError('Probability (p) must be between 0 and 1.') <NEW_LINE> <DEDENT> probabilities = binomial([0, 1], 1, p) <NEW_LINE> probabilities = [round(x, decimals) for x in probabilities] <NEW_LINE> return(probabilities)
The `Bernoulli distribution`_ is, quoting from the Wikipedia page: The Bernoulli distribution is the probability discrete distribution of a random variable which takes value 1 with success probability p and value 0 with failure probability q = 1 - p. It can be used, for example, to represent the toss of a ...
625941d20383005118ecf797
def _parameter_parsing(self, **kwargs): <NEW_LINE> <INDENT> self._dt = None <NEW_LINE> self._band = None <NEW_LINE> self._order = None <NEW_LINE> self._orts = None <NEW_LINE> self._processed = dict() <NEW_LINE> self._indices_brain = None <NEW_LINE> self._mean_brain = None <NEW_LINE> for k, item in kwargs.items(): <NEW_...
Main parameter preparation :param kwargs: :return:
625941d2d486a94d0b98e2fa
def _request(self, method, url, params=None, data=None, headers=None, files=None, save=False, savedir='', timeout=None, cache=True, stream=False, auth=None): <NEW_LINE> <INDENT> if save: <NEW_LINE> <INDENT> local_filename = url.split('/')[-1] <NEW_LINE> local_filepath = os.path.join(self.cache_location or savedir or '....
A generic HTTP request method, similar to `requests.Session.request` but with added caching-related tools This is a low-level method not generally intended for use by astroquery end-users. As such, it is likely to be renamed to, e.g., `_request` in the near future. Parameters ---------- method : 'GET' or 'POST' url ...
625941d2d164cc6175782f02
def update(self, inputs): <NEW_LINE> <INDENT> if self.num_of_inputs != len(inputs): <NEW_LINE> <INDENT> logger.error('Incorrect number of inputs(' + str(len(inputs)) + '), correct number is ' + str(self.num_of_inputs)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return numpy.array([output_node.output(inputs) for outp...
Returns a numpy array of output value arrays.
625941d2d164cc6175782f03
@pytest.fixture <NEW_LINE> def dummy_claimant(): <NEW_LINE> <INDENT> return { "name": "dummy_claimant", "url": "http://dummy.net", "persistent_identifiers": [ { "type": "CDS_RECORD_ID", "description": "CDS record", "url": "http://cds.cern.ch/record/<CDS_RECORD_ID>", "example_value": "123", "example_url": "http://cds.ce...
Fixture that creates a dummy claimant.
625941d2e8904600ed9f20e2
def __init__(self, simName = "DMC_Sim", outputFolder = "DMCResults/", weighting = 'discrete', initialWalkers = 1000, nTimeSteps = 10000, equilTime = 2000, wfnSpacing = 1000, DwSteps = 50, atoms = [], dimensions = 3, deltaT = 5, D = 0.5, potential=None, masses = None, startStructure = None, branch_every = 1 ): <NEW_LINE...
:param simName:Simulation name for saving wavefunctions :type simName:str :param outputFolder:The folder where the results will be stored, including wavefunctions and energies :type outputFolder:str :param weighting:Discrete or Continuous weighting DMC. Continuous means that there are fixed number of walkers :type wei...
625941d2bde94217f3682fa5
def do_sync(self, target_name): <NEW_LINE> <INDENT> replica_uid = self._soledad._dbpool.replica_uid <NEW_LINE> sync_db = self._soledad._sync_db <NEW_LINE> sync_enc_pool = self._soledad._sync_enc_pool <NEW_LINE> target = soledad_sync_target( self, target_name, source_replica_uid=replica_uid, sync_db=sync_db, sync_enc_po...
Perform sync using SoledadSynchronizer, SoledadSyncTarget and Token auth.
625941d221bff66bcd684b06
def close(self, data=b''): <NEW_LINE> <INDENT> if not self.local_closed: <NEW_LINE> <INDENT> self.write_frame(data, opcode=8) <NEW_LINE> self.local_closed = True <NEW_LINE> self.writer.close()
Close the connection with the client.
625941d24d74a7450ccd4378
def load_xml(self, fn): <NEW_LINE> <INDENT> tree = ET.parse(fn) <NEW_LINE> model_node = tree.getroot() <NEW_LINE> spaces_node = model_node.find('Spaces') <NEW_LINE> figure_adapter_node = model_node.find('FigureAdapter') <NEW_LINE> self.spaces = getattr(Data, spaces_node.tag)(self, [getattr(Data, space.tag)(eval(...
Load the state from a given XML file. :param fn: Filename to load from :type fn: str.
625941d266673b3332b92246
def _readitem(self): <NEW_LINE> <INDENT> remote_mem = RemoteMemoryBlock(self.tree_ctrl) <NEW_LINE> if is64bitprocess(self.tree_ctrl.process_id()) or not is_x64_Python(): <NEW_LINE> <INDENT> item = win32structures.TVITEMW() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> item = win32structures.TVITEMW32() <NEW_LINE> <DEDE...
Read the treeview item
625941d2a05bb46b383ec9d6
def add_sessions_boxes(self, layout): <NEW_LINE> <INDENT> for session in self.sessions: <NEW_LINE> <INDENT> box = QtWidgets.QCheckBox(session.name) <NEW_LINE> layout.addWidget(box)
Add checkboxes for sessions to layout :param layout: QLayout
625941d2566aa707497f471c
def _transit(t,Rp,Rs,i,P,t0,mu): <NEW_LINE> <INDENT> t -= t0 <NEW_LINE> i = np.radians(i) <NEW_LINE> om = 2*np.pi/P <NEW_LINE> d = np.sqrt( np.sin(om*t)**2 + np.cos(i)**2 * np.cos(om*t)**2 ) <NEW_LINE> if d>Rs+Rp: <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> def LD(x,mu): <NEW_LINE> <INDENT> return 1-mu*(1-np.sqr...
Calculates transit at single time
625941d2e64d504609d749f4
def scrap_for_posts(self, url, wait, retry, wait_retry): <NEW_LINE> <INDENT> if url == None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> response = self.get_request(url, wait, retry, wait_retry) <NEW_LINE> if response['response_code'] != 200: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> soup = BeautifulS...
Scraps all post url in a given page. Returns a list of links to each post. If it receives an invalid url or None, it returns None.
625941d2507cdc57c6306e91
@click.command() <NEW_LINE> @click.option( "--path", "-p", help='path of directory you want to sort, DEFAULT: `.`' ) <NEW_LINE> @click.option( "--create-dir", "-d", is_flag=True, help='if you only want to create directories' ) <NEW_LINE> @click.option( "--organise", "-o", is_flag=True, help='create all the directories,...
A little tool that helps you organise your directory into meaningful subdirectories.
625941d207f4c71912b11638
def __init__(self, recipename: str, args: Union[List[Any], None] = None, kwargs: Union[Dict[str, Any], None] = None): <NEW_LINE> <INDENT> self.name = recipename <NEW_LINE> if args is None: <NEW_LINE> <INDENT> self.args = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.args = list(args) <NEW_LINE> <DEDENT> if kwar...
This just stores the information for each run - for now it is either used to just write the "runstring" or to run the "recipe" .main function we use get_run_program at run time to get the correct module runstring is: recipename arg[0] arg[1] arg[2] --kwarg[0]=kwargs[kwarg[0]] :param recipename: str, the name of ...
625941d28c0ade5d55d3eb70
def get_depends(repo_url, deb_name, os_platform, arch): <NEW_LINE> <INDENT> package_deps = load_Packages(repo_url, os_platform, arch) <NEW_LINE> queue = [deb_name] <NEW_LINE> depends = set() <NEW_LINE> while queue: <NEW_LINE> <INDENT> next = queue[0] <NEW_LINE> queue = queue[1:] <NEW_LINE> for package, _, deps, _ in p...
Get all debian package dependencies by scraping the Packages list. We mainly use this for invalidation logic.
625941d27b25080760e3960e
def getRing(self): <NEW_LINE> <INDENT> if self.ring is None: <NEW_LINE> <INDENT> self.ring = FinitePrimeField.getInstance(self.m) <NEW_LINE> <DEDENT> return self.ring
Return the finite prime field to which the element belongs.
625941d282261d6c526ab655
def salir(): <NEW_LINE> <INDENT> accion = input('Estas seguro de salir del programa? [S/n] '.lower().strip()) <NEW_LINE> if accion == 's': <NEW_LINE> <INDENT> sys.exit(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('\n\n') <NEW_LINE> menu_loop()
Salir del programa
625941d23317a56b86939e0b
def on_trans_committed(func, *args, **kwargs): <NEW_LINE> <INDENT> azzert(db.is_in_transaction()) <NEW_LINE> post_transaction_actions.append(True, func, *args, **kwargs)
Executes func when the transaction the function is run in has completed. Args: func: Function to execute *args: Positional arguments for func **kwargs: Keyword arguments for func Notes: Does not return the function's return value.
625941d21b99ca400220ac66
def _create_map_measure_dd_div (self): <NEW_LINE> <INDENT> return html.Div([ dcc.Dropdown( id='map_measure_dd', options=[{'label': i, 'value': i} for i in self.cases.map_measures], value=self.mapparams['plotmeasure'],clearable=False ) ])
Map measure dropdown box
625941d2dc8b845886cb56ea
def test_tcp(self): <NEW_LINE> <INDENT> reactor = object() <NEW_LINE> server = endpoints.serverFromString( reactor, "tcp:1234:backlog=12:interface=10.0.0.1") <NEW_LINE> self.assertIsInstance(server, endpoints.TCP4ServerEndpoint) <NEW_LINE> self.assertIdentical(server._reactor, reactor) <NEW_LINE> self.assertEqual(serve...
When passed a TCP strports description, L{endpoints.serverFromString} returns a L{TCP4ServerEndpoint} instance initialized with the values from the string.
625941d297e22403b379d14f
def from_kb (n_kb): <NEW_LINE> <INDENT> return ByteSize(n_kb * 1024)
Construct a new ByteSize representing `n_kb` kilobytes.
625941d24428ac0f6e5ba9a8
def updateImagery(self): <NEW_LINE> <INDENT> self.getContours()
GET RID OF THIS. but great reminder for how slow things are... this is called everytime something changes in the image threshold widget from the toolbar!!!! Todo ---- storm my brain to find a better and faster solution for this
625941d255399d3f0558886a
def getCatalogCustomAttr(url, user, pWd): <NEW_LINE> <INDENT> resturl = url + "/access/2/catalog/models/attributes" <NEW_LINE> header = {"Accept": "application/json"} <NEW_LINE> total = 1000 <NEW_LINE> offset = 0 <NEW_LINE> page = 0 <NEW_LINE> pageSize = 200 <NEW_LINE> customAttrs = [] <NEW_LINE> while offset < total: ...
call GET /access/2/catalog/models/attributes this returns all attributes (system + custom) filter for only the custom attributes (id startswith "com.infa.appmodels.ldm."
625941d2099cdd3c635f0e10
def __process_b(self, inst_dec, inst_name): <NEW_LINE> <INDENT> opcode = Disassembler.get_bits_as_decimal(31, 24, inst_dec) <NEW_LINE> address = Disassembler.get_bits_as_decimal(23, 0, inst_dec, signed=True) <NEW_LINE> assembly = '{}\t#{}'.format(inst_name, address) <NEW_LINE> self.__processed_inst[self.__address] = { ...
Disassembles a B-format ARM instruction opcode address 6 26 :param inst_dec: The decimal value of the 32-bit instruction :param inst_name: The assembly name of the instruction :return: A string containing the ARM assembly instruction
625941d2167d2b6e31218d4b
def __init__(self, A, b, c, x_constraints, Ax_constraints, problem, abs_tol=1e-9): <NEW_LINE> <INDENT> self.A = A <NEW_LINE> self.b = b <NEW_LINE> self.x_constraints = x_constraints <NEW_LINE> self.c = c <NEW_LINE> self.Ax_constraints = Ax_constraints <NEW_LINE> self.basic_idxs = None <NEW_LINE> self.x = None <NEW_LINE...
transforms LP into standard form - checks constraints' independence - handles unconstrained variables - adds slack variables expects input LP in the form of: min c'x s.t. Ax <= b x_i in x may or may not be constrained
625941d27d847024c06be472
def problem4(seq_of_seq, n): <NEW_LINE> <INDENT> pass
What comes in: -- A sequence of sequences: seq_of_seq where the sub-sequences contain only positive integers -- A non-negative integer: n What goes out: Returns the first number in the sub-sequences that is both prime and greater than n. Returns -1 if there are no prime numbers greater than n. Sid...
625941d28c3a873295158571
def about(topic): <NEW_LINE> <INDENT> assert all([lower(x) == x for x in topic]), 'topics should be lowercase.' <NEW_LINE> def select(a): <NEW_LINE> <INDENT> a = a.translate(str.maketrans('', '', string.punctuation)).split() <NEW_LINE> for i in topic: <NEW_LINE> <INDENT> for x in a: <NEW_LINE> <INDENT> if i == lower(x)...
Return a select function that returns whether a paragraph contains one of the words in TOPIC. >>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy']) >>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_dogs, 0) 'Cute Dog!' >>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup.'], about_dogs, 1) 'Nice pup.'
625941d2187af65679ca52d4
def _check_diff(changes): <NEW_LINE> <INDENT> for conf_dict in changes: <NEW_LINE> <INDENT> if conf_dict == 'Networks': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for item in changes[conf_dict]: <NEW_LINE> <INDENT> if changes[conf_dict][item]['new'] is None: <NEW_LINE> <INDENT> old = changes[conf_dict][item]['old...
Check the diff for signs of incorrect argument handling in previous releases, as discovered here: https://github.com/saltstack/salt/pull/39996#issuecomment-288025200
625941d29c8ee82313fbb92b
def model_eval_fn(self, features, labels, inference_outputs, train_loss, train_outputs, mode, config = None, params = None): <NEW_LINE> <INDENT> eval_mse = tf.metrics.mean_squared_error( labels=labels.classes, predictions=inference_outputs['a_predicted'], name='eval_mse') <NEW_LINE> predictions_rounded = tf.round(infer...
See base class.
625941d2a934411ee3751849
def __init__(self, coordinator: GiosDataUpdateCoordinator, name: str) -> None: <NEW_LINE> <INDENT> super().__init__(coordinator) <NEW_LINE> self._name = name <NEW_LINE> self._attrs: dict[str, Any] = {}
Initialize.
625941d2fff4ab517eb2f5f2
def main(*args): <NEW_LINE> <INDENT> test()
Ejemplo de insercion de una imagen muy grande que se redimensiona al tamano adecuado para que quepa en la pagina (650). ![Menu de conexion al espacio de trabajo](importacion_datos_files/menu_conexion_espacio_trabajo.png){ width=650 } Estaria bien tener herramientas como: - Insertar imagen (que seleccionamos ...
625941d2293b9510aa2c344a
def recursive_get(url, headers, destination='.', url_type=url, url_base=None, tab=''): <NEW_LINE> <INDENT> assert url_type == agave, 'Only agave currently supported for recursive files-get; source was type {}'.format(url_type) <NEW_LINE> list_url = agave_path_setlisting(url, url_base) <NEW_LINE> list_json = list_agave_...
Performs recursive files-get from remote to local location (ONLY AGAVE CURRENTLY SUPPORTED)
625941d27c178a314d6ef617
def test_6_j_2(self): <NEW_LINE> <INDENT> game = self.create_game() <NEW_LINE> self.clear_units(game) <NEW_LINE> self.clear_centers(game) <NEW_LINE> self.set_centers(game, 'FRANCE', 'PAR') <NEW_LINE> self.set_units(game, 'FRANCE', ['A PIC', 'A PAR', 'F NAO']) <NEW_LINE> self.move_to_phase(game, 'W1901A') <NEW_LINE> sel...
6.J.2. TEST CASE, REMOVING THE SAME UNIT TWICE If you have to remove two units, you can always try to trick the computer by removing the same unit twice. France has to disband two and has an army in Paris. France: Remove A Paris France: Remove A Paris Program should remove army in Paris and remove another unit by using...
625941d201c39578d7e74ff1
def dfs_orientation(self, v): <NEW_LINE> <INDENT> dfs_stack = [v] <NEW_LINE> ind = defaultdict(lambda: 0) <NEW_LINE> skip_init = defaultdict(lambda: False) <NEW_LINE> while dfs_stack: <NEW_LINE> <INDENT> v = dfs_stack.pop() <NEW_LINE> e = self.parent_edge[v] <NEW_LINE> for w in self.adjs[v][ind[v] :]: <NEW_LINE> <INDEN...
Orient the graph by DFS, compute lowpoints and nesting order.
625941d2d58c6744b4257e15
def push(self, e): <NEW_LINE> <INDENT> self._data.append(e)
add element to the top of the stack
625941d2462c4b4f79d1d886
def __call__(self,sensation,reward=None): <NEW_LINE> <INDENT> raise NYI
Do a single step and return an action. If reward is None, it is the first step of a new episode.
625941d291f36d47f21ac6a9
def pairwise_ttest(control_df, strain_df, feature_list, test_name='t-test', group_by='antioxidant', fdr_method='fdr_by', fdr=0.05): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> import pandas as pd <NEW_LINE> from scipy.stats import ttest_ind, chi2 <NEW_LINE> from tierpsytools.analysis.statistical_tests import _mul...
Perform pairwise t-tests between each strain and control, for each treatment group in 'group_by' column Inputs ------ control_df : pd.Dataframe Combined metadata + features dataframe for control strain only strain_df : pd.Dataframe Combined metadata + features dataframe for strains to be tested against contro...
625941d294891a1f4081bc5f
@parameterized(streamtypes) <NEW_LINE> def test_bad_content(cls, args, kwargs): <NEW_LINE> <INDENT> def bad_content(request): <NEW_LINE> <INDENT> for n in xrange(10): <NEW_LINE> <INDENT> yield "[1,2,3]\r" <NEW_LINE> <DEDENT> yield "[1,2, I need no stinking close brace\r" <NEW_LINE> yield "[1,2,3]\r" <NEW_LINE> <DEDENT>...
Test error handling if we are given invalid data
625941d26fb2d068a760f254
@pytest.fixture <NEW_LINE> def landbosse_costs_by_module_type_operation(): <NEW_LINE> <INDENT> prob = om.Problem() <NEW_LINE> prob.model = LandBOSSE() <NEW_LINE> prob.setup() <NEW_LINE> prob.run_model() <NEW_LINE> landbosse_costs_by_module_type_operation = prob["landbosse_costs_by_module_type_operation"] <NEW_LINE> ret...
Executes LandBOSSE and extracts cost output for the regression test.
625941d2925a0f43d254a02e
def spiral_order(matrix): <NEW_LINE> <INDENT> def boundary_points(depth): <NEW_LINE> <INDENT> n = len(matrix) <NEW_LINE> if depth == n // 2: <NEW_LINE> <INDENT> return [matrix[depth][depth]] <NEW_LINE> <DEDENT> boundary_points = [] <NEW_LINE> boundary_points.extend(matrix[depth][depth : -1 - depth]) <NEW_LINE> boundary...
2D List -> List Given: a matrix Returns: the given matrix in spiral order
625941d21f037a2d8b9463b3
def _add_node(self, new_node): <NEW_LINE> <INDENT> with lock_for_object(self._discovered_nodes): <NEW_LINE> <INDENT> old_node = self.get_node_with_tag(new_node.get_tag()) <NEW_LINE> if old_node is not None: <NEW_LINE> <INDENT> old_node.is_alive(new_node.get_last_rssi()) <NEW_LINE> old_node.update_advertising_data(new_n...
Add a node to the Manager and notify the listeners, or update its advertising data in case it has been already discovered previously. Args: new_node (:class:`blue_st_sdk.node.Node`): Node to add. Returns: bool: True if the node is added, False if a node with the same tag is already present.
625941d2796e427e537b077d
def generate(self): <NEW_LINE> <INDENT> c = int(math.log(random.random() / 2, 0.5)) - 1 <NEW_LINE> return " ".join([self.child.generate() for _ in range(c)])
Generate a string matching this expansion. This method can generate zero or more repetitions of the child expansion, zero repetitions meaning the empty string (`""`) will be returned. :rtype: str
625941d2d6c5a10208144202
def itkNotImageFilterIUS3IUS3_Superclass_cast(*args): <NEW_LINE> <INDENT> return _itkNotImageFilterPython.itkNotImageFilterIUS3IUS3_Superclass_cast(*args)
itkNotImageFilterIUS3IUS3_Superclass_cast(itkLightObject obj) -> itkNotImageFilterIUS3IUS3_Superclass
625941d24a966d76dd5511c6
def setPotential(self, column, potential): <NEW_LINE> <INDENT> assert(column < self._numColumns) <NEW_LINE> potentialSparse = numpy.where(potential > 0)[0] <NEW_LINE> self._potentialPools.replaceSparseRow(column, potentialSparse)
Sets the potential mapping for a given column. 'potential' size must match the number of inputs
625941d260cbc95b062c66f9
def test_setter_no_value(self): <NEW_LINE> <INDENT> root = api.NaElement('root') <NEW_LINE> root['k'] = None <NEW_LINE> self.assertIsNone(root.get_child_content('k'))
Tests key with None value.
625941d226238365f5f0f025
def receive(self, timeout=None): <NEW_LINE> <INDENT> timeout = timeout if timeout is not None else self.timeout <NEW_LINE> timeout += time.time() <NEW_LINE> response = None <NEW_LINE> while time.time() < timeout: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = self.responses.get(False) <NEW_LINE> <DEDENT> excep...
Wait to receive a response. :param timeout: Number of seconds to wait for a response, overrides timeout from init. :type timeout: ``int`` :return: A request response or ``None`` :rtype: ``requests.models.Response`` or ``NoneType``
625941d2ec188e330fd5a953
def hive_worker(params): <NEW_LINE> <INDENT> name = params[0] <NEW_LINE> data = json.loads(params[1]) <NEW_LINE> options = params[2] <NEW_LINE> query = data["query"]["query"] <NEW_LINE> logging.info("Starting worker for query " + name) <NEW_LINE> try: <NEW_LINE> <INDENT> client = hiver.connect(options['hive-host'], opt...
Connect to hive and run query
625941d2cc0a2c11143dd046
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False): <NEW_LINE> <INDENT> enabled_patterns = tuple('.' + x.lstrip('.').lower() for x in enabled_extensions) <NEW_LINE> disabled_patterns = tuple('.' + x.lstrip('.').lower() for x in disabled_exten...
Intelligently sets the initial value of autoescaping based on the filename of the template. This is the recommended way to configure autoescaping if you do not want to write a custom function yourself. If you want to enable it for all templates created from strings or for all templates with `.html` and `.xml` extensi...
625941d22ae34c7f2600d2e7
def institutions_read_with_http_info(self, institution_code, **kwargs): <NEW_LINE> <INDENT> all_params = ['institution_code'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout')...
Institution Information # noqa: E501 Institution Information Get basic information on all or any institutions. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.institutions_read_with_http_info(institution_code, as...
625941d294891a1f4081bc60
def client_config(self): <NEW_LINE> <INDENT> data = json.dumps({ "deviceID": self.device_id, "bundleID": "com.narvii.amino.master", "clientType": 100, "timezone": -timezone // 1000, "systemPushEnabled": True, "locale": locale()[0], "timestamp": int(time() * 1000) }) <NEW_LINE> headers = self.headers(data) <NEW_LINE> re...
Configure the client by sending Amino data about the device id and such. sets the class' configured value if the server returns a 200 status_code
625941d2099cdd3c635f0e11
def intYdYdtheta_ez(l1, m1, l2, m2): <NEW_LINE> <INDENT> return mix(l1,m1,l2,m2,_intYdYdtheta_ez)
Calculates:: pi 2pi / / d y(u,v) A = - | | y (u,v) sin(u) --- l'm' sin(u) dv du LL' / / lm du 0 0 where u = theta and v = phi in the usual notation. Note that the result is only non-zero if `|l1-l2|...
625941d257b8e32f52483651
def __init__(self, state_size, action_size, seed, use_dueling=False, use_double=False): <NEW_LINE> <INDENT> self.state_size = state_size <NEW_LINE> self.action_size = action_size <NEW_LINE> self.seed = random.seed(seed) <NEW_LINE> self.use_dueling = use_dueling <NEW_LINE> self.use_double = use_double <NEW_LINE> self.qn...
Initialize an Agent object.
625941d266656f66f7cbc361
def removeDuplicates(self, nums): <NEW_LINE> <INDENT> if nums is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> elif len(nums) == 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> n = len(nums) <NEW_LINE> updated = True <NEW_LINE> while updated: <NEW_LINE> <INDENT> updated = False <NEW_LINE> duplicated = 0 <N...
:type nums: List[int] :rtype: int
625941d250812a4eaa59c4d7
def is_socket_error(exception): <NEW_LINE> <INDENT> return isinstance(exception, SocketError)
Only retry if the exception is a SocketError. Fail otherwise.
625941d26fece00bbac2d8f5
def calculate_auth(appkey, rand, time, file_sha1sum): <NEW_LINE> <INDENT> raw_text = "appkey={}&random={}&time={}&content-sha1={}".format( appkey, rand, time, file_sha1sum ) <NEW_LINE> return hashlib.sha256(utf8(raw_text)).hexdigest()
Calculate a auth signature for uploading voice file. :param appkey: sdk appkey :param random: random string :param time: unix timestamp time :param file_sha1sum: voice file sha1 sum
625941d27cff6e4e81117b3c
def add(self, filename, arcname): <NEW_LINE> <INDENT> filename = path.normpath(filename) <NEW_LINE> if not self.mode == "w": <NEW_LINE> <INDENT> raise Exception("Archive not opened for read access") <NEW_LINE> <DEDENT> if not path.isfile(filename): <NEW_LINE> <INDENT> raise Exception("File does not exist") <NEW_LINE> <...
Add a file to a new archive.
625941d2167d2b6e31218d4c
def comments_list(request): <NEW_LINE> <INDENT> comments = Comment.objects.all() <NEW_LINE> return SerializeOrRender('blog/comments_list.html', { 'comments': comments })
Lists all blog comment.
625941d2fb3f5b602dac384a
def set_ClientID(self, value): <NEW_LINE> <INDENT> super(GetAllContactsInputSet, self)._set_input('ClientID', value)
Set the value of the ClientID input for this Choreo. ((required, string) The client ID provided by Google when you register your application.)
625941d257b8e32f52483652
def parse_markup_for_favicon(markup, url): <NEW_LINE> <INDENT> parsed_site_uri = urlparse(url) <NEW_LINE> soup = BeautifulSoup(markup) <NEW_LINE> icon_link = soup.find('link', rel='icon') <NEW_LINE> if icon_link and icon_link.has_attr('href'): <NEW_LINE> <INDENT> favicon_url = icon_link['href'] <NEW_LINE> if favicon_ur...
Given markup, parse it for a favicon URL. The favicon URL is adjusted so that it can be retrieved independently. If no favicon is found in the markup we return None. Keyword arguments: markup -- A string containing the HTML markup. url -- A string containing the URL where the supplied markup can be found. We use this...
625941d24f88993c3716c21c
def test_split_multiple(self): <NEW_LINE> <INDENT> PathFactory.create(name="CD", geom=LineString((1, -2), (1, 2))) <NEW_LINE> PathFactory.create(name="EF", geom=LineString((2, -2), (2, 2))) <NEW_LINE> PathFactory.create(name="GH", geom=LineString((3, -2), (3, 2))) <NEW_LINE> PathFactory.create(name="IJ", geom=LineStrin...
C E G I + + + + | | | | A +--+---+---+---+--+ B | | | | + + + + D F H J
625941d207f4c71912b11639
def test_names(self): <NEW_LINE> <INDENT> def capitalize(c): <NEW_LINE> <INDENT> if "-" in c: <NEW_LINE> <INDENT> return string.capwords(c.replace("-", " ")).replace(" ", "") <NEW_LINE> <DEDENT> return c.capitalize() <NEW_LINE> <DEDENT> for extr in extractor.extractors(): <NEW_LINE> <INDENT> if extr.category not in (""...
Ensure extractor classes are named CategorySubcategoryExtractor
625941d23d592f4c4ed1d222
def do_math(): <NEW_LINE> <INDENT> a = random.randint(1, 9) <NEW_LINE> b = random.randint(1, 9) <NEW_LINE> op = random.randint(1, 3) <NEW_LINE> answer = 0 <NEW_LINE> if op == 1: <NEW_LINE> <INDENT> print("What is", a, "+", b, "?") <NEW_LINE> answer = a + b <NEW_LINE> <DEDENT> elif op == 2: <NEW_LINE> <INDENT> print("Wh...
Using the random module, create a program that, first, generates two positive one-digit numbers and then displays a question to the user incorporating those numbers, e.g. “What is the sum of x and y?”. Ensure your program conducts error-checking on the answer and notifies the user whether the answer is correct or not.
625941d299cbb53fe6792d9c
def FromIAngularVector(*args): <NEW_LINE> <INDENT> return _stomp.IndexedAngularCoordinate_FromIAngularVector(*args)
FromIAngularVector(IAngularVector i_ang, DoubleVector thetaVec, DoubleVector phiVec, IndexVector indexVec, Sphere sphere = Equatorial, bool radians = False) -> bool FromIAngularVector(IAngularVector i_ang, DoubleVector thetaVec, DoubleVector phiVec, IndexVector indexVec, Sphere sphere = Equatorial) -> bo...
625941d2656771135c3eba26
def cash(self, json): <NEW_LINE> <INDENT> pass
Parameters: - json
625941d2b5575c28eb68e1b7
def run_cli(cli, args, exit_code=0): <NEW_LINE> <INDENT> from click.testing import CliRunner <NEW_LINE> result = CliRunner().invoke(cli, args, catch_exceptions=False) <NEW_LINE> if result.exit_code != exit_code: <NEW_LINE> <INDENT> sys.stderr.write('Exit code mismatch!\n') <NEW_LINE> sys.stderr.write('Ouput:\n') <NEW_L...
Run Click command line tool. Thin wrapper around `click.testing.CliRunner` that prints info to stderr if the command fails. Parameters ---------- cli : click.Command Click command args : list of str Argument list exit_code : int Expected exit code of the command Returns ------- result : `click.testing.Re...
625941d2b7558d58953c50c9
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.executing: <NEW_LINE> <INDENT> self.count += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.count = 0 <NEW_LINE> <DEDENT> if self.count >= 60: <NEW_LINE> <INDENT> self.count = 0 <NEW_LINE> self.executing = False <NEW_LINE> <DEDENT> super(BackupStatus, s...
A cada 60 execuções (= 1 hora) que se passam com executing = True, reseta-o para False, para prevenir que uma queda do servidor prenda o status em True indefinidamente.
625941d2f9cc0f698b1407b1
def test_20_period_trade(self): <NEW_LINE> <INDENT> self.assertAlmostEqual((datetime.datetime.now() - parse(min(self.prestoList.period_trade))).days / 7.0 , self.mongoList.period_trade, delta=0.8)
交易周期:第一笔开仓单的时间到当前时间的周数
625941d28e7ae83300e4b183
def call(self, input_ids=None, inputs_embeds=None, training=False): <NEW_LINE> <INDENT> assert not (input_ids is None and inputs_embeds is None) <NEW_LINE> assert not (input_ids is not None and inputs_embeds is not None) <NEW_LINE> if input_ids is not None: <NEW_LINE> <INDENT> inputs_embeds = self.word_embeddings(input...
Applies embedding based on inputs tensor. Returns: final_embeddings (:obj:`tf.Tensor`): output embedding tensor.
625941d2e8904600ed9f20e4
def upload(request): <NEW_LINE> <INDENT> if request.method == "POST": <NEW_LINE> <INDENT> if(timezone.now() > Config.objects.all()[0].end): <NEW_LINE> <INDENT> return HttpResponse("Time Up! No more submissions.") <NEW_LINE> <DEDENT> ip_address = get_ip(request) <NEW_LINE> problem_id = request.POST.get('problem_id') <NE...
Receives C file. Passes Submission object to runner class for compilation, execution and evaluation.
625941d26e29344779a627c8
def __init__(self, lookup): <NEW_LINE> <INDENT> self.lookup = lookup <NEW_LINE> self.pipe = pipe.Pipe() <NEW_LINE> self.session = app.settings.SESSION_KEY
initializes class variables pipe, session, and mako lookup Args lookup: (mako.TemplateLookup)
625941d27047854f462a15bf
def fill_between_steps(x, y1, y2=0, h_align='post', ax=None, **kwargs): <NEW_LINE> <INDENT> if ax is None: <NEW_LINE> <INDENT> ax = plt.gca() <NEW_LINE> <DEDENT> xx = x.repeat(2)[1:] <NEW_LINE> xstep = sp.repeat((x[1:] - x[:-1]), 2) <NEW_LINE> xstep = sp.concatenate(([xstep[0]], xstep, [xstep[-1]])) <NEW_LINE> xx = sp....
Fills a hole in matplotlib: fill_between for step plots. Parameters : ------------ x : array-like Array/vector of index values. These are assumed to be equally-spaced. If not, the result will probably look weird... y1 : array-like Array/vector of values to be filled under. y2 : array-Like Array/vector...
625941d232920d7e50b28387
def connect(address, ssl_context=None, error_handler=None, **config): <NEW_LINE> <INDENT> last_error = None <NEW_LINE> log_debug("~~ [RESOLVE] %s", address) <NEW_LINE> resolver = Resolver(custom_resolver=config.get("resolver")) <NEW_LINE> resolver.addresses.append(address) <NEW_LINE> resolver.custom_resolve() <NEW_LINE...
Connect and perform a handshake and return a valid Connection object, assuming a protocol version can be agreed.
625941d24d74a7450ccd437a
def populate_sell_trend(self, dataframe: DataFrame) -> DataFrame: <NEW_LINE> <INDENT> dataframe.loc[ ( (dataframe['open'] >= dataframe['ema_high']) ) | ( (qtpylib.crossed_above(dataframe['fastk'], 70)) | (qtpylib.crossed_above(dataframe['fastd'], 70)) ), 'sell'] = 1 <NEW_LINE> return dataframe
Based on TA indicators, populates the sell signal for the given dataframe :param dataframe: DataFrame :return: DataFrame with buy column
625941d221bff66bcd684b08
def dump_glu(): <NEW_LINE> <INDENT> from pyglet.gl import glu_info <NEW_LINE> print('glu_info.get_version():', glu_info.get_version()) <NEW_LINE> print('glu_info.get_extensions():') <NEW_LINE> extensions = list(glu_info.get_extensions()) <NEW_LINE> extensions.sort() <NEW_LINE> for name in extensions: <NEW_LINE> <INDEN...
Dump GLU info.
625941d28e71fb1e9831d95f
def add_group_mindist(self, group_definitions, group_pairs='all', threshold=None, ): <NEW_LINE> <INDENT> group_definitions, group_pairs, distance_list, group_identifiers = _parse_groupwise_input(group_definitions, group_pairs, self._logger, 'add_group_mindist') <NEW_LINE> distance_list = self._check_indices(distance_li...
Adds the minimum distance between groups of atoms to the feature list. If the groups of atoms are identical to residues, use :py:obj:`add_residue_mindist <pyemma.coordinates.data.featurizer.MDFeaturizer.add_residue_mindist>`. Parameters ---------- group_definition : list of 1D-arrays/iterables containing the group de...
625941d256ac1b37e6264384
def test_pessoa_fisica_simples(client): <NEW_LINE> <INDENT> create_user(PESSOA_FISICA_SIMPLES_EMAIL, SENHA, 'XXXXXXXXXXX', 'FIS', False) <NEW_LINE> rv = login(client, PESSOA_FISICA_SIMPLES_EMAIL, SENHA) <NEW_LINE> assert 'Bem vindo, Han Solo!' in rv.data.decode('utf-8') <NEW_LINE> assert 'Nunca venda para ele!' in rv.d...
Testa o acesso de uma pessoa física simples
625941d2a05bb46b383ec9d8
def _rssify_link(link): <NEW_LINE> <INDENT> if type(link) is dict: <NEW_LINE> <INDENT> return link['href'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return link
return a link in a suitable format
625941d2b57a9660fec33a3b
def test_check_rbl_accreditor(self): <NEW_LINE> <INDENT> self.mock_msg.sender_address = "sender@a--accreditor.mail.example.com" <NEW_LINE> self.plugin.check_rbl_accreditor( self.mock_msg, "accredit", "example.com", "127.0.0.1", "accreditor" ) <NEW_LINE> self.mock_ctxt.dns.query.assert_called_with( "1.0.0.127.example.co...
Test the check_rbl_accreditor eval rule
625941d2377c676e9127235f
def getCpuModel(self): <NEW_LINE> <INDENT> if self.lCpuRevision is None: <NEW_LINE> <INDENT> return 0; <NEW_LINE> <DEDENT> return (self.lCpuRevision >> 8 & 0xffff);
Returns the CPU model for a x86 or amd64 testboxes.
625941d299cbb53fe6792d9d
def _resize(buffer, resized_shape): <NEW_LINE> <INDENT> img = convert_to_pil_image(buffer) <NEW_LINE> img = img.resize((resized_shape[1], resized_shape[0])) <NEW_LINE> return np.asarray(img)
Resize to displaing image size >>> buffer = np.arange(9).reshape(3,3).astype(np.uint8) >>> resized = _resize(buffer, (9, 9)) >>> resized.shape (9, 9)
625941d271ff763f4b549844
def init_LEED_Tab(self): <NEW_LINE> <INDENT> self.LEED_IV_fig, (self.LEED_img_ax, self.LEED_IV_ax) = plt.subplots(1, 2, figsize=(6,6), dpi=100) <NEW_LINE> self.LEED_IV_canvas = FigureCanvas(self.LEED_IV_fig) <NEW_LINE> self.LEED_IV_canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) <NEW_LINE...
Setup GUI items for LEED analysis :return none:
625941d276d4e153a657ece8
@node.commandWrap <NEW_LINE> def adskAssetListUI(*args, **kwargs): <NEW_LINE> <INDENT> u <NEW_LINE> return cmds.adskAssetListUI(*args, **kwargs)
:rtype: list|str|basestring|DagNode|AttrObject|ArrayAttrObject|Components1Base
625941d2f548e778e58cd735