code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_positive_get_status_code(self): <NEW_LINE> <INDENT> response = client.get( self.path, auth=settings.server.get_credentials(), verify=False, ) <NEW_LINE> self.assertEqual(response.status_code, http_client.OK) <NEW_LINE> self.assertIn('application/json', response.headers['content-type'])
GET ``api/v2`` and examine the response. @id: 9d9c1afd-9158-419e-9a6e-91e9888f0c04 @Assert: HTTP 200 is returned with an ``application/json`` content-type
625941d1004d5f362079a4cf
def add_element(self, element_dict=None): <NEW_LINE> <INDENT> if self.curr_section is None: <NEW_LINE> <INDENT> self.add_section() <NEW_LINE> <DEDENT> self.curr_section['element_list'].append(SongElement(element_dict)) <NEW_LINE> self.curr_element = self.curr_section['element_list'][-1]
Appends an empty element to the current section
625941d14e4d5625662d4573
def test1CreationAfvoerendOppervlak2(self): <NEW_LINE> <INDENT> repr = sampleStrings["SUFHYD"][AfvoerendOppervlak][1] <NEW_LINE> obj = HydroObjectFactory.hydroObjectFromSUFHYD(repr) <NEW_LINE> self.assertEqual(obj.__class__, AfvoerendOppervlak_Tak)
- just if AfvoerendOppervlak (Tak) is created
625941d156b00c62f0f147f6
def resetCenter(self): <NEW_LINE> <INDENT> self._mousePanningDelta = QPoint() <NEW_LINE> self.current_scale = 1.0
Resets origin
625941d1236d856c2ad44978
def process_rdfgraph(self, rg, ont=None): <NEW_LINE> <INDENT> if ont is None: <NEW_LINE> <INDENT> ont = Ontology() <NEW_LINE> subjs = list(rg.subjects(RDF.type, SKOS.ConceptScheme)) <NEW_LINE> if len(subjs) == 0: <NEW_LINE> <INDENT> logging.warning("No ConceptScheme") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ont.i...
Transform a skos terminology expressed in an rdf graph into an Ontology object Arguments --------- rg: rdflib.Graph graph object Returns ------- Ontology
625941d18a349b6b435e8310
def init_bert_weights(module): <NEW_LINE> <INDENT> if isinstance(module, (torch.nn.Linear, torch.nn.Embedding)): <NEW_LINE> <INDENT> module.weight.data.normal_(mean = 0.0, std = 0.02) <NEW_LINE> <DEDENT> elif isinstance(module, BertLayerNorm): <NEW_LINE> <INDENT> module.bias.data.zero_() <NEW_LINE> module.weight.data.f...
Initialize the weights.
625941d17b25080760e395f5
def add_at_back(self, item): <NEW_LINE> <INDENT> self.items.insert(0, item)
To adds a new item to the back (rear) of the deque
625941d17b180e01f3dc4998
@wrap_name_default() <NEW_LINE> @layer_support() <NEW_LINE> def crop_layer(input, offset, axis=2, shape=None, name=None, layer_attr=None): <NEW_LINE> <INDENT> if isinstance(input, LayerOutput): <NEW_LINE> <INDENT> input = [input] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert isinstance(input, collections.Sequenc...
The crop layer crops images by offset and shape. User can set crop shape by args 'shape' explicitly or by reference input layer. The example usage is: .. code-block:: python crop = crop_layer(input=[image_input, reference_input], axis=2, offset=[2, 3]) :param input: The input layer.If two inputs were setted, ...
625941d1ff9c53063f47c38f
def xml(obj): <NEW_LINE> <INDENT> return (obj.__xml__())
Used to convert either - a django model decorated with :func:`easymode.tree.decorators.toxml` - a queryset obtained by querying a model decorated with :func:`easymode.tree.decorators.toxml` - an :class:`easymode.tree.query.XmlQuerySetChain` to xml
625941d150485f2cf553cf36
def test_validate_current_and_prefix_locales_are_non_default_and_same(self): <NEW_LINE> <INDENT> activate('de') <NEW_LINE> try: <NEW_LINE> <INDENT> self.validator('/de/test/') <NEW_LINE> <DEDENT> except ValidationError: <NEW_LINE> <INDENT> self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!')
Current locale is non-default ("de"), URL has locale prefix of non-default locale ("de").
625941d1be8e80087fb20dde
def ra_dec_z(x, v, cosmo=None): <NEW_LINE> <INDENT> if cosmo is None: <NEW_LINE> <INDENT> cosmo = cosmology.FlatLambdaCDM(H0=0.7, Om0=0.3) <NEW_LINE> <DEDENT> c_km_s = c.to('km/s').value <NEW_LINE> x = x/cosmo.h <NEW_LINE> r = np.sqrt(x[:, 0]**2+x[:, 1]**2+x[:, 2]**2) <NEW_LINE> ct = x[:, 2]/r <NEW_LINE> st = np.sqrt(1...
Calculate the ra, dec, and redshift assuming an observer placed at (0,0,0). Parameters ---------- x: array_like Npts x 3 numpy array containing 3-d positions in Mpc/h v: array_like Npts x 3 numpy array containing 3-d velocities in km/s cosmo : object, optional Instance of an Astropy `~astropy.cosmology` ...
625941d18e05c05ec3eea512
def test_update_a_dish(self): <NEW_LINE> <INDENT> self.login_client('test_user', 'testing') <NEW_LINE> response = self.make_a_request( kind="put", version="v1", id=2, data=self.valid_data ) <NEW_LINE> self.assertEqual(response.data, self.valid_data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) ...
This test ensures that a single dish can be updated. In this test we update the second dish in the db with valid data and the third dish with invalid data and make assertions
625941d1566aa707497f4703
def query(self, query, timeout=30): <NEW_LINE> <INDENT> return self.__connection.query(query)
Execute a query and return the result set.
625941d199cbb53fe6792d82
def ionization_constant_water(temperature=298.15, density=None): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> n = 6 <NEW_LINE> alpha_0 = -0.864671 <NEW_LINE> alpha_1 = 8659.19 <NEW_LINE> alpha_2 = -22786.2 <NEW_LINE> beta_0 = 0.642044 <NEW_LINE> beta_1 = -56.8534 <NEW_LINE> beta_2 = -0.375754 <NEW_LINE> Mw = 18.01...
Calculate the ionizatoin constant (Kw) of water at the fiven temperature and 0.1 MPa pressure. If you pass a density, it will use this density indead of the 0.1 MPa pressure. Data from: Bandura etal., J. Phys. Chem. Ref. Data, Vol. 35, No. 1, 2006 DOI: 10.1063/1.1928231
625941d1d164cc6175782eea
def test_privatize_vaults(self): <NEW_LINE> <INDENT> g = Game() <NEW_LINE> g.add_player(uuid4(), 'p0') <NEW_LINE> g.add_player(uuid4(), 'p1') <NEW_LINE> gs = g <NEW_LINE> p0, p1 = gs.players <NEW_LINE> latrine, insula, statue, road = cm.get_cards(['Latrine', 'Insula', 'Statue', 'Road']) <NEW_LINE> p0.vault.set_content(...
Test hiding all vaults.
625941d16fece00bbac2d8db
def build(self, rgb): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> print("build model started") <NEW_LINE> rgb_scaled = rgb <NEW_LINE> red, green, blue = tf.split(axis=3, num_or_size_splits=3, value=rgb_scaled) <NEW_LINE> bgr = tf.concat(axis=3, values=[ blue - VGG_MEAN[0], green - VGG_MEAN[1], red - VGG_MEA...
load variable from npy to build the VGG :param rgb: rgb image [batch, height, width, 3] values scaled [0, 1]
625941d10383005118ecf77e
def _parse_request_line(line): <NEW_LINE> <INDENT> request_line = line.split(' ') <NEW_LINE> method = request_line[0] <NEW_LINE> path = request_line[1] <NEW_LINE> http_version = request_line[2] <NEW_LINE> assert http_version == HTTP_VERSION <NEW_LINE> return method, path
Parses the request line. Returns the method and path.
625941d12eb69b55b151ca4c
def request_the_next_step(main_url, next_uri): <NEW_LINE> <INDENT> result_url = main_url + next_uri <NEW_LINE> return get_request(result_url, 'next')
Obtain the next step
625941d197e22403b379d136
def get_dio_value(self, io_line): <NEW_LINE> <INDENT> sample = self.read_io_sample() <NEW_LINE> if not sample.has_digital_values() or io_line not in sample.digital_values.keys(): <NEW_LINE> <INDENT> raise OperationNotSupportedException("Answer does not contain digital values for the given IO_LINE") <NEW_LINE> <DEDENT> ...
Returns the digital value of the provided IO line. The provided IO line must be previously configured as digital I/O. To do so, use :meth:`.AbstractXBeeDevice.set_io_configuration`. Args: io_line (:class:`.IOLine`): the DIO line to gets its digital value. Returns: :class:`.IOValue`: current value of the prov...
625941d16fb2d068a760f23b
def rollback(self): <NEW_LINE> <INDENT> self.__connection.rollback()
Rollback the transaction.
625941d166673b3332b9222e
def test_diag(): <NEW_LINE> <INDENT> x = theano.tensor.vector() <NEW_LINE> y = diag(x) <NEW_LINE> assert y.owner.op.__class__ == AllocDiag <NEW_LINE> x = theano.tensor.matrix() <NEW_LINE> y = extract_diag(x) <NEW_LINE> assert y.owner.op.__class__ == ExtractDiag <NEW_LINE> x = theano.tensor.tensor3() <NEW_LINE> ok = Fal...
Test that linalg.diag has the same behavior as numpy.diag. numpy.diag has two behaviors: (1) when given a vector, it returns a matrix with that vector as the diagonal. (2) when given a matrix, returns a vector which is the diagonal of the matrix. (1) and (2) are tested by test_alloc_diag and test_extract_diag respect...
625941d1956e5f7376d71009
def call(self, inputs: Mapping[Any, nd.NumDict]) -> nd.NumDict: <NEW_LINE> <INDENT> return self.strengths
Return stored strengths.
625941d1a79ad161976cc2e2
def download_suricata_rule_event(self, event_id): <NEW_LINE> <INDENT> url = urljoin(self.root_url, 'events/nids/suricata/download/{}'.format(event_id)) <NEW_LINE> response = self.__prepare_request('GET', url, output_type='rules') <NEW_LINE> return response
Download one suricata rule event. :param event_id: ID of the event to download (same as get)
625941d1e64d504609d749dc
def __error(self, error_message, position=None): <NEW_LINE> <INDENT> if position is None: <NEW_LINE> <INDENT> position = max(0, self.__scanner.position - 1) <NEW_LINE> <DEDENT> raise JsonParseException( error_message, position, self.__scanner.line_number_for_offset(position - self.__scanner.position), )
Report an error at the character just consumed.
625941d167a9b606de4a8056
@media.route('/albums/search', methods=['GET']) <NEW_LINE> @required_params({'title': str}) <NEW_LINE> def albums_by_title(title): <NEW_LINE> <INDENT> if title == '' or title.isspace(): <NEW_LINE> <INDENT> return msg.errors.bad_request('Title parameter is an empty string') <NEW_LINE> <DEDENT> per_page = request.args.ge...
Returns all albums matching specified title
625941d1ff9c53063f47c390
def function_2(): <NEW_LINE> <INDENT> pass
Docstring for function_1
625941d115fb5d323cde0cad
@_get_client <NEW_LINE> def image_member_count(client, image_id): <NEW_LINE> <INDENT> return client.image_member_count(image_id=image_id)
Return the number of image members for this image :param image_id: identifier of image entity
625941d1a05bb46b383ec9be
def exit_enable_mode(self, exit_command: str = "") -> str: <NEW_LINE> <INDENT> output = "" <NEW_LINE> if self.check_enable_mode(): <NEW_LINE> <INDENT> self.write_channel(self.normalize_cmd(exit_command)) <NEW_LINE> output += self.read_until_prompt() <NEW_LINE> if self.check_enable_mode(): <NEW_LINE> <INDENT> raise Valu...
Exit enable mode. :param exit_command: Command that exits the session from privileged mode :type exit_command: str
625941d1fb3f5b602dac3830
def main(): <NEW_LINE> <INDENT> if len(sys.argv) == 6: <NEW_LINE> <INDENT> fname = sys.argv[1] <NEW_LINE> cleaned_fname = sys.argv[2] <NEW_LINE> stats_fname = sys.argv[3] <NEW_LINE> histo_dir = sys.argv[4] <NEW_LINE> scatter_dir = sys.argv[5] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Usage: data_file_name cl...
example run files\patient_data_to_clean.csv files\patient_data_cleaned.csv files\patient_data_stats.csv figures\patient_age_histograms figures\patient_fim_scatters
625941d185dfad0860c3aff8
def close(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print('关闭浏览器') <NEW_LINE> self.browser.close() <NEW_LINE> del self.browser <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> print('Browser not opened')
关闭 :return:
625941d14d74a7450ccd4360
def fromDetector(self, detector): <NEW_LINE> <INDENT> self._detectorName = detector.getName() <NEW_LINE> self._detectorSerial = detector.getSerial() <NEW_LINE> self._detectorId = detector.getId() <NEW_LINE> self.hasLinearity = True <NEW_LINE> for amp in detector.getAmplifiers(): <NEW_LINE> <INDENT> ampName = amp.getNam...
Read linearity parameters from a detector. Parameters ---------- detector : `lsst.afw.cameraGeom.detector` Input detector with parameters to use. Returns ------- calib : `lsst.ip.isr.Linearizer` The calibration constructed from the detector.
625941d18e7ae83300e4b169
def append(self, error): <NEW_LINE> <INDENT> longitude, latitude = self.transformer_out_in.transform(error.y, error.x) <NEW_LINE> self.error_cache.append('{};{};{};{}'.format(error.identifier, error.error_type, latitude, longitude)) <NEW_LINE> self.total_size += 1 <NEW_LINE> if len(self.error_cache) >= self.cache_size:...
:param error: :return:
625941d1090684286d50ee83
def time_exponential_shoot(): <NEW_LINE> <INDENT> logger = logging.getLogger("time_exponential") <NEW_LINE> rng = galsim.UniformDeviate(RANDOM_SEED) <NEW_LINE> image = galsim.ImageF(IMAGE_XMAX, IMAGE_YMAX) <NEW_LINE> image.setScale(PIXEL_SCALE) <NEW_LINE> t1 = time.time() <NEW_LINE> for i in range(NIMAGES): <NEW_LINE> ...
Shoot photons through an Exponential profile recording times for comparison between USE_COS_SIN method in SBProfile.cpp and the unit circle rejection method, and for comparing the customized radius sampling method against the use of the OneDimensionalDeviate with a Sersic(n=1) profile.
625941d1498bea3a759b9c4b
def __init__(self, name, choices=9): <NEW_LINE> <INDENT> assert (name is not None and len(name) == 2) <NEW_LINE> self.__name = name <NEW_LINE> self.__values = ''.join(str(d) for d in range(1, choices + 1)) <NEW_LINE> self.__peers = set() <NEW_LINE> self.__units = []
Creates a Sudoku Cell :param name: the name of the cell (row-column) :param choices: the number of choices the cell can have :return: SudokuCell
625941d1e8904600ed9f20cb
def get_ad_group_criterion_simulation( self, resource_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): <NEW_LINE> <INDENT> if 'get_ad_group_criterion_simulation' not in self._inner_api_calls: <NEW_LINE> <INDENT> self._inner_api_calls[ 'get_ad_group_cr...
Returns the requested ad group criterion simulation in full detail. Args: resource_name (str): The resource name of the ad group criterion simulation to fetch. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be r...
625941d123849d37ff7b322c
def travellingSalesman(nodeStart, nodes): <NEW_LINE> <INDENT> global bestDistance <NEW_LINE> global bestPaths <NEW_LINE> bestDistance = float('inf') <NEW_LINE> bestPaths = [] <NEW_LINE> distance = 0 <NEW_LINE> path = [] <NEW_LINE> TSM_auxi(nodeStart, nodes, distance, path) <NEW_LINE> return bestDistance, bestPaths
Implementation of the travelling salesman problem algorithm with naïve try.
625941d11b99ca400220ac4e
def parse_args(): <NEW_LINE> <INDENT> parser = ArgumentParser() <NEW_LINE> parser.add_argument('images_path', type=Path) <NEW_LINE> return parser.parse_args()
Extract the images path from the command line arguments.
625941d14f6381625f114bd8
def get_module_qualname_from_path(path): <NEW_LINE> <INDENT> (head, tail) = os.path.split(path) <NEW_LINE> if head == '' or tail == '': <NEW_LINE> <INDENT> raise InvalidModulePath('Invalid python file path: "%s"' ' Missing path or file name' % (path)) <NEW_LINE> <DEDENT> qname = [os.path.splitext(tail)[0]] <NEW_LINE> w...
Get the module's qualified name by analysis of the path. Resolve the absolute pathname and eliminate symlinks. This could result in an incorrect name if symlinks are used to restructure the python lib directory. Starting from the right-most directory component look for __init__.py in the directory component. If it ex...
625941d121a7993f00bc7e8e
def detectCycle(self, head): <NEW_LINE> <INDENT> low, fast = head, head <NEW_LINE> while True: <NEW_LINE> <INDENT> if fast == None or fast.next == None: return None <NEW_LINE> low, fast = low.next, fast.next.next <NEW_LINE> if fast == low: break <NEW_LINE> <DEDENT> while head != fast: <NEW_LINE> <INDENT> head, fast = h...
:type head: ListNode :rtype: ListNode
625941d173bcbd0ca4b2c213
def set_hint_enabled(self, index: int, is_enabled: bool) -> None: <NEW_LINE> <INDENT> self._hints_set[index] = is_enabled <NEW_LINE> self.changed()
Set whether a specific hint is enabled for this grade item. :param index: The index of the hint :param is_enabled: Whether the hint should be set to enabled
625941d1b57a9660fec33a22
@p.command("pack") <NEW_LINE> def genAPM(*args): <NEW_LINE> <INDENT> os.system(binpath + '/avalongen ' + "apm " + " ".join([f"\"{i}\"" for i in sys.argv[2:]]))
Generate .apm file with AvalonGen
625941d1be383301e01b5621
def codons(self): <NEW_LINE> <INDENT> from collections import Counter <NEW_LINE> import pandas as pd <NEW_LINE> frame1 = [] <NEW_LINE> frame2 = [] <NEW_LINE> frame3 = [] <NEW_LINE> i = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> frame1.append(self.seq[i:i+3].upper()) <NEW_LINE> frame2.append(self.seq[i+1:i+4].upper())...
Goes over the three possible reading frames of the sequence and returns the codon count of each one of them. Highlights stop codons.
625941d13539df3088e2e4e8
def test_driver(driver): <NEW_LINE> <INDENT> driver.update() <NEW_LINE> time.sleep(1) <NEW_LINE> driver.update() <NEW_LINE> assert hasattr(driver, 'o'), 'Driver did not generate output' <NEW_LINE> assert not driver.o.data.empty, 'Driver generated empty data'
Test driver general use-case
625941d163d6d428bbe4468c
def GWweights2(returns, muRet, varcovar, epsilon, gamma): <NEW_LINE> <INDENT> T, N = returns.shape <NEW_LINE> sigmap = optSigma2(returns, muRet, varcovar, epsilon, gamma) <NEW_LINE> if sigmap == 10: <NEW_LINE> <INDENT> pi = 10 * np.ones(N) <NEW_LINE> return pi <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> invSigma = ma...
calculates the optimal portfolio weights under Garlappi Wang assumptions
625941d15166f23b2e1a52f6
def __init__(self, data, var, dimensions, dims={}, lon='lon', lat='lat', level='level', time='time', spatial_ax=None, triangles=None): <NEW_LINE> <INDENT> self.set_logger() <NEW_LINE> self.__var = var <NEW_LINE> self.logger.debug("Input arguments:") <NEW_LINE> for arg in ['data', 'dimensions']: <NEW_LINE> <INDENT> self...
Initialization method of DataField2D instance Input: - data: two-dimensional data array - lon: longitude data - lat: latitude data - time: array with time information as datetime instances - level: array with level informations - dimensions: dimension names (e.g. ('lat', 'lon')) in the order as they ...
625941d1ec188e330fd5a93a
def calc_spectrum(self, collenergy, collvelocity): <NEW_LINE> <INDENT> emissivity = numpy.zeros(len(self.ebins)-1, dtype=float) <NEW_LINE> for sig in self.crosssectiondata: <NEW_LINE> <INDENT> Cout = loginterp(collenergy, sig['E'], sig['C']) <NEW_LINE> if Cout > 0: <NEW_LINE> <INDENT> if not sig['n'] in self.spectra.ke...
Calculate the spectrum of the data PARAMETERS ---------- ebins : array(float) The energy bins (in keV) to calcualte the spectrum on collenergy : flaot The collision energy (keV/amu) collvelocity : float The velocity of the center of mass (cm/s) linedata : hdulist The line emissivity data contdata : hdulist T...
625941d1dc8b845886cb56d2
def reverse(x, axes): <NEW_LINE> <INDENT> if isinstance(axes, int): <NEW_LINE> <INDENT> axes = [axes] <NEW_LINE> <DEDENT> return tf.reverse(x, axes)
Reverses a tensor along the specified axes. # Arguments x: Tensor to reverse. axes: Integer or iterable of integers. Axes to reverse. # Returns A tensor. {{np_implementation}}
625941d101c39578d7e74fd8
def get_nyquist_vel(self, scans=None): <NEW_LINE> <INDENT> if scans is None: <NEW_LINE> <INDENT> scans = range(self.nscans) <NEW_LINE> <DEDENT> return self._msg31_rad_array(scans, 'nyquist_vel') * 0.01
Retrieve the Nyquist velocities of the requested scans. Parameters ---------- scans : list or None Scans (0 based) for which the Nyquist velocities will be retrieved. None (the default) will return the velocities for all scans in the volume. Returns ------- velocities : ndarray Nyquist velocities (in ...
625941d1293b9510aa2c3432
def __init__(self, columns, rows): <NEW_LINE> <INDENT> self.columns = columns <NEW_LINE> self.rows = rows <NEW_LINE> self.row = 0 <NEW_LINE> self.col = 0 <NEW_LINE> self.top = 0 <NEW_LINE> self.bot = rows - 1 <NEW_LINE> self.left = 0 <NEW_LINE> self.right = columns - 1 <NEW_LINE> self._cells = [[Cell() for c in range(c...
Initialize the Screen instance.
625941d13617ad0b5ed68094
def init_weights(self): <NEW_LINE> <INDENT> normal_init(self.rpn_conv, std=0.01) <NEW_LINE> bias_cls = bias_init_with_prob(0.01) <NEW_LINE> normal_init(self.rpn_cls, std=0.01, bias=bias_cls) <NEW_LINE> normal_init(self.rpn_reg, std=0.01)
Initialize weights of the head.
625941d16aa9bd52df036f42
def get_file_extension(fname): <NEW_LINE> <INDENT> _, ext = os.path.splitext(fname) <NEW_LINE> return ext
Returns the given file's extension as a string, . included
625941d15fcc89381b1e185d
@target_filter <NEW_LINE> def rotated_square_filter(contour_list, min_area_ratio: RangedNumber(0, 1) = 0.8, min_ratio: RangedNumber(0, 1) = 0.95, max_ratio: RangedNumber(0, 1) = 1.05): <NEW_LINE> <INDENT> output_list = [] <NEW_LINE> for current_contour in contour_list: <NEW_LINE> <INDENT> fill_ratio, bounding_width, bo...
Receives a list of contours and returns only the ones that are approximately square Relation checked is [minimum ratio < (Circle radius / width * height * (square root of 2)) < maximum ratio] :param contour_list: List of Contours to filter :param max_ratio: maximum ratio between radius and sides of bounding rectangle ...
625941d116aa5153ce362615
def joint_positions(self, theta): <NEW_LINE> <INDENT> joint_angles = np.cumsum(theta) <NEW_LINE> normalized_components = np.array([np.cos(joint_angles), np.sin(joint_angles)]).reshape((2, self.n)) <NEW_LINE> components = normalized_components * self.lengths.transpose() <NEW_LINE> return np.cumsum(components, axis=1).re...
Given a theta vector, this returns where the joints will be located.
625941d1cad5886f8bd27176
def plusOne(self, digits): <NEW_LINE> <INDENT> if digits is None or len(digits) < 1: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> carry = 1 <NEW_LINE> for i in range(len(digits)-1, -1, -1): <NEW_LINE> <INDENT> tmp = digits[i] + carry <NEW_LINE> carry = 1 if tmp == 10 else 0 <NEW_LINE> res = 0 if tmp == 10 else tmp...
:type digits: List[int] :rtype: List[int]
625941d1ac7a0e7691ed4268
def __str__(self): <NEW_LINE> <INDENT> return self.text
返回模型字符串表示
625941d1a17c0f6771cbe1ed
def test_custom_logged_out(self) -> None: <NEW_LINE> <INDENT> response = self.client.get('/custom') <NEW_LINE> self.assertIn(b"Please log in", response.data)
TODO: Doku.
625941d17d43ff24873a2e3e
@pytest.fixture <NEW_LINE> def embedding_model(a_backend): <NEW_LINE> <INDENT> return model_with_containers( backend=a_backend, containers=[ {'input' : {'shape' : [10]}, 'name' : 'TEST_input'}, {'embedding' : {'vocab_size' : 100, 'size': 64}}, 'flatten', {'dense' : 3}, {'output' : 'TEST_output'} ] )
Returns a model which tests an embedding layer.
625941d18c3a873295158559
def _read_fields(self, root_node, fields, dtypes=None, root_only=False): <NEW_LINE> <INDENT> if dtypes is None: <NEW_LINE> <INDENT> dtypes = {} <NEW_LINE> <DEDENT> my_dtypes = self._determine_dtypes( fields, override_dict=dtypes) <NEW_LINE> if root_only: <NEW_LINE> <INDENT> fsize = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE...
Read fields from disk for a single tree.
625941d1d486a94d0b98e2e3
def renderForValue(value): <NEW_LINE> <INDENT> pass
Render a single radio button element for a given value. Here the word ``value`` is used in the HTML sense, in other words it is a term token.
625941d11d351010ab855cb9
def remove_file(file_path): <NEW_LINE> <INDENT> file_ws = os.path.dirname(file_path) <NEW_LINE> for file_name in glob.glob(os.path.splitext(file_path)[0] + ".*"): <NEW_LINE> <INDENT> os.remove(os.path.join(file_ws, file_name))
Remove a feature/raster and all of its anciallary files
625941d1b545ff76a8913fb3
def get_mean(number_list): <NEW_LINE> <INDENT> mean = 0 <NEW_LINE> for i in range(len(number_list)): <NEW_LINE> <INDENT> mean += number_list[i] <NEW_LINE> <DEDENT> mean /= len(number_list) <NEW_LINE> return mean
주어진 리스트 숫자들의 평균을 구함. Parameters: number_list (list): integer로 값으로만 구성된 list ex - [10, 33, 22, 99, 33] Returns: mean (int): parameter number_list 숫자들의 평균 Examples: >>> number_list = [39, 54, 32, 11, 99] >>> import basic_math as bm >>> bm.get_mean(number_list...
625941d1507cdc57c6306e7a
def strip_diacritics(s): <NEW_LINE> <INDENT> return u"".join(c for c in unicodedata.normalize('NFKD', s) if not unicodedata.combining(c))
Return s without diacritics.
625941d1956e5f7376d7100a
def get(self, network_id): <NEW_LINE> <INDENT> resp, body = self.request_manager.get('/networks/%s' % network_id) <NEW_LINE> return body['network']
Show network segment details.
625941d18e05c05ec3eea513
def export(self, file_path): <NEW_LINE> <INDENT> directory = os.path.dirname(file_path) <NEW_LINE> if not os.path.isdir(directory): <NEW_LINE> <INDENT> raise RuntimeError( 'The directory needs to exist, please create: ' '{0:s} first'.format(directory)) <NEW_LINE> <DEDENT> if not file_path.lower().endswith('.zip'): <NEW...
Exports the content of the sketch to a ZIP file. Args: file_path (str): a file path where the ZIP file will be saved. Raises: RuntimeError: if sketch cannot be exported.
625941d1cc40096d61595aee
def _estimate_coefficients(self): <NEW_LINE> <INDENT> if self.n_classes == 2: <NEW_LINE> <INDENT> coef_array = np.append(self.model.coef_,self.model.intercept_) <NEW_LINE> coef_names = np.append(self.x_train.columns, 'intercept') <NEW_LINE> coef_df = pd.Series(data=coef_array, index=coef_names, name = 'Coefficients') ...
Returns fitted coeficients. For logistic regression, these are the 'log odds'. Returns ------- coef_df : pd.Series Coefficients of the model.
625941d1d99f1b3c44c6772a
def get_coin_info(self): <NEW_LINE> <INDENT> return self.json_data_obtain(self.url_coin)['Data']
Get general info for all the coins available on the website. Get coin list example https://www.cryptocompare.com/api/data/coinlist/
625941d1d7e4931a7ee9e0bc
def _data(self): <NEW_LINE> <INDENT> self.x = tf.placeholder(tf.float32, [None, flags['image_dim'], flags['image_dim'], 1], name='x') <NEW_LINE> self.epsilon = tf.placeholder(tf.float32, [None, flags['hidden_size']], name='epsilon') <NEW_LINE> self.data = Mnist(self.flags)
Define data I/O
625941d10fa83653e4657158
def __getstate__(self): <NEW_LINE> <INDENT> state = self.__dict__.copy() <NEW_LINE> del state['factory'] <NEW_LINE> if self.factory is not None: <NEW_LINE> <INDENT> state['factory_name'] = self.factory.__name__ <NEW_LINE> state['factory_module'] = self.factory.__module__ <NEW_LINE> <DEDENT> return state
Pickle can't handle the case where the factory can not be found. Instead we save the factory metadata. When unpickle is called we try to load the factory ourselves. If the factory doesn't exist we don't generate an error. This allows access to existing values though no new values can be generated unless the user explic...
625941d10a366e3fb873e9b8
def tag(self, fieldname=None, scale=None, height=None, width=None, css_class=None, direction='keep', **args): <NEW_LINE> <INDENT> if scale is not None: <NEW_LINE> <INDENT> available = self.getAvailableSizes(fieldname) <NEW_LINE> if not scale in available: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> width, heigh...
Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height' and 'width'. If specified, the 'scale' argument will be ...
625941d18da39b475bd65112
def chk_id(self): <NEW_LINE> <INDENT> if self.id not in alive.clients: <NEW_LINE> <INDENT> display.stop(self.display_num); <NEW_LINE> try: id2displaynum.pop(self.id) <NEW_LINE> except: pass <NEW_LINE> display_handlers.pop(self.id) <NEW_LINE> self.clients.pop(self.id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.c...
chks to see if reqid given back
625941d150812a4eaa59c4be
def call(self, inputs, training=False): <NEW_LINE> <INDENT> f_ = inputs <NEW_LINE> links = f_['links'] <NEW_LINE> paths = f_['paths'] <NEW_LINE> seqs = f_['sequences'] <NEW_LINE> shape = tf.stack([ f_['n_links'], int(self.config['HYPERPARAMETERS']['link_state_dim']) - 1 ], axis=0) <NEW_LINE> link_state = tf.concat([ tf...
This function is execution each time the model is called Args: inputs (dict): Features used to make the predictions. training (bool): Whether the model is training or not. If False, the model does not update the weights. Returns: tensor: A tensor containing the per-path delay.
625941d11f037a2d8b94639b
def close_connection(self): <NEW_LINE> <INDENT> self.log.debug("Database offline.") <NEW_LINE> self.cursor.close()
Closes the database connection to avoid issues related to the connectivity.
625941d1d6c5a102081441e9
def hash_md5_readfile(self): <NEW_LINE> <INDENT> filename = self.get_fullname() <NEW_LINE> f = open(filename, 'rb') <NEW_LINE> m = hashlib.md5() <NEW_LINE> readBytes = 1024 ** 2 <NEW_LINE> totalBytes = 0 <NEW_LINE> while readBytes: <NEW_LINE> <INDENT> readString = f.read(readBytes) <NEW_LINE> m.update(readString) <NEW_...
compute a hash of a file @return string
625941d126238365f5f0f00d
def is_gifsicle_installed(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subprocess.call( ['gifsicle', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE> return True <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> return False
Check if gifsicle is installed Returns ------- bool
625941d110dbd63aa1bd2d42
def get_optimizer(data: list, fitness: type(lambda a: a), population_size: int = 10, generations: int = 100, crossover_probability: float = 0.8, mutation_probability: float = 0.05, elitism: bool = True, maximise_fitness: bool = True, create_individual: type(lambda a: a) = None, crossover: type(lambda a: a) = None, muta...
:return: ga Возвращает объект ga. Методы искать в документации pyeasyga. :param data: anything Пример существа, генома. Может быть списков. :param fitness: function Функция приспособленности. :param population_size: int, optional Размер популяции. По умолчанию равен 10. :param generations: int, optional...
625941d1c432627299f04de4
def Mathd_inversePi(): <NEW_LINE> <INDENT> return _fife.Mathd_inversePi()
Mathd_inversePi() -> FIFE::Math< double >::num_type
625941d1287bf620b61d3c01
def testFlag(self): <NEW_LINE> <INDENT> self.RunAndVerify(flag_value='0', expected_output=None, other_flag=None) <NEW_LINE> self.RunAndVerify(flag_value='1', expected_output=EXPECTED_OUTPUT_NO_FILTER, other_flag=None)
Tests using the --gtest_list_tests flag.
625941d1462c4b4f79d1d86f
def clear_display(self): <NEW_LINE> <INDENT> for i in range(8): <NEW_LINE> <INDENT> IO.output(self.pos_pins[7 - i], 1) <NEW_LINE> IO.output(self.neg_pins[7 - i], 0)
Clear all leds on display :return:
625941d1004d5f362079a4d0
def threefry(W, N, ctr, key, Nrounds=None): <NEW_LINE> <INDENT> assert W in (32, 64) <NEW_LINE> assert N in (2, 4) <NEW_LINE> if Nrounds is None: <NEW_LINE> <INDENT> Nrounds = 20 <NEW_LINE> <DEDENT> dtype = numpy.uint32 if W == 32 else numpy.uint64 <NEW_LINE> if N == 2: <NEW_LINE> <INDENT> assert Nrounds <= 32 <NEW_LIN...
W: word length (32, 64) N: number of generated items, 2 or 4 Nrounds: number of rounds (up to 72) ctr: counter, array(N, numpy.uint${W}) key: key, array(N, numpy.uint${W}) returns: array(N, numpy.uint${W}) Note: for W=64, N=4 and Nrounds=72 it is the same as Threefish algorithm from Skein, only without the 128-bit "tw...
625941d150812a4eaa59c4bf
def is_valid_config( config: Dict, ) -> bool: <NEW_LINE> <INDENT> docs = config.get('docs', None) <NEW_LINE> if not docs: <NEW_LINE> <INDENT> print("Missing top-level 'docs' key") <NEW_LINE> return False <NEW_LINE> <DEDENT> repo = docs.get('repo', None) <NEW_LINE> if not repo: <NEW_LINE> <INDENT> print("Missing 'repo' ...
Validate configuration.
625941d123849d37ff7b322d
@pytest.fixture(scope="function", autouse=True) <NEW_LINE> def steam_dir(home_dir): <NEW_LINE> <INDENT> steam_path = home_dir / ".steam" <NEW_LINE> steam_path.mkdir() <NEW_LINE> (steam_path / "root" / "compatibilitytools.d").mkdir(parents=True) <NEW_LINE> (steam_path / "steam" / "appcache" / "librarycache").mkdir(paren...
Fake Steam directory
625941d191f36d47f21ac691
def act(self, obss: List[np.ndarray]) -> List[int]: <NEW_LINE> <INDENT> joint_action = [] <NEW_LINE> for current_agent in range(self.num_agents): <NEW_LINE> <INDENT> c_obss_agent = self.c_obss[current_agent] <NEW_LINE> q_tab = self.q_tables[current_agent] <NEW_LINE> model = self.models[current_agent] <NEW_LINE> if np.r...
Implement the epsilon-greedy action selection here YOU MUST IMPLEMENT THIS FUNCTION FOR Q5 :param obss (List[np.ndarray] of float with dim (observation size)): received observations representing the current environmental state for each agent :return (List[int]): index of selected action for each agent
625941d1627d3e7fe0d68fee
def test_total_prices_anonymous(self): <NEW_LINE> <INDENT> self.response = self.post( "api-basket-add-product", url="http://testserver/api/products/1/", quantity=5, ) <NEW_LINE> self.response.assertStatusEqual(200) <NEW_LINE> self.response.assertValueEqual("total_incl_tax", "50.00")
Test if the prices calculated by the basket are ok
625941d17cff6e4e81117b24
def test_newform(self): <NEW_LINE> <INDENT> r <NEW_LINE> base_url = '/ModularForm/GL2/ImaginaryQuadratic/' <NEW_LINE> self.check_args(base_url+'2.0.11.1/207.6/b', 'Base change') <NEW_LINE> self.check_args(base_url+'2.0.11.1/207.6/b', '2.0.11.1-207.6-b') <NEW_LINE> self.check_args(base_url+'2.0.3.1/44332.1/a/', 'Isogeny...
Check newform pages
625941d1f8510a7c17cf989a
def tail_stream(stream, nlines=10): <NEW_LINE> <INDENT> stream.seek(0, 2) <NEW_LINE> fsize = stream.tell() <NEW_LINE> stream.seek(max(0, fsize - 1024), 0) <NEW_LINE> lines = stream.readlines() <NEW_LINE> return lines[-nlines:]
Returns last N lines from the io object (file or io.string).
625941d14f88993c3716c204
def get_providers(self): <NEW_LINE> <INDENT> return dict(self.providers)
Get the machine providers. @return A dictionary of name/provider mappings.
625941d199fddb7c1c9de52f
def test_missing_apparatus_kind(self): <NEW_LINE> <INDENT> root = etree.Element('experiment') <NEW_LINE> exp = etree.SubElement(root, 'experimentType') <NEW_LINE> exp.text = 'Ignition delay measurement' <NEW_LINE> etree.SubElement(root, 'apparatus') <NEW_LINE> with pytest.raises(MissingElementError) as excinfo: <NEW_LI...
Ensure proper error raised if missing apparatus kind.
625941d160cbc95b062c66e2
@app.route('/api/task/move', methods=['POST']) <NEW_LINE> def move_item(): <NEW_LINE> <INDENT> from_index = int(request.form.get('from')) <NEW_LINE> to_index = int(request.form.get('to')) <NEW_LINE> if to_index < from_index: <NEW_LINE> <INDENT> g.task_controller.move_before(from_index, to_index) <NEW_LINE> <DEDENT> eli...
Moves (reorders) a task. Params: from: Order ID of task to: New order ID of task Note: This moves the task currently at the `to` Order ID to be AFTER the moved task
625941d10c0af96317bb8386
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( description='Argument that can be parsed to the InfluxDB') <NEW_LINE> parser.add_argument('--host', type=str, required=False, default='localhost', help='hostname of InfluxDB http API') <NEW_LINE> parser.add_argument('--port', type=int, required=Fal...
Parse the args.
625941d13539df3088e2e4e9
def items(self, limit=10000, page_limit=500, headers=None): <NEW_LINE> <INDENT> found = self.found(headers=headers) <NEW_LINE> limit = self.limit or limit <NEW_LINE> if found > limit: <NEW_LINE> <INDENT> logger.warning('There are more items found (%s) than the limit (%s) provided.' % (found, limit)) <NEW_LINE> <DEDENT>...
Return all of the Items and Collections for this search
625941d17b180e01f3dc499a
def fetch_all_vulnerabilities(self, page=1, limit=50, href=None): <NEW_LINE> <INDENT> if href: <NEW_LINE> <INDENT> return super().request('GET', '/api/network' + href) <NEW_LINE> <DEDENT> return super().request('GET', f'/api/network/vulnerabilities?_page={page}&_limit={limit}')
Fetches all vulnerabilities one page at a time of limit :param page: The page of the vulnerability to get (optional if you have href) :param limit: The amount of vulnerabilities per page :param href: The link to the next page in the system from a previous call
625941d1ff9c53063f47c391
def load_report_records(report_filename): <NEW_LINE> <INDENT> clones = [] <NEW_LINE> with open(report_filename, "r") as report_fh: <NEW_LINE> <INDENT> reader = csv.DictReader(report_fh, delimiter="\t") <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> if row["Stdn"] == "Y": <NEW_LINE> <INDENT> clone = SequencedClone() ...
Load records from an NCBI CloneDB report into the database.
625941d1460517430c394321
def set_timeticks(self, oid, value, idx=(0,)): <NEW_LINE> <INDENT> value = self.convert_to_timeticks(value) <NEW_LINE> self.set(oid, value, idx)
Does a SNMP SET request after converting the value to a TimeTicks SNMP Object. See also `Set Integer`.
625941d1d8ef3951e32436dc
@app.route('/token') <NEW_LINE> @auth.login_required <NEW_LINE> @swag_from('resources/api_docs/token.yml') <NEW_LINE> def get_auth_token(): <NEW_LINE> <INDENT> exp_time = app.config['EXP_TIME'] <NEW_LINE> token = g.user.generate_auth_token(exp_time) <NEW_LINE> group, group_id = get_group(request.headers['Authorization'...
get token when user log in, and the token will be used as auth in the other API call
625941d1f548e778e58cd71c
def runRdr2Geo(self): <NEW_LINE> <INDENT> if hasattr(self, 'doInSAR'): <NEW_LINE> <INDENT> if not self.doInSAR: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> catalog = isceobj.Catalog.createCatalog(self._insar.procDoc.name) <NEW_LINE> self.updateParamemetersFromUser() <NEW_LINE> referenceTrack = self._insar.l...
compute lat/lon/hgt
625941d12eb69b55b151ca4f
def allow_migrate(self, db, app_label, model_name=None, **hints): <NEW_LINE> <INDENT> if model_name.startswith('postgres'): <NEW_LINE> <INDENT> return db == 'postgres' <NEW_LINE> <DEDENT> return None
Make sure the postgres app only appears in the 'postgres db' database.
625941d16fece00bbac2d8dd
def add_record(graph, record): <NEW_LINE> <INDENT> graph.add_edge(record[1], record[3], attr_dict={'sport': record[2], 'dport': record[4], 'stime_epoch_secs': record[5], 'etime_epoch_secs': record[6]}) <NEW_LINE> return graph
Add one record to a graph. :params graph: networkx graph. :params record: record for an edge. :return: graph, as modified in place.
625941d12eb69b55b151ca4e
def get_amica_menu(name, restaurant_number, language='en'): <NEW_LINE> <INDENT> monday = date.today() <NEW_LINE> menu = {} <NEW_LINE> if monday.weekday() != 0: <NEW_LINE> <INDENT> monday -= timedelta(days=monday.weekday()) <NEW_LINE> <DEDENT> day_str = monday.strftime('%Y-%m-%d') <NEW_LINE> url = 'http://www.amica.fi/a...
Fetches the menu for the current week of Amica restaurants from their API.
625941d1d164cc6175782eec
def deletePortForwardRule(self, dstaddress, dstport): <NEW_LINE> <INDENT> results = self._do_filtered( '/ip/firewall/nat/print', filters=[ '=.proplist=.id', '?dst-address=%s' % dstaddress, '?dst-port=%s' % dstport]) <NEW_LINE> for i in results: <NEW_LINE> <INDENT> self.do('/ip/firewall/nat/remove', args=i) <NEW_LINE> <...
Delete portforward
625941d1046cf37aa974cee5
def test_refresh_token_for_user(self): <NEW_LINE> <INDENT> payload = {'email': 'test@qdstudio.com', 'password': 'password123'} <NEW_LINE> create_user(**payload) <NEW_LINE> res = self.client.post(OBTAIN_TOKEN_URL, payload) <NEW_LINE> payload = {'refresh': res.data['refresh']} <NEW_LINE> res_refresh = self.client.post(RE...
Test that JWT token can be refreshed using refresh token.
625941d1656771135c3eba0e