code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def unixtime_to_datetime(self, unixtime): <NEW_LINE> <INDENT> dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(0, unixtime) <NEW_LINE> return dt
Return datetime (UTC) for a given unixtime. Parameters ---------- unixtime : int The unixtime to convert to datetime. Returns ------- datetime : datetime.datetime The datetime (UTC) corresponding to the given unixtime.
625941e244b2445a33932453
def next_month(dt): <NEW_LINE> <INDENT> from datetime import date, timedelta <NEW_LINE> temp = date(dt.year, dt.month, 15) + timedelta(days=30) <NEW_LINE> try: <NEW_LINE> <INDENT> return date(temp.year, temp.month, dt.day) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> temp = dt + timedelta(days=45) <NEW_LINE> return ...
Change the month of given date. If day is out of range, make it the last day of that month.
625941e238b623060ff0b1ad
def replace_vars_in_targets(targets, values): <NEW_LINE> <INDENT> retval = [] <NEW_LINE> for o in targets: <NEW_LINE> <INDENT> retval.append(replace_vars_in_dict(o, values)) <NEW_LINE> <DEDENT> return retval
Replace all occurrences of variables in the targets with the values.
625941e21f5feb6acb0c4f0a
def testNamedDescribedWorkflowStartEventType(self): <NEW_LINE> <INDENT> pass
Test NamedDescribedWorkflowStartEventType
625941e2ac7a0e7691ed4485
def process_place(self, place): <NEW_LINE> <INDENT> token_info = _TokenInfo(self._cache) <NEW_LINE> names = place.name <NEW_LINE> if names: <NEW_LINE> <INDENT> token_info.add_names(self.conn, names) <NEW_LINE> if place.is_country(): <NEW_LINE> <INDENT> self.add_country_names(place.country_code, names) <NEW_LINE> <DEDEN...
Determine tokenizer information about the given place. Returns a JSON-serialisable structure that will be handed into the database via the token_info field.
625941e266673b3332b92451
def disk_usage(self): <NEW_LINE> <INDENT> is_open = self._fortran_is_open() <NEW_LINE> if not is_open: <NEW_LINE> <INDENT> self.read_header() <NEW_LINE> <DEDENT> HS = 2 * self._nspin * self._nk <NEW_LINE> SE = HS / 2 * self._nE <NEW_LINE> mem = (HS + SE) * self._no_u ** 2 * 16 / 1024 ** 3 <NEW_LINE> if not is_open: <NE...
Calculate the estimated size of the resulting file Returns ------- estimated disk-space used in GB
625941e2460517430c39453c
def test_upload_file(self): <NEW_LINE> <INDENT> file_name = "test_upload_file.jpg" <NEW_LINE> src = TestHelper.get_local_folder() + file_name <NEW_LINE> dst = TestHelper.get_folder() + "/" + file_name <NEW_LINE> result = self.api.upload_file(dst, src) <NEW_LINE> self.assertTrue(len(result.uploaded) == 1) <NEW_LINE> sel...
Test case for upload_file Upload a specific file
625941e2b545ff76a89141d5
def redirect(request, next, template_name='redirect.html'): <NEW_LINE> <INDENT> if not next.startswith('http'): <NEW_LINE> <INDENT> next = '/%s%s' % (request.get_host(), next) <NEW_LINE> <DEDENT> logging.info('Redirect to %r' % next) <NEW_LINE> return render_to_response(template_name, { 'next': next })
Show a simple page which does a javascript redirect, closing any popup enclosing us
625941e285dfad0860c3b21b
def average_of_layer_average(outputs): <NEW_LINE> <INDENT> hidden_states = outputs[2] <NEW_LINE> sentence_embedding = [] <NEW_LINE> for layers in hidden_states: <NEW_LINE> <INDENT> token_layer = layers[0] <NEW_LINE> for token_embedding in token_layer: <NEW_LINE> <INDENT> layer_average = torch.mean(token_embedding, dim=...
Averaging the average of each layer tokens. :param outputs: BERT model output, :return a 768 length vector formed by averaging the average embedding of each layer tokens
625941e2cdde0d52a9e533f5
def archGetNopInstr(self): <NEW_LINE> <INDENT> raise ArchNotImplemented("archGetNopInstr")
Return a python string of the byte sequence that corresponds to a no-op (if present) for this architecture. Return None if not present for this architecture.
625941e2aad79263cf390e07
def max_depth(l: list): <NEW_LINE> <INDENT> return isinstance(l, list) and max(map(max_depth, l)) + 1
Maximum depth of a list, found recursively.
625941e27c178a314d6ef825
def test_post_expired_token_failing_jwt_auth(self): <NEW_LINE> <INDENT> token = jwt_encode_user(self.user, DEFAULT_TARGET, override={'exp': 1}) <NEW_LINE> auth = 'JWT {0}'.format(token) <NEW_LINE> response = self.csrf_client.post( '/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json') <NEW_LINE> msg =...
Ensure POSTing over JWT auth with expired token fails
625941e2a05bb46b383ecbdf
def GalLon(self): <NEW_LINE> <INDENT> return _stomp.Pixel_GalLon(self)
GalLon(self) -> double
625941e23eb6a72ae02ec8a7
def computeUVForFiles(filePaths, filePattern): <NEW_LINE> <INDENT> pass
Given a collection of paths to a file and the UV pattern it matches compute the 0-based UV tile indicated by the file name. If a filePath or the pattern are poorly formed then (0,0) is returned for that path.
625941e28a43f66fc4b54421
def create_rfs(self): <NEW_LINE> <INDENT> assert hasattr(self, 'xs'), "please set up the grid first" <NEW_LINE> self.grid_rfs = np.rot90(gauss2D_iso_cart( x=self.stimulus.x_coordinates[..., np.newaxis], y=self.stimulus.y_coordinates[..., np.newaxis], mu=np.array([self.xs.ravel(), self.ys.ravel()]), sigma=self.sizes.rav...
create_rfs creates rfs for the grid
625941e2e64d504609d74c00
def get_source_targets(self): <NEW_LINE> <INDENT> with open(self.loading_plan_path, "r") as fd: <NEW_LINE> <INDENT> d = json.load(fd) <NEW_LINE> <DEDENT> tgts = [] <NEW_LINE> for path in d["dataset_done_files"]: <NEW_LINE> <INDENT> tgts.append(SrcVolumeTarget(os.path.splitext(path)[0] + ".plan")) <NEW_LINE> <DEDENT> re...
Return the SrcVolumeTargets required to read this volume
625941e226068e7796caf0a5
def unload(*args): <NEW_LINE> <INDENT> return _cspice.unload(*args)
unload(char CONST_STRING)
625941e263f4b57ef00014cf
def full_join(self, table_a, table_b, test): <NEW_LINE> <INDENT> return full_join(test, **{table_a: self[table_a], table_b: self[table_b]})
Full joins tables and views by name using test.
625941e2498bea3a759b9e6e
def parse_ceiling(ceil, floor): <NEW_LINE> <INDENT> return parse_extreme(ceil, floor, 999, "FINAL < INITIAL, TRY AGAIN", "FINAL > 999, TRY AGAIN")
Check if ceiling value is OK. :param ceil: Ending OS version. :type ceil: int :param floor: Starting OS version. :type floor: int
625941e232920d7e50b28593
def run(self, input_objs, input_hashes): <NEW_LINE> <INDENT> env = input_objs <NEW_LINE> block = ast.parse(self.code) <NEW_LINE> if len(block.body) > 0 and type(block.body[-1]) is ast.Expr: <NEW_LINE> <INDENT> last = ast.Expression(block.body.pop().value) <NEW_LINE> exec(compile(block, '<string>', mode='exec'), env) <N...
Execute this node in the provided environment given hashes of inputs
625941e29c8ee82313fbbb36
def key_callback(self, window, key, scancode, action, mods): <NEW_LINE> <INDENT> if key == glfw.KEY_ESCAPE and action == glfw.PRESS: <NEW_LINE> <INDENT> glfw.set_window_should_close(self.window, True)
press ESCAPE to quit the application
625941e28e05c05ec3eea738
def ensure_locale(): <NEW_LINE> <INDENT> locale_conf = slurp('/etc/default/locale') <NEW_LINE> for line in locale_conf.split('\n'): <NEW_LINE> <INDENT> if line.startswith('#'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if "LC_ALL" in line: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> new_locale = "LC_...
Makes sure LC_ALL is defined to something sensible
625941e28e71fb1e9831db68
def beam(self, number): <NEW_LINE> <INDENT> ray = Ray(number) <NEW_LINE> result = 'null' <NEW_LINE> end = 0 <NEW_LINE> if self.reflection(ray) is True: <NEW_LINE> <INDENT> result = 'R' <NEW_LINE> self.setmarker(number, result, end) <NEW_LINE> return result <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> check = sel...
Send ray through board at given marker number. Returns fate of ray and adjusts score accordingly. Possible return values are 'reflection', 'hit', or number of exit. Score increases by for every marker assigned: +1 for every hit or reflection and +2 if the ray leaves the board.
625941e2c4546d3d9de72df7
def prune(node, examples): <NEW_LINE> <INDENT> return pruneRecurse(node,node,examples)
Takes in a trained tree and a validation set of examples. Prunes nodes in order to improve accuracy on the validation data; the precise pruning strategy is up to you.
625941e207f4c71912b11845
def test_load_low_level_none(self): <NEW_LINE> <INDENT> with self.assertRaises(db.exceptions.NoDataFoundException): <NEW_LINE> <INDENT> db.data.load_low_level(self.test_mbid) <NEW_LINE> <DEDENT> one = {"data": "one", "metadata": {"audio_properties": {"lossless": True}, "version": {"essentia_build_sha": "x"}}} <NEW_LINE...
If no lowlevel data is loaded, or offset is too high, an exception is raised
625941e266673b3332b92452
def relu_backward(dout, cache): <NEW_LINE> <INDENT> x = cache <NEW_LINE> dx = dout * (x>0).astype(int) <NEW_LINE> return dx
Computes the backward pass for a layer of rectified linear units (ReLUs). Input: - dout: Upstream derivatives, of any shape - cache: Input x, of same shape as dout Returns: - dx: Gradient with respect to x
625941e2bf627c535bc13590
def processWithScriptedCLI(self): <NEW_LINE> <INDENT> logging.info('Scheduling processing with scipted CLIs started') <NEW_LINE> cliParams = { 'name': "Scripted CLI One", } <NEW_LINE> logging.info('Starting %s' % cliParams['name']) <NEW_LINE> cliNode = slicer.cli.run(slicer.modules.paralleltestcli, None, cliParams, wai...
Starts two scripted CLIs asynchronously.
625941e25f7d997b87174e5c
def _calcresp(calfile, nfft, sampfreq): <NEW_LINE> <INDENT> poles, zeros, scale_fac = readPaz(calfile) <NEW_LINE> h, f = pazToFreqResp(poles, zeros, scale_fac, 1.0 / sampfreq, nfft, freq=True) <NEW_LINE> return h, f
Calculate transfer function of known system. :type calfile: str :param calfile: file containing poles, zeros and scale factor for known system :returns: complex transfer function, array of frequencies
625941e22c8b7c6e89b35b7e
def test_view_categories(self): <NEW_LINE> <INDENT> self.create_user() <NEW_LINE> self.create_category() <NEW_LINE> with self.client: <NEW_LINE> <INDENT> headers = self.helper_login_with_token() <NEW_LINE> response = self.client.get('/category/', content_type='application/json', headers=headers) <NEW_LINE> reply = json...
Test the viewing of all categories at once with pagination
625941e2956e5f7376d7122c
def analyse_file_in_chunks(path_to_file): <NEW_LINE> <INDENT> fsize = os.stat(path_to_file).st_size <NEW_LINE> sample_prop = max_filesize / fsize <NEW_LINE> line_count = count_lines(path_to_file) <NEW_LINE> chunks = round(line_count * sample_prop) <NEW_LINE> temp = {} <NEW_LINE> data_iterator = pd.read_csv(path_to_file...
Given a path to a large dataset we will iteratively load it in chunks and build out the statistics necessary to summarise the whole dataset.
625941e27c178a314d6ef826
def grab_next(self, timeout: typing.Optional[float] = None) -> typing.Sequence[DataAndMetadata.DataAndMetadata]: <NEW_LINE> <INDENT> with self.__buffer_lock: <NEW_LINE> <INDENT> self.__buffer = list() <NEW_LINE> <DEDENT> return self.grab_latest(timeout)
Grab the next data to finish from the buffer, blocking until one is available.
625941e250485f2cf553d15b
@app.route('/good/add', methods=['POST']) <NEW_LINE> def add_good_api(): <NEW_LINE> <INDENT> if not config.DEBUG: <NEW_LINE> <INDENT> limit_to_localhost() <NEW_LINE> <DEDENT> payload = request.get_json(silent=True) <NEW_LINE> try: <NEW_LINE> <INDENT> offer_id = payload.get('offer_id', None) <NEW_LINE> good_type = paylo...
internal endpoint used to populate the server with goods
625941e250485f2cf553d15c
def get_path_output_convert(app: object) -> NoReturn: <NEW_LINE> <INDENT> output_path = QtWidgets.QFileDialog.getExistingDirectory( None, "Procurar Diretório de Destino.", r"%s" % app.current_directory_convert, ) <NEW_LINE> if output_path: <NEW_LINE> <INDENT> app.output_path_convert = output_path <NEW_LINE> app.line_ed...
Factory para busca do path de saída das conversões.
625941e232920d7e50b28594
def psm(control, treatment, use_col = None, stratified_col = None, k = 1): <NEW_LINE> <INDENT> if use_col: <NEW_LINE> <INDENT> used_control, used_treatment = control[:, use_col], treatment[:, use_col] <NEW_LINE> <DEDENT> indices = stratified_matching(used_control, used_treatment, stratified_col = stratified_col) <NEW_L...
Select matched sample from control by naming: [Args] ------ use_col = the columns' index you want to use in the matching stratified_col = the stratify order you defined k = how many sample selected from control group for each treatment sample
625941e2379a373c97cfaf07
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Convert ULog to CSV') <NEW_LINE> parser.add_argument('filename', metavar='file.ulg', help='ULog input file') <NEW_LINE> parser.add_argument( '-m', '--messages', dest='messages', help=("Only consider given messages. Must be a comma-separated l...
Command line interface
625941e26aa9bd52df037166
def test_handle_delete_error(DeleteTemplateSideEffect): <NEW_LINE> <INDENT> with pytest.raises(exception.ResourceFailure): <NEW_LINE> <INDENT> DeleteTemplateSideEffect.handle_delete()
Currently, test exists to satisfy 100% code coverage.
625941e255399d3f05588a77
def volumeChanged(self, value): <NEW_LINE> <INDENT> self.playerCore.setVolume(value) <NEW_LINE> if value == 0: <NEW_LINE> <INDENT> self.buttons['mute'].setIcon(QIcon('icons/mute.png')) <NEW_LINE> <DEDENT> elif value <= 35: <NEW_LINE> <INDENT> self.buttons['mute'].setIcon(QIcon('icons/volumeMin.png')) <NEW_LINE> <DEDENT...
Set player's volume to value. Set icon for sound.
625941e216aa5153ce362838
def get_isolated_genes(genome, min_Gap, minLength): <NEW_LINE> <INDENT> path = get_config("RNA_ref_"+genome, "gencode") <NEW_LINE> df = pd.read_table(path, comment="#", header=None, names=["chr", "source", "type", "start", "end", "dot", "strand", "dot2", "infos"]) <NEW_LINE> df = df.loc[df.type==type] <NEW_LINE> infos ...
Get The Isolated Genes Which Do not Have Genes At upstream and downstream. :param genome: Genome Version Name like hg38. :param min_Gap: mininum distance to the upstream and downstream Gene. :param minLength: mininum length of the gene. :return: A int ... :rtype: list
625941e26fb2d068a760f463
def test_find_events(): <NEW_LINE> <INDENT> events = read_events(fname) <NEW_LINE> raw = fiff.Raw(raw_fname) <NEW_LINE> events2 = find_events(raw) <NEW_LINE> assert_array_almost_equal(events, events2)
Test find events in raw file
625941e2d18da76e2353289b
def max_quadratic_utility(self, risk_aversion=1, market_neutral=False): <NEW_LINE> <INDENT> if risk_aversion <= 0: <NEW_LINE> <INDENT> raise ValueError("risk aversion coefficient must be greater than zero") <NEW_LINE> <DEDENT> update_existing_parameter = self.is_parameter_defined("risk_aversion") <NEW_LINE> if update_e...
Maximise the given quadratic utility, i.e: .. math:: \max_w w^T \mu - \frac \delta 2 w^T \Sigma w :param risk_aversion: risk aversion parameter (must be greater than 0), defaults to 1 :type risk_aversion: positive float :param market_neutral: whether the portfolio should be market neutral (...
625941e267a9b606de4a8278
def _vm_cleanup(mgmt, vm_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logger.info("VM/Instance status: %s", mgmt.vm_status(vm_name)) <NEW_LINE> <DEDENT> except Exception as f: <NEW_LINE> <INDENT> logger.error( "Could not retrieve VM/Instance status: %s: %s", type(f).__name__, str(f)) <NEW_LINE> <DEDENT> logger.i...
Separated to make the logic able to propagate the exceptions directly.
625941e2d268445f265b522f
def shutdown(self): <NEW_LINE> <INDENT> self.fomega2.close() <NEW_LINE> self.fqc.close() <NEW_LINE> self.fpc.close()
Prepare to end simulation by safely closing any open files and removing temporary files
625941e25166f23b2e1a551a
def getConnectState(self): <NEW_LINE> <INDENT> self.log.info("[getConnectState]") <NEW_LINE> state = self.dynamicCall("GetConnectState()") <NEW_LINE> return state
현재 접속상태를 반환합니다. 반환되는 접속상태는 아래와 같습니다. 0: 미연결, 1: 연결 :return: int
625941e294891a1f4081be6c
def _VerifyRange(r_op, limit, forward, start_key, exp_keys, exp_last_key): <NEW_LINE> <INDENT> result = self._client.Query(table='RangeTest', hash_key=hash_key, range_operator=r_op, callback=None, attributes=['test_hk', 'test_rk', 'attr1', 'attr2'], limit=limit, scan_forward=forward, excl_start_key=(DBKey(hash_key, sta...
Returns the result
625941e2b7558d58953c52cd
def list_acords_by_ens_obj(self, ens): <NEW_LINE> <INDENT> return sorted( [acord.getObject() for acord in self.catalog.searchResults( portal_type='genweb.ens.acord', path={ 'query': self.get_path(ens), 'depth': 1 })], key=get_sortable_key_by_date, reverse=True)
List acord(s) related to the specified ens.
625941e23617ad0b5ed682b7
def find_zero_phase(prc, est_ix): <NEW_LINE> <INDENT> len_prc = len(prc) <NEW_LINE> assert est_ix < len(prc) <NEW_LINE> assert est_ix >= 0 <NEW_LINE> zero_ixs = { 1: len_prc, -1:-len_prc} <NEW_LINE> for dirn in [1, -1]: <NEW_LINE> <INDENT> ix = est_ix + dirn <NEW_LINE> while ix >= 0 and ix < len_prc: <NEW_LINE> <INDENT...
prc should be of a single variable of interest
625941e24428ac0f6e5babb6
def mobilenetv3_large_w5d4(**kwargs): <NEW_LINE> <INDENT> return get_mobilenetv3(version="large", width_scale=1.25, model_name="mobilenetv3_large_w5d4", **kwargs)
MobileNetV3 Large 224/1.25 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.keras/models' Location for keeping the model parameters.
625941e201c39578d7e751fc
def is_empty(self): <NEW_LINE> <INDENT> return False if self.timeSegments else True
Return True if there is no scheduled action.
625941e2e64d504609d74c01
def sample_authset(numleaves, height, function): <NEW_LINE> <INDENT> leaves = pick_leaves(numleaves, height) <NEW_LINE> authset = function(leaves, height) <NEW_LINE> return len(authset)
Sample the size of an authentication set. Keyword arguments: numleaves -- the number of given leaves which will be picked randomly height -- the height of the binary hash tree function -- the function that is used to sample the result. Should be naive_auth_set_indices or efficient_auth_set_indices, or...
625941e238b623060ff0b1ae
def get_card(self, card_id): <NEW_LINE> <INDENT> card_json = self.fetch_json( uri_path=self.base_uri + '/cards/' + card_id ) <NEW_LINE> return self.create_card(card_json)
Get a Card for a given card id. Returns a Card object.
625941e2f8510a7c17cf9ac0
def as_type(self, cls): <NEW_LINE> <INDENT> return cls(downloader=self.downloader, **self.dict)
Return the URL transformed to a different class. Copies the downloader and build the new url using :py:meth:`Url.dict` :param cls: Class of Url to construct :return: A new Url object
625941e2956e5f7376d7122d
def conform(self, name, from_convention): <NEW_LINE> <INDENT> if from_convention is self.convention: <NEW_LINE> <INDENT> return name <NEW_LINE> <DEDENT> mapping = ConventionConverter._convention_mapper( ConventionConverter._as_convention(from_convention), ConventionConverter._as_convention(self.convention), ) <NEW_LINE...
Convert a name to a new convention. Parameters ---------- name : str A name in the given convention. from_convention : {"nlp", "nef", "cfc"} Naming convention of the provided string. Returns ------- str The name converted to the convention. Examples -------- >>> from landlab.graph import ConventionConver...
625941e2fb3f5b602dac3a58
def test_contested_ebzzry(): <NEW_LINE> <INDENT> assert_equal(SOLVER_EBZZRY.contested(), (1, {frozenset([(7, 9), (7, 8), (6, 8), (7, 10), (7, 7)]): set(['e', 'd'])}))
Test contested on ebzzry_grid.
625941e2099cdd3c635f101a
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.orientation is None: <NEW_LINE> <INDENT> self.orientation = geometry_msgs.msg.Quaternion() <NEW_LINE> <DEDENT> if self.angular_velocity is None: <NEW_LINE> <INDENT> self.angular_velocity = geometry_msgs.msg.Vector3() <NEW_LINE> <DEDENT> if...
unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str``
625941e2462c4b4f79d1da90
def __init__(self, *, connector=None, loop=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, request_class=ClientRequest, response_class=ClientResponse, ws_response_class=ClientWebSocketResponse, version=http.HttpVersion11, cookie_jar=None, connector_owner=True, raise_for_s...
The class packaging a class ClientSession to perform HTTP request and manager that these HTTP connection. For details of the params: http://aiohttp.readthedocs.io/en/stable/client_advanced.html#client-session
625941e29f2886367277ac4c
def get_botorch( experiment: Experiment, data: Data, search_space: Optional[SearchSpace] = None, dtype: torch.dtype = torch.double, device: torch.device = DEFAULT_TORCH_DEVICE, transforms: List[Type[Transform]] = Cont_X_trans + Y_trans, transform_configs: Optional[Dict[str, TConfig]] = None, model_constructor: TModelCo...
Instantiates a BotorchModel.
625941e226238365f5f0f234
def getStatus(self): <NEW_LINE> <INDENT> return self._status
Get the sample status. Returns: str: sample status
625941e28a349b6b435e8534
def release_all_drivers(self): <NEW_LINE> <INDENT> self.driver_map = {}
Sometimes we need to release the entire pool..
625941e2c432627299f0500a
def test_cloudbiolinux_import(): <NEW_LINE> <INDENT> from snakemakelib.bio.ngs.db import index <NEW_LINE> assert "foo.fa" == index("foo.fa", "bar", index="foo.fa") <NEW_LINE> import snakemakelib.bio.ngs.db.cloudbiolinux <NEW_LINE> from snakemakelib.bio.ngs.db import index <NEW_LINE> assert "../bar/foo.fa" == snakemakel...
Test that importing cloudbiolinux changes db.index
625941e230c21e258bdfa861
def decode_huffman(bit_seq, dc_ac, layer_type): <NEW_LINE> <INDENT> def diff_value(idx, size): <NEW_LINE> <INDENT> if idx >= len(bit_seq) or idx + size > len(bit_seq): <NEW_LINE> <INDENT> raise IndexError('There is not enough bits to decode DIFF value ' 'codeword.') <NEW_LINE> <DEDENT> fixed = bit_seq[idx:idx + size] <...
Decode a bit sequence encoded by JPEG baseline Huffman table. Arguments: bit_seq {str} -- The encoded bit sequence. dc_ac {DC or AC} -- The type of current. layer_type {LUMINANCE or CHROMINANCE} -- The layer type of bit sequence. Raises: IndexError -- When there is not enough bits in bit sequence to d...
625941e230bbd722463cc189
def check_for_local_eq(quant): <NEW_LINE> <INDENT> criterion = 0 <NEW_LINE> quant.converged = np.zeros(quant.nlayer+1) <NEW_LINE> quant.marked_red = np.zeros(quant.nlayer+1) <NEW_LINE> for i in range(quant.nlayer+1): <NEW_LINE> <INDENT> if quant.conv_layer[i] == 0: <NEW_LINE> <INDENT> if i < quant.nlayer: <NEW_LINE> <I...
checks for local equilibrium
625941e2091ae35668667319
def processTable(self, table): <NEW_LINE> <INDENT> tbody = table.tbody <NEW_LINE> contests= [] <NEW_LINE> for row in tbody.findAll('tr'): <NEW_LINE> <INDENT> name= row.contents[3].a.string <NEW_LINE> start_time= row.contents[5]['data-starttime'] <NEW_LINE> end_time= row.contents[7]['data-endtime'] <NEW_LINE> unix_start...
:param table: a BeautifulSoup object representing a table :return: list of contests extracted from the table
625941e29b70327d1c4e1198
def emit_body(writer): <NEW_LINE> <INDENT> writer.write("def main():\n") <NEW_LINE> writer.write("\tinput_file = []\n") <NEW_LINE> writer.write("\t#reading the validation file\n") <NEW_LINE> writer.write("\twith open('HW_05B_DecTree_validation_data___v200.csv') as csvfile:\n") <NEW_LINE> writer.write("\t\tattributes = ...
This function writes the body of output file :param writer: Object to write in file :return: None
625941e2bd1bec0571d909f0
def test_bad_object_class(self): <NEW_LINE> <INDENT> entry = self.good_entry <NEW_LINE> entry['objectClass'] = ['BadObject'] <NEW_LINE> suite = unittest.TestSuite() <NEW_LINE> test_names = unittest.TestLoader().getTestCaseNames(EntryTest) <NEW_LINE> for test_name in test_names: <NEW_LINE> <INDENT> suite.addTest(EntryTe...
Test a bad object class
625941e27d847024c06be681
def _make_dir(self, client_kwargs): <NEW_LINE> <INDENT> with _handle_client_exception(): <NEW_LINE> <INDENT> if 'obj' in client_kwargs: <NEW_LINE> <INDENT> return self.client.put_object( client_kwargs['container'], client_kwargs['obj'], b'') <NEW_LINE> <DEDENT> return self.client.put_container(client_kwargs['container'...
Make a directory. args: client_kwargs (dict): Client arguments.
625941e2379a373c97cfaf08
def crawl(self): <NEW_LINE> <INDENT> pass
Spider Event
625941e297e22403b379d35d
@coroutine <NEW_LINE> def start_server(client_connected_cb, host=None, port=None, loop=None, limit=_DEFAULT_LIMIT, **kwds): <NEW_LINE> <INDENT> if loop is None: <NEW_LINE> <INDENT> loop = events.get_event_loop() <NEW_LINE> <DEDENT> def factory(): <NEW_LINE> <INDENT> reader = StreamReader(limit=limit, loop=loop) <NEW_LI...
Start a socket server, call back for each client connected. The first parameter, `client_connected_cb`, takes two parameters: client_reader, client_writer. client_reader is a StreamReader object, while client_writer is a StreamWriter object. This parameter can either be a plain callback function or a coroutine; if i...
625941e223849d37ff7b344e
def copy_template_dir(source, destination, vars): <NEW_LINE> <INDENT> source = os.path.abspath(source) <NEW_LINE> destination = os.path.abspath(destination) <NEW_LINE> try: <NEW_LINE> <INDENT> distutils.dir_util.copy_tree(source, destination) <NEW_LINE> for f in find_files(destination, "tpl")[0]: <NEW_LINE> <INDENT> ne...
Copies over a template directory.
625941e20383005118ecf9a3
def removeTags(html, tags): <NEW_LINE> <INDENT> tags = [re.escape(tag) for tag in tags.split()] <NEW_LINE> tagsRe = '(%s)' % '|'.join(tags) <NEW_LINE> starttagRe = re.compile(r'<%s(/?>|(\s+[^>]*>))' % tagsRe, re.U) <NEW_LINE> endtagRe = re.compile('</%s>' % tagsRe) <NEW_LINE> html = starttagRe.sub('', html) <NEW_LINE> ...
Returns the given HTML with given tags removed.
625941e28e05c05ec3eea739
def _control(self, dt): <NEW_LINE> <INDENT> return self._pedal(self.est_distance, dt), self._steer(self.est_angle, dt)
Issue PID control signals for distance and angle.
625941e2e76e3b2f99f3abc8
def repackage_tar_with_one_level(in_tarpath, out_tarpath, addprefix): <NEW_LINE> <INDENT> with tempfile.TemporaryDirectory() as target: <NEW_LINE> <INDENT> extract_all(in_tarpath, target) <NEW_LINE> try: <NEW_LINE> <INDENT> prefix = find_prefix(target, level=1) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT>...
takes in_tarpath, but rewrites it so that there is alwyas 1 top level directory before all the crap. If the input tar file directory hierarchy is deep enough, we strip excess directories until there is one parent. if the input tar file directory hierarchy is not deep enough, we add <addprefix>
625941e2167d2b6e31218f57
def get_max_f1_thresh(y_true, y_score): <NEW_LINE> <INDENT> precision, recall, thresh = precision_recall_curve(y_true, y_score) <NEW_LINE> f1 = 2 * precision * recall / (precision + recall) <NEW_LINE> max_f1_ind = np.argmax(f1) <NEW_LINE> max_f1 = f1[max_f1_ind] <NEW_LINE> max_f1_thresh = thresh[max_f1_ind] <NEW_LINE> ...
Get maximum F1-score and corresponding threshold.
625941e2b7558d58953c52ce
def truncate_array(a, index): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not isinstance(a, Array): <NEW_LINE> <INDENT> a = Array(a, accessmode='r+') <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise TypeError(f"'{a}' not recognized as a darr Array") <NEW_LINE> <DEDENT> a.check_arraywriteable...
Truncate darr data. Parameters ---------- a: array or str or pathlib.Path The darr object to be truncated or file system path to it. index: int The index along the first axis at which the darr should be truncated. Negative indices can be used but the resulting length of the truncated darr should be larg...
625941e23cc13d1c6d3c773a
def give_effect_self(self, effect, message_class=None, **message_args): <NEW_LINE> <INDENT> return self.apply_effect(effect, inducer=self, message_class=message_class, **message_args)
Apply an effect to this subject, making it the inducer also
625941e2a05bb46b383ecbe0
def get_topocentric_azimuth_angle(topocentric_local_hour_angle, latitude, topocentric_sun_declination): <NEW_LINE> <INDENT> tlha_rad = math.radians(topocentric_local_hour_angle) <NEW_LINE> latitude_rad = math.radians(latitude) <NEW_LINE> tsd_rad = math.radians(topocentric_sun_declination) <NEW_LINE> a = math.sin(tlha_r...
Measured eastward from north
625941e2566aa707497f4925
def _create_luncopy(self, luncopyname, srclunid, tgtlunid): <NEW_LINE> <INDENT> url = self.url + "/luncopy" <NEW_LINE> data = json.dumps({"TYPE": "219", "NAME": luncopyname, "DESCRIPTION": luncopyname, "COPYSPEED": "2", "LUNCOPYTYPE": "1", "SOURCELUN": ("INVALID;%s;INVALID;INVALID;INVALID" % srclunid), "TARGETLUN": ("I...
Create a luncopy.
625941e2baa26c4b54cb14de
def mean_and_stdev(df, Duplicates, win, kind='lines', per_sample='False'): <NEW_LINE> <INDENT> df[Duplicates] = pd.to_numeric(df[Duplicates], errors='coerce').round(2) <NEW_LINE> if per_sample == 'False': <NEW_LINE> <INDENT> df_names = format_sample_names(df, Duplicates) <NEW_LINE> df_dup_all = df.groupby(['Run', 'Date...
(df) -> df get rolling mean (1 year window), positive and negative std
625941e2e5267d203edce05a
def main(): <NEW_LINE> <INDENT> desc = _(DESCRIPTION) <NEW_LINE> parser = p4gf_util.create_arg_parser(desc=desc) <NEW_LINE> parser.add_argument(NTR('--config'), metavar=NTR('config'), help=_('Path to Git Fusion p4gf_config file (required)'), required=True) <NEW_LINE> parser.add_argument('-u', '--p4user', metavar='p4us...
Parse the command-line arguments and report on locks.
625941e2a4f1c619b28b03f2
def start_large_file( self, bucket_id, file_name, content_type=None, file_info=None, encryption: Optional[EncryptionSetting] = None, file_retention: Optional[FileRetentionSetting] = None, legal_hold: Optional[LegalHold] = None, ): <NEW_LINE> <INDENT> return UnfinishedLargeFile( self.services.session.start_large_file( b...
Start a large file transfer. :param str file_name: a file name :param str,None content_type: the MIME type, or ``None`` to accept the default based on file extension of the B2 file name :param dict,None file_info: a file info to store with the file or ``None`` to not store anything :param b2sdk.v2.EncryptionSetting en...
625941e2d99f1b3c44c6794b
def test_product_setter_getter_methods(self): <NEW_LINE> <INDENT> product = Product() <NEW_LINE> product.set_id(0) <NEW_LINE> product.set_name("Samsung HDTV") <NEW_LINE> product.set_price(449) <NEW_LINE> product.set_image_id("001") <NEW_LINE> product.set_description("Latest TV") <NEW_LINE> review = Review(username="cou...
Set and get all product attributes
625941e2460517430c39453e
def get_all_containers(self, is_all=True): <NEW_LINE> <INDENT> container_name_list = [] <NEW_LINE> container_info_list = self.docker_opers.containers(all=is_all) <NEW_LINE> for container_info in container_info_list: <NEW_LINE> <INDENT> name = container_info.get('Names')[0] <NEW_LINE> name = name.replace('/', '') <NEW_L...
get all containers on some server all -> True all containers on such server all -> False started containers on such server
625941e2a934411ee3751a56
def has_next(self): <NEW_LINE> <INDENT> return self.current and self.current.next
Checks if the iterator has a next value
625941e2507cdc57c63070a5
def forward(self, x1_att, x2_att, x2, x2_mask): <NEW_LINE> <INDENT> if x1_att.size(0) == 1 and x2_att.size(0) > 1: <NEW_LINE> <INDENT> x1_att = x1_att.repeat(x2_att.size(0), 1, 1) <NEW_LINE> <DEDENT> elif x2_att.size(0) == 1 and x1_att.size(0) > 1: <NEW_LINE> <INDENT> x2_att = x2_att.repeat(x1_att.size(0), 1, 1) <NEW_L...
x1_att: batch * len1 * full_size x2_att: batch * len2 * full_size x2: batch * len2 * hidden_size x2_mask: batch * len2
625941e282261d6c526ab867
def __init__( self, name, supported_extensions, command, exit_codes=None, output_stderr=False ): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.supported_extensions = supported_extensions <NEW_LINE> self.command = command <NEW_LINE> self.exit_codes = exit_codes <NEW_LINE> self.output_stderr = output_stderr
Args: name: (str) name of the driver supported_extensions: (list[str]) list of file extensions this driver supports Example: py, js command: (list[str]) list of tokens that are the command to be executed to create a report exit_codes: (list[int]) list of exit codes that do not indicate a...
625941e23eb6a72ae02ec8a9
def input_eamount(self, eamount): <NEW_LINE> <INDENT> self.send_keys(self.eamount_loc, eamount)
输入EA批复额度
625941e285dfad0860c3b21d
def get_scoped_session(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._scoped_sessions() <NEW_LINE> <DEDENT> except (TypeError, AttributeError): <NEW_LINE> <INDENT> return None
Return a scoped session object locally for a thread, can be used liberally within the same thread without deadlocks
625941e23539df3088e2e70d
def __init__(self, P=None, *args, **kwargs): <NEW_LINE> <INDENT> k_spatial = 1.0 * kernels.ExpSquaredKernel( metric=[1.0, 1.0], ndim=3, axes=[0, 1]) <NEW_LINE> k_temporal = 1.0 * kernels.ExpSquaredKernel( metric=1.0, ndim=3, axes=2) * kernels.ExpSine2Kernel( gamma=2, log_period=1, ndim=3, axes=2...
Initialises the priors, initial hp values, and kernel.
625941e276d4e153a657eef4
def get_target_speed(self): <NEW_LINE> <INDENT> return 79
Retrieves the target (expected) speed of the fan Returns: An integer, the percentage of full fan speed, in the range 0 (off) to 100 (full speed)
625941e2e64d504609d74c02
def is_next_intent_error(handler_input, current_intent): <NEW_LINE> <INDENT> next_intent = handler_input.attributes_manager.session_attributes['next_intent'] <NEW_LINE> return not (True in [x in next_intent for x in current_intent])
Checks if the current intent should play
625941e255399d3f05588a78
def canAttendMeetings(self, intervals): <NEW_LINE> <INDENT> start = None <NEW_LINE> for end in sorted(intervals, key=lambda i: i.start): <NEW_LINE> <INDENT> if start: <NEW_LINE> <INDENT> if not start.end <= end.start: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> start = end <NEW_LINE> <DEDENT> return T...
:type intervals: List[Interval] :rtype: bool
625941e2b830903b967e9cc9
def imageSmoother(self, M): <NEW_LINE> <INDENT> m, n = len(M), len(M[0]) <NEW_LINE> res = [[0] * n for _ in range(m)] <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> for j in range(n): <NEW_LINE> <INDENT> neigh = [] <NEW_LINE> for v in [(0, 0), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]: <N...
:type M: List[List[int]] :rtype: List[List[int]]
625941e223849d37ff7b344f
@pytest.fixture <NEW_LINE> def editor_open_files(request, setup_editor, python_files): <NEW_LINE> <INDENT> def _get_editor_open_files(last_focused_filename, expected_current_filename): <NEW_LINE> <INDENT> editor = setup_editor <NEW_LINE> expected_filenames, tmpdir = python_files <NEW_LINE> if expected_current_filename ...
Setup an Editor with a set of open files, given a past file in focus. If no/None ``last_focused_filename`` is passed, the ``"layout_settings"`` key is not included in the options dict. If no/None ``expected_current_filename``, is assumed to be the first file.
625941e27047854f462a17c8
def __init__(self, key_schema, value_schema): <NEW_LINE> <INDENT> if not isinstance(key_schema, Schema): <NEW_LINE> <INDENT> raise tuf.FormatError('Expected Schema but got '+repr(key_schema)) <NEW_LINE> <DEDENT> if not isinstance(value_schema, Schema): <NEW_LINE> <INDENT> raise tuf.FormatError('Expected Schema but got ...
<Purpose> Create a new DictOf schema. <Arguments> key_schema: The dictionary's key. value_schema: The dictionary's value.
625941e28a43f66fc4b54423
def test_write_hdf5(self): <NEW_LINE> <INDENT> filepath = os.path.join(self.test_data_path, "test_point_write_hdf5.hdf5") <NEW_LINE> with h5py.File(filepath, "w") as hdf5_file: <NEW_LINE> <INDENT> self.point.write_hdf5(hdf5_file) <NEW_LINE> self.assertTrue(self.name_ref in hdf5_file) <NEW_LINE> root_group = hdf5_file[s...
Test write_hdf5 method.
625941e245492302aab5e689
def difference(a, b): <NEW_LINE> <INDENT> if not a: return b <NEW_LINE> if not b: return a <NEW_LINE> d = [] <NEW_LINE> for i in a: <NEW_LINE> <INDENT> if (i not in b) and (i not in d): <NEW_LINE> <INDENT> d.append(i) <NEW_LINE> <DEDENT> <DEDENT> for i in b: <NEW_LINE> <INDENT> if (i not in a) and (i not in d): <NEW_LI...
difference(list, list):
625941e2f8510a7c17cf9ac1
def OnOpen(self,e): <NEW_LINE> <INDENT> dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "MP3 files (*.mp3)|*.mp3|M4A files (*.m4a)|*.m4a|All files (*.*)|*.*", wx.OPEN) <NEW_LINE> if dlg.ShowModal() == wx.ID_OK: <NEW_LINE> <INDENT> self.filename = dlg.GetFilename() <NEW_LINE> self.dirname = dlg.GetDirectory...
Open a file
625941e25fc7496912cc3d40
def backtracking_search(csp): <NEW_LINE> <INDENT> result = {} <NEW_LINE> found = backtrack(csp, result) <NEW_LINE> return found, result
returns a solution, or failure :param csp: the problem
625941e2d10714528d6000a9
def possibleStates(self, word, num=5): <NEW_LINE> <INDENT> p = sorted([(i.dst, i.prob) for i in self._graphFrame.edges[self._graphFrame.edges['src'] == word].collect()], key=lambda x:x[1], reverse=True) <NEW_LINE> return p[0:min(num, len(p))]
returning the most probable future words for a given word
625941e28e05c05ec3eea73a
def get(self, node_key): <NEW_LINE> <INDENT> return self._nodes.get(node_key)
Returns the current node's child having node_key, or None.
625941e29c8ee82313fbbb38
@pg_extras.command() <NEW_LINE> @with_appcontext <NEW_LINE> def queries_popular(): <NEW_LINE> <INDENT> query_queries_popular(current_app.extensions['sqlalchemy'].db)
10 most called queries.
625941e256b00c62f0f14a1e