code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _dumps(self, payload): <NEW_LINE> <INDENT> return self._serialize.dumps(payload)
Serialize value using serializer :param payload: mixed, value :return: bytes, the result
625941f266673b3332b92669
def __new__(self, P: NumpyArray, metric: String = "default", exp: PositiveInteger = 2, matrix: Bool = False) -> NumpyArray: <NEW_LINE> <INDENT> if metric == 'minkowski': <NEW_LINE> <INDENT> dist_object = Minkowski <NEW_LINE> distance = dist_object().compute(P, exp) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dist_obj...
Compute the pairwise distance for each two elements of P.
625941f2a219f33f34628f39
def build_accession_table(self, acc): <NEW_LINE> <INDENT> parts = ['<table>'] <NEW_LINE> row = '<tr><td>%s</td><td>%s</td></tr>' <NEW_LINE> name_href = '<a href="/acc?name=%(name)s">%(name)s</a>' <NEW_LINE> google_href = '<span style="margin-left: 40px"><a href="http://google.com/search?q=%(name)s">google</a></span>' <...
Return an html table from the acc argument.
625941f2eab8aa0e5d26e132
def SetDataCol(self, label, data_col_t): <NEW_LINE> <INDENT> if not self.__openO: <NEW_LINE> <INDENT> print('ERROR: Must use OpenO before set functions') <NEW_LINE> sys.exit(-1) <NEW_LINE> <DEDENT> if label not in self.__DataCols: <NEW_LINE> <INDENT> self.__DataCols.append(label) <NEW_LINE> <DEDENT> idx_col = (self.__D...
Sets particle positions of current frame Parameters ---------- label : str name of the data column data_col_t : numpy array (number of particles,) particle positions (coordinates) of current frame in order of id_t
625941f2fbf16365ca6f67a9
def colorize_bw(img, new_color, new_alpha=1, background=0, background_alpha=0): <NEW_LINE> <INDENT> dat = convert_to_rgba(img) <NEW_LINE> r, g, b, a = np.array(dat).T <NEW_LINE> one_inds = r > 0 <NEW_LINE> zero_inds = r == 0 <NEW_LINE> a[zero_inds] = background_alpha <NEW_LINE> a[one_inds] = int(new_alpha * 255) <NEW_L...
Colorize a binary image with a new color, alpha, and background value. Parameters ---------- img : PIL.Image.Image Image to convert. new_color : array-like Three element rgb color new_alpha : float, optional New alpha value, by default 1 background : float, optional background alpha, by default 0 Retu...
625941f24d74a7450ccd479d
def search(self, user_info=None, collection=None, **kwargs): <NEW_LINE> <INDENT> user_info = user_info or current_user <NEW_LINE> query = self.query <NEW_LINE> for enhancer in query_enhancers(): <NEW_LINE> <INDENT> query = enhancer(query, user_info=user_info, collection=collection) <NEW_LINE> <DEDENT> for walker in sea...
Search records.
625941f27d847024c06be899
def framerate(data:np.ndarray) -> int: <NEW_LINE> <INDENT> return int(round(1/(data[1,0]-data[0,0])))
Gets the frame rate (samples per second) of the data Parameters ---------- data : ndarray The waveform data as a 2D array Returns ------- int The number of samples per second in the data
625941f231939e2706e4d439
def test_ShouldApplyStateUpdate_5(self): <NEW_LINE> <INDENT> self.template_ShouldApplyStateUpdate(32, -1, 31, 30, int('0'*64,2), 64, 32, -1, 1)
Unacked and untriggered.
625941f25fdd1c0f98dc080e
def add_node(self, node): <NEW_LINE> <INDENT> knode = self.unodes.get(node, None) <NEW_LINE> if knode is None: <NEW_LINE> <INDENT> knode = self.nkG.addNode() <NEW_LINE> self.unodes[node] = knode <NEW_LINE> self.knodes[knode] = node <NEW_LINE> <DEDENT> return knode
Adds the node and returns the NetworKit ID for the newly added node. If the node already existed, returns the existing NetworKit ID.
625941f2dd821e528d63b77c
def test_set_aux_heat_off(self): <NEW_LINE> <INDENT> common.set_aux_heat(self.hass, False, ENTITY_CLIMATE) <NEW_LINE> self.hass.block_till_done() <NEW_LINE> state = self.hass.states.get(ENTITY_CLIMATE) <NEW_LINE> assert 'off' == state.attributes.get('aux_heat')
Test setting the auxiliary heater off/false.
625941f22eb69b55b151ce90
def calc_width(r_200: float, dist: float, factor: int = 1) -> float: <NEW_LINE> <INDENT> return factor * r_200 / dist * 360. / 2. / np.pi
Calculate the width of the map based on distance and R_200 : r_200 : R_200 in unit of pc : dist : distance of the dwaf from us in unit of pc : factor : decide how many times the width as to R_200 : returns : width of the map in unit of degree
625941f299cbb53fe67931bc
def _minmax_impl(a_gpu, axis, min_or_max, stream=None): <NEW_LINE> <INDENT> assert len(a_gpu.shape) < 3 <NEW_LINE> if iscomplextype(a_gpu.dtype): <NEW_LINE> <INDENT> raise ValueError("Cannot compute min/max of complex values") <NEW_LINE> <DEDENT> if axis is None: <NEW_LINE> <INDENT> if min_or_max == 'max': <NEW_LINE> <...
Returns both max and argmax (min/argmin) along an axis.
625941f27c178a314d6efa42
def clear(self, name): <NEW_LINE> <INDENT> _CLEARER_DICT[name](self.__data)
トランスフォーメーション修飾属性をクリアする。 :param `str` name: トランスフォーメーション修飾属性名。
625941f2925a0f43d254a455
def getNodesByName(parent, name): <NEW_LINE> <INDENT> childNodes = parent.xpath("*[local-name() = '%s']" % name) <NEW_LINE> return childNodes
Return a list of all of the child nodes matching a given local name
625941f2627d3e7fe0d6942a
def assertKnownGoodJSON(self, url, expected): <NEW_LINE> <INDENT> self.app.put('/storeResultEntry/', data=self.testjson) <NEW_LINE> result = self.app.get(url) <NEW_LINE> actual = json.loads(result.data)['results'] <NEW_LINE> self.assertEqual(expected, actual)
Gets JSON from a URL and asserts that the known data is equal.
625941f232920d7e50b287ad
@pytest.mark.django_db <NEW_LINE> def test_autocomplete_no_url(rf: RequestFactory) -> None: <NEW_LINE> <INDENT> question_field = QuizQuestionFactory( field_type=URLAutocompleteSelectField.name, field_type_options={ "url": "", "mapping": { "root": "data", "value": "_id", "text": "name", "extra": {"Airline": "airline.nam...
Ensure that an autocomplete field can be configured with no URL. Simulates a scenario where autocomplete is powered by something other than an HTTP endpoint.
625941f29f2886367277ae60
def test_init_consistency(self): <NEW_LINE> <INDENT> args = dict( datatag='tag', a=('a', 'ao'), dEa=('dEa', 'dEao'), b=('b', 'bo'), dEb=('dEb', 'dEbo'), Vnn='Vnn', Vno='Vno', Von='Von', Voo='Voo', reverse=False, symmetric_V=False, tmin=2, T=5 ) <NEW_LINE> m = Corr3(**args) <NEW_LINE> with self.assertRaises(ValueError):...
Corr3 consistency checks
625941f23317a56b8693a221
def rcvtimeo(self): <NEW_LINE> <INDENT> return utils.lib.zsock_rcvtimeo(self._p)
Get socket option `rcvtimeo`. Available from libzmq 2.2.0.
625941f2a8ecb033257d36a3
def run(m, nullable=False, throwable=False): <NEW_LINE> <INDENT> nonlocal s <NEW_LINE> r = m(s) <NEW_LINE> if r is not None: <NEW_LINE> <INDENT> (a, s) = r <NEW_LINE> return a <NEW_LINE> <DEDENT> if nullable: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if throwable: <NEW_LINE> <INDENT> raise ParserFailure <NEW_...
Run a parser `m`, while chaining its state underground. Possibly returns `None` if `nullable=True` is specified; otherwise, skip the remaining task. Specifying `throwable=True` will raise `Nothing` exception, instead.
625941f2a17c0f6771cbe627
def add_image(self, image_path, annotations): <NEW_LINE> <INDENT> self.image_paths.append(image_path) <NEW_LINE> self.bounding_boxes.append([bounding_box_from_annotation(**a) for a in annotations])
Adds an image and its bounding boxes to the current list of files The bounding boxes are automatically estimated based on the given annotations. **Parameters:** ``image_path`` : str The file name of the image, including its full path ``annotations`` : [dict] A list of annotations, i.e., where each annotation ca...
625941f2a79ad161976cc71e
@pytest.mark.parametrize( "ucn,expected", [ ( "U+4E9D", [ { "type": "C", "cid": 17245, "radical": 7, "strokes": 2, "strokes-residue": 6, }, { "type": "C", "cid": 17245, "radical": 28, "strokes": 2, "strokes-residue": 6, }, ], ), ( "U+4E9E", [ { "type": "C", "cid": 4108, "radical": 7, "strokes": 2, "strokes-residue": 6,...
The value consists of a number of space-separated entries. Each entry consists of three pieces of information separated by a plus sign: 1) C or V. “C” indicates that the Unicode code point maps directly to the Adobe-Japan1-6 CID that appears after it, and “V” indicates that it is considered a variant form, and thus no...
625941f276d4e153a657f10b
def _to_network(self, network): <NEW_LINE> <INDENT> extra = {} <NEW_LINE> extra['selfLink'] = network.get('selfLink') <NEW_LINE> extra['gatewayIPv4'] = network.get('gatewayIPv4') <NEW_LINE> extra['description'] = network.get('description') <NEW_LINE> extra['creationTimestamp'] = network.get('creationTimestamp') <NEW_LI...
Return a Network object from the JSON-response dictionary. :param network: The dictionary describing the network. :type network: ``dict`` :return: Network object :rtype: :class:`GCENetwork`
625941f2fff4ab517eb2fa19
def __init__(self, graph_name: str) -> None: <NEW_LINE> <INDENT> url = get_neo4j_url(graph_name) <NEW_LINE> self.driver = GraphDatabase.driver(url, auth=(NEO4J_USER, NEO4J_PASSWORD))
Set up Neo4JClient using the default test credentials.
625941f2851cf427c661aae2
@named("stop") <NEW_LINE> def cmd_stop(): <NEW_LINE> <INDENT> assert_conf() <NEW_LINE> cmd_stop_env()
stop docker environment, then all networks and all vms
625941f22eb69b55b151ce91
def log(self, message, *args): <NEW_LINE> <INDENT> print("[%s] %s" % (self.NAME, (message % args)), file=sys.stderr)
Mostrar mensaje de registro por stderr
625941f2e76e3b2f99f3adda
def carrinhoOrGet_for_qs(request): <NEW_LINE> <INDENT> if 'carrinho_parlamentar' in request.session: <NEW_LINE> <INDENT> ids = request.session['carrinho_parlamentar'] <NEW_LINE> qs = Parlamentar.objects.filter(pk__in=ids) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> qs = Parlamentar.objects.all() <NEW_LINE> if request...
Verifica se existe parlamentares na sessão se não verifica get e retorna qs correspondente.
625941f2be383301e01b5a52
def resolve_path(*path: str): <NEW_LINE> <INDENT> return os.path.abspath(os.path.join(_orig_dir, '..', *path))
Resolve any path based on the project root. resolve_path('foo', 'bar') will give an absolute path to your_project_directory/foo/bar If the path is already absolute, it will stay absolute
625941f263f4b57ef00016e0
def get_roles_for_user(dbo, user): <NEW_LINE> <INDENT> rows = dbo.query("SELECT r.Rolename FROM role r " "INNER JOIN userrole ur ON ur.RoleID = r.ID " "INNER JOIN users u ON u.ID = ur.UserID " "WHERE u.UserName LIKE ? " "ORDER BY r.Rolename", [user]) <NEW_LINE> roles = [] <NEW_LINE> for r in...
Returns a list of roles a user is in
625941f2460517430c39474d
def addColumnToTable(self, table, column_name, data_type): <NEW_LINE> <INDENT> sql = "ALTER TABLE %s ADD COLUMN %s %s;" % (table, column_name, data_type) <NEW_LINE> print(sql) <NEW_LINE> self.cursor.execute(sql) <NEW_LINE> self.conn.commit()
Data type must be passed as string. Supported data types can be found from: http://www.postgresql.org/docs/current/static/datatype.html
625941f24a966d76dd5515ee
def _handler_command_acquire_status(self, *args, **kwargs): <NEW_LINE> <INDENT> log.debug("IN _handler_command_acquire_status") <NEW_LINE> next_state = None <NEW_LINE> kwargs['timeout'] = 30 <NEW_LINE> kwargs['expected_prompt'] = TeledynePrompt.COMMAND <NEW_LINE> try: <NEW_LINE> <INDENT> self._do_cmd_no_resp(TeledyneIn...
Get the raw format outputs of the following commands, AC, PT2, PT4
625941f2656771135c3ebe4f
def trimmed_local_mean(data, window_len: int, threshold: float) -> Iterator[int]: <NEW_LINE> <INDENT> m = np.ones(window_len) <NEW_LINE> t_c = window_len // 2 <NEW_LINE> m[t_c] = 0 <NEW_LINE> for idx, data_part in enumerate(windowing(data, window_len)): <NEW_LINE> <INDENT> mis, ents = zip(*data_part) <NEW_LINE> if sum(...
Yields index where there is a sudden dip in mutual information.
625941f2cb5e8a47e48b8078
def map_language(self): <NEW_LINE> <INDENT> arg0 = self.arg0 <NEW_LINE> if arg0 and self.languages and arg0 in self.languages: <NEW_LINE> <INDENT> self.language = arg0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.language = self.default_language <NEW_LINE> <DEDENT> if self.language: <NEW_LINE> <INDENT> log_rewrit...
Handles language (no hyphen mapping)
625941f230c21e258bdfaa7d
def rowOfButtonsProxy(model_cls): <NEW_LINE> <INDENT> class ProxyModel(model_cls): <NEW_LINE> <INDENT> def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> super(ProxyModel, self).__init__(*args, **kwds) <NEW_LINE> <DEDENT> def rowCount(self, parent=QModelIndex()): <NEW_LINE> <INDENT> return super(ProxyModel, self).r...
Given a TableModel class, return a new class that pretends to have an extra row at the end. This row is used to display "Add..." buttons in the GUI.
625941f223e79379d52eeb35
def __init__(self, name, starting_health=100): <NEW_LINE> <INDENT> self.abilities = list() <NEW_LINE> self.armors = list() <NEW_LINE> self.name = name <NEW_LINE> self.starting_health = starting_health <NEW_LINE> self.current_health = starting_health <NEW_LINE> self.deaths = 0 <NEW_LINE> self.kills = 0
Instance properties: abilities: List armors: List name: String starting_health: Integer current_health: Integer
625941f2377c676e9127277f
def write_payload(self, payload): <NEW_LINE> <INDENT> self.set_mode(MODE.STDBY) <NEW_LINE> base_addr = self.get_fifo_tx_base_addr() <NEW_LINE> self.set_fifo_addr_ptr(base_addr) <NEW_LINE> return self.spi.transfer([REG.LORA.FIFO | 0x80] + payload)[1:]
Get FIFO ready for TX: Set FifoAddrPtr to FifoTxBaseAddr. The transceiver is put into STDBY mode. :param payload: Payload to write (list) :return: Written payload
625941f21f037a2d8b9467d5
def projectToMap(self, p): <NEW_LINE> <INDENT> xScene = p[0] <NEW_LINE> yScene = p[1] <NEW_LINE> xMap = self.siteMap.xFederal - self.scaleToMap(xScene) <NEW_LINE> yMap = self.siteMap.yFederal - self.scaleToMap(yScene) <NEW_LINE> return (xMap, yMap)
The given 2D scene point p, comprised of scene cooordinates (xScene, zScene), is projected to the corresponding 2D siteMap location (xMap, yMap) and returned. xScene is positive to the left, and zScene is positive upwards; xMap is positive to the right and yMap is positive downwards.
625941f27cff6e4e81117f5e
def set_generator(self, generator=None, version=None, uri=None, exclude_podgen=False): <NEW_LINE> <INDENT> self.generator = self._program_name_to_str(generator, version, uri) + (" (using %s)" % self._feedgen_generator_str if not exclude_podgen else "")
Set the generator of the feed, formatted nicely, which identifies the software used to generate the feed. :param generator: Software used to create the feed. :type generator: str :param version: (Optional) Version of the software, as a tuple. :type version: :obj:`tuple` of :obj:`int` :param uri: (Optional) The softwar...
625941f2d6c5a10208144628
def teardown_connectivity_audit(self, context, audit_uuid, hostname): <NEW_LINE> <INDENT> if hostname: <NEW_LINE> <INDENT> topic_pnet_connectivity_call = topics.get_topic_name( self.topic, topics.PNET_CONNECTIVITY, topics.UPDATE, hostname ) <NEW_LINE> cctxt = self.client.prepare(topic=topic_pnet_connectivity_call, fano...
Call teardown_connectivity_audit for given host, or cast for all if none is specified.
625941f2b830903b967e9edd
def test_get_root_nodegroup(self): <NEW_LINE> <INDENT> graph = Graph.new(name='TEST',is_resource=False,author='TEST') <NEW_LINE> graph.append_branch('http://www.cidoc-crm.org/cidoc-crm/P1_is_identified_by', graphid=self.NODE_NODETYPE_GRAPHID) <NEW_LINE> for node in graph.nodes.itervalues(): <NEW_LINE> <INDENT> if node....
test we can get the right parent NodeGroup
625941f2c432627299f05223
def build_search_url(self, basic_search_units, req_args=None, lang=CFG_SITE_LANG, limit=CFG_EXTERNAL_COLLECTION_MAXRESULTS): <NEW_LINE> <INDENT> if req_args: <NEW_LINE> <INDENT> search_url_params = "" <NEW_LINE> if type(req_args) is list: <NEW_LINE> <INDENT> conjunction = " or " <NEW_LINE> search_url_recids = conjuncti...
Build a URL for an Invenio based site
625941f2097d151d1a22342f
def set_qmp_monitor(self, enabled=True): <NEW_LINE> <INDENT> if enabled: <NEW_LINE> <INDENT> self._qmp_set = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._qmp_set = False <NEW_LINE> self._qmp = None
Set the QMP monitor. @param enabled: if False, qmp monitor options will be removed from the base arguments of the resulting QEMU command line. Default is True. @note: call this function before launch().
625941f2293b9510aa2c3869
def count_brigade_winner(self): <NEW_LINE> <INDENT> users_rating = self._show_rating() <NEW_LINE> self._count_average_rating(users_rating[-1]) <NEW_LINE> self._add_main_brigades_results(*users_rating[:-1]) <NEW_LINE> self._add_average_kti(*users_rating[:-1]) <NEW_LINE> print('\n', self.totl_res) <NEW_LINE> self._count_...
Show rating.
625941f2a934411ee3751c6e
def get_decent_joke(self): <NEW_LINE> <INDENT> jokes = self._get_cached_jokes() <NEW_LINE> if not jokes: <NEW_LINE> <INDENT> jokes = self._get_jokes_and_fill_cache() <NEW_LINE> <DEDENT> return jokes[randint(0, len(jokes) - 1)]
Get cached joke, or refill cache and use one from that process.
625941f221a7993f00bc82d4
def test_multi_items_in_list(self): <NEW_LINE> <INDENT> raw_keypress_list = [ {'key': 'a', 'timestamp': 12345, 'theme': 1}, {'key': 'b', 'timestamp': 12445, 'theme': 1}, {'key': 'c', 'timestamp': 12545, 'theme': 1}, {'key': 'd', 'timestamp': 12645, 'theme': 1}, {'key': 'e', 'timestamp': 12745, 'theme': 1} ] <NEW_LINE> ...
Test what happens when processing a list with many keypresses.
625941f2d7e4931a7ee9e4f9
def __reverse__(self, sentence): <NEW_LINE> <INDENT> rev = 0 <NEW_LINE> for w, tag in sentence: <NEW_LINE> <INDENT> if (w in self.neg_words and tag in ['VXV']): <NEW_LINE> <INDENT> rev = not rev <NEW_LINE> <DEDENT> <DEDENT> return rev
some phrases totally change the meaning ex) 싫지 않아
625941f22ae34c7f2600d709
def _finalize(self, data, append, **args): <NEW_LINE> <INDENT> if append: <NEW_LINE> <INDENT> self.append(data, **args, inplace=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if data is None or data.empty: <NEW_LINE> <INDENT> return _empty_iamframe(self.dimensions + ["value"]) <NEW_LINE> <DEDENT> return IamDataFra...
Append `data` to `self` or return as new IamDataFrame with copy of `meta`
625941f2a05bb46b383ecdf5
def estimate_fuv_to_sfr(estimator, factor, required_unit, fuv_luminosity, unit=None, distance=None): <NEW_LINE> <INDENT> fuv_wavelength = parse_filter("GALEX FUV").wavelength <NEW_LINE> new_unit = u("Msun/yr") <NEW_LINE> required_unit = u(required_unit, density=True) <NEW_LINE> name = "SFR" <NEW_LINE> description = "st...
This function ... :param estimator: :param factor: :param required_unit: :param fuv_luminosity: :param unit: :param distance: :return:
625941f294891a1f4081c085
def construct_mapping(loader, node, deep=False): <NEW_LINE> <INDENT> loader.flatten_mapping(node) <NEW_LINE> if not isinstance(node, yaml.MappingNode): <NEW_LINE> <INDENT> raise yaml.constructor.ConstructorError( None, None, f'expected a mapping node, but found {node.id}', node.start_mark ) <NEW_LINE> <DEDENT> mapping ...
Construct python object from yaml mapping node, based on :meth:`yaml.BaseConstructor.construct_mapping` in PyYAML (MIT).
625941f230dc7b7665901f39
def _insert(self): <NEW_LINE> <INDENT> with sqlite3.connect(self.database) as conn: <NEW_LINE> <INDENT> cur = conn.cursor() <NEW_LINE> SQLPATTERN = "INSERT INTO {tablename}({fieldnames}) VALUES({qmarks});" <NEW_LINE> fieldnames = ", ".join(self.fields) <NEW_LINE> qmarks = ", ".join(["?" for _ in self.fields]) <NEW_LINE...
insert a new row into the database
625941f221a7993f00bc82d5
def _stepGame(self): <NEW_LINE> <INDENT> TEST = self.env.TEST <NEW_LINE> TEST.display("simpleapp", 3, "SudoSimpleApp - dans _playGame()") <NEW_LINE> r = _checkBeforePlaying() <NEW_LINE> if r is not True: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self._playing = True <NEW_LINE> playResult = self._game.step() ...
Joue une itération de la partie en cours. Retourne le résultat.
625941f294891a1f4081c086
def f_map_data(regle, obj): <NEW_LINE> <INDENT> val = obj.attributs.get(regle.params.att_entree.val, regle.params.val_entree.val) <NEW_LINE> obj.attributs[regle.params.att_entree.val] = remap(val, regle.elmap)
#aide||applique un mapping complexe aux donnees #aide_spec||C: fichier de mapping #pattern||A;?C;A;map_data;C #schema||ajout_attribut
625941f24f88993c3716c63a
def regularizer(circuit_params): <NEW_LINE> <INDENT> regularized_params = circuit_params[self._regularized_params_idx] <NEW_LINE> return regul_strength*myregularizer(regularized_params)
Compute the regularization term
625941f23eb6a72ae02ecac7
def get_bs4(): <NEW_LINE> <INDENT> soup = BeautifulSoup(html, features='lxml') <NEW_LINE> print(soup.attrs) <NEW_LINE> print(soup.name)
获取bs对象 :return:
625941f229b78933be1e5c7e
def __send_http_request(self, path, http_type, data=None, headers=None): <NEW_LINE> <INDENT> if headers is None: <NEW_LINE> <INDENT> all_headers = self.__headers <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> all_headers = self.__headers.copy() <NEW_LINE> all_headers.update(headers) <NEW_LINE> <DEDENT> if path[0] == '/'...
Send an HTTP message. Args: path: [string] The URL path to send to (without network location) http_type: [string] The HTTP message type (e.g. POST) data: [string] Data payload to send, if any. headers: [dict] Headers to write, if any. Returns: HttpResponseType
625941f2e1aae11d1e74a297
def minimumTotal(self, triangle): <NEW_LINE> <INDENT> if not triangle: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> n = len(triangle) <NEW_LINE> arr = triangle[-1] <NEW_LINE> for i in range(n - 2, -1, -1): <NEW_LINE> <INDENT> for j in range(i + 1): <NEW_LINE> <INDENT> arr[j] = triangle[i][j] + min(arr[j], arr[j + 1...
:type triangle: List[List[int]] :rtype: int
625941f2b830903b967e9ede
def detrim_and_decode_sagemaker_parameters(trimmed_params: dict) -> dict: <NEW_LINE> <INDENT> encoded_params = detrim_sagemaker_parameters(trimmed_params) <NEW_LINE> return valmap(decode_sagemaker_parameter, encoded_params)
Decode a SageMaker parameters dictionary where all values are strings. Example: >>> detrim_and_decode_sagemaker_parameters({ ... '_0_foo': '[1, ', ... '_1_foo': '2, 3', ... '_2_foo': ']', ... '_0_bar': 'hell', ... '_1_bar': 'o' ... }) {'foo': [1, 2, 3], 'bar': 'hello'}
625941f25166f23b2e1a5733
def consulter_Notes_Classe_SV(self, cours): <NEW_LINE> <INDENT> def notes_Classes(Notes): <NEW_LINE> <INDENT> return reduce(lambda x, y: f"{x}\nNuméro de l'étudiant: {y.numero_Etud}\tNote: {y.note}", Notes, "Les notes dans le cours " + str(cours.intitule_Cours) + ":") <NEW_LINE> <DEDENT> Notes_Cours = list(filter(lambd...
filter est utilisée pour extraire les Notes du cours en paramètre reduce est utilisée pour concatener les valeurs des notes Il s'agit de consulter les notes dans un cours donné :param cours: Cours à consulter ses notes :return: les notes dans ce cours
625941f2f7d966606f6aa5e5
def drawGL(self): <NEW_LINE> <INDENT> pass
Overwrite the refresh
625941f2e64d504609d74e19
def join(regexes): <NEW_LINE> <INDENT> if not isinstance(regexes, Sequence): <NEW_LINE> <INDENT> regexes = tuple(regexes) <NEW_LINE> <DEDENT> n = len(regexes) <NEW_LINE> if n == 2: <NEW_LINE> <INDENT> return concat(regexes[0], regexes[1]) <NEW_LINE> <DEDENT> elif n == 1: <NEW_LINE> <INDENT> return regexify(regexes[0]) ...
Concatenates a sequence of regular expressions, such that each one will be matched successively. (Note that a `Null` value anywhere in the sequence will result in a `Null` overall.) A zero-length sequence will return `Epsilon`. :param regexes: The regular expressions to concatenate.
625941f27d43ff24873a327f
def getValue(self): <NEW_LINE> <INDENT> return self.value
get the current value of the slider
625941f207d97122c4178e73
def resnet_v1(input_shape, depth, num_classes=10): <NEW_LINE> <INDENT> if (depth - 2) % 6 != 0: <NEW_LINE> <INDENT> raise ValueError('depth should be 6n+2 (eg 20, 32, 44 in [a])') <NEW_LINE> <DEDENT> num_filters = 16 <NEW_LINE> num_res_blocks = int((depth - 2) / 6) <NEW_LINE> inputs = Input(shape=input_shape) <NEW_LINE...
ResNet Version 1 Model builder [a] Stacks of 2 x (3 x 3) Conv2D-BN-ReLU Last ReLU is after the shortcut connection. At the beginning of each stage, the feature map size is halved (downsampled) by a convolutional layer with strides=2, while the number of filters is doubled. Within each stage, the layers have the same n...
625941f263f4b57ef00016e1
def _set_signal_range_in_pixels(self, i1=None, i2=None): <NEW_LINE> <INDENT> self.backup_channel_switches = copy.copy(self.channel_switches) <NEW_LINE> self.channel_switches[:] = False <NEW_LINE> if i2 is not None: <NEW_LINE> <INDENT> i2 += 1 <NEW_LINE> <DEDENT> self.channel_switches[i1:i2] = True <NEW_LINE> self.updat...
Use only the selected spectral range in the fitting routine. Parameters ---------- i1 : Int i2 : Int Notes ----- To use the full energy range call the function without arguments.
625941f2aad79263cf391024
def message(main, title, text): <NEW_LINE> <INDENT> with MsgBox(main, title, text, buttons=[MsgBox.OK_BUTTON]) as dlg: <NEW_LINE> <INDENT> dlg.run()
Shows a message box with an OK button.
625941f297e22403b379d576
def parse_command_line(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description = __doc__) <NEW_LINE> group = parser.add_mutually_exclusive_group(required = True) <NEW_LINE> group.add_argument('-n', dest = 'nstart', help = 'A positive 4-digit number to start the routine (digits must not be all the same; lead...
Parse command line arguments
625941f2a4f1c619b28b0604
def join_linestrings0(linestrings_wkb): <NEW_LINE> <INDENT> linestrings = [ogr.CreateGeometryFromWkb(g) for g in linestrings_wkb] <NEW_LINE> linestrings = [(g, g.GetPointCount()) for g in linestrings] <NEW_LINE> points = [(g.GetPoint(0), g.GetPoint(n-1)) for g, n in linestrings] <NEW_LINE> points_dict = {} <NEW_LINE> f...
:param linestrings_wkb: :return:
625941f2ac7a0e7691ed469a
def oci_client(resource_name: str, configuration: Configuration = None, secrets: Secrets = None, skip_deserialization: bool = False): <NEW_LINE> <INDENT> configuration = configuration or {} <NEW_LINE> if not configuration.get('tenancy'): <NEW_LINE> <INDENT> configuration = from_file() <NEW_LINE> <DEDENT> else: <NEW_LIN...
Create an oci configuration object
625941f2be7bc26dc91cdbce
def __init__(self, filename): <NEW_LINE> <INDENT> self.nodes = {} <NEW_LINE> self.ways = {} <NEW_LINE> self.poi = [] <NEW_LINE> self.divisor = float(2 ** 31) <NEW_LINE> if filename is not None: <NEW_LINE> <INDENT> self.loadOsm(filename)
Load an OSM XML file into memory
625941f2eab8aa0e5d26e134
def _setnull(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setnull = arcpy.sa.SetNull( self.flow_accumulation_clip, 1, "VALUE < 300" ) <NEW_LINE> setnull.save(self.storage.output_filepath('setnull')) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise StreamPreparationError( "Unexpected error during setnull cal...
Define mask.
625941f2379a373c97cfb121
def get_doctor_details(doctor_id, access_token): <NEW_LINE> <INDENT> headers = { 'Authorization': 'Bearer {}'.format(access_token) } <NEW_LINE> doctor_url = 'https://drchrono.com/api/doctors/{}'.format(doctor_id) <NEW_LINE> data = requests.get(doctor_url, headers=headers).json() <NEW_LINE> filtered_data = { 'website': ...
Given the User of a doctor, returns the details of the doctor
625941f2507cdc57c63072c3
def delete_post(request, post, **kwargs): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> remove = removal_condition(post, user) <NEW_LINE> if remove: <NEW_LINE> <INDENT> msg = f"removed post" <NEW_LINE> messages.info(request, mark_safe(msg)) <NEW_LINE> auth.db_logger(user=user, post=post, text=msg) <NEW_LINE> post....
Post may be marked as deleted or removed entirely
625941f27b25080760e39a2f
def detectCycle(self, head): <NEW_LINE> <INDENT> slow = fast = head <NEW_LINE> while fast is not None and fast.next is not None: <NEW_LINE> <INDENT> fast = fast.next.next <NEW_LINE> slow = slow.next <NEW_LINE> if fast == slow: <NEW_LINE> <INDENT> slow2 = head <NEW_LINE> while slow != slow2: <NEW_LINE> <INDENT> slow = s...
:type head: ListNode :rtype: ListNode
625941f28e05c05ec3eea954
def getxattr(self, xattr_name, **kwargs): <NEW_LINE> <INDENT> return self.s3.getxattr(self.path, xattr_name, **kwargs)
Get an attribute from the metadata. See :func:`~s3fs.S3Filesystem.getxattr`. Examples -------- >>> mys3file.getxattr('attribute_1') # doctest: +SKIP 'value_1'
625941f2097d151d1a223430
def __init__(self, is_directed=True): <NEW_LINE> <INDENT> self.__vertex_dict = {} <NEW_LINE> self.__is_directed = is_directed
Initialize a graph object with an empty vertex dictionary. Parameters: is_directed (boolean): Whether the graph is directed (edges go in only one direction).
625941f2b5575c28eb68e5e0
def test_import_application_with_two_applications(double_mock_service): <NEW_LINE> <INDENT> with pytest.raises(CommandError) as e: <NEW_LINE> <INDENT> cli._import_application("double_service") <NEW_LINE> assert "More than one Doozer application found" in e.message
Test that _import_application fails with ambiguous app choices.
625941f291f36d47f21acad3
def get_bb_url(project_name="", repo_name=""): <NEW_LINE> <INDENT> bb_home = 'https://bitbucket/dashboard' <NEW_LINE> bb_view = 'https://bitbucket/projects/{}/repos/{}' <NEW_LINE> if not project_name or not repo_name: <NEW_LINE> <INDENT> repo = get_current_bb() <NEW_LINE> if repo: <NEW_LINE> <INDENT> project_name = rep...
Get bitbucket url smartly
625941f2bd1bec0571d90c09
def get_generic_pass(account=None): <NEW_LINE> <INDENT> params = { 'security': '/usr/bin/security', 'command': 'find-generic-password', 'account': account, } <NEW_LINE> command = 'sudo {0} -v {1} -g -a "{2}"'.format( params['security'], params['command'], params['account']) <NEW_LINE> try: <NEW_LINE> <INDENT> output = ...
Search OSX keychain app and return generic password on account Example: get_generic_pass('HomeWifi') will return the password of 'HomeWifi' Args: account: account in string
625941f24d74a7450ccd479f
def __new__(mcs, name, bases, attrs): <NEW_LINE> <INDENT> attrs['pool'] = dict() <NEW_LINE> return super(FlyweightMeta, mcs).__new__(mcs, name, bases, attrs)
Override class construction to add 'pool' attribute to classes dict. @param name: The name of the class. @param bases: Base classes of the class. @param attrs: Attributes of the class. @return: A new Class.
625941f22eb69b55b151ce92
def check_connection(url="www.google.com", timeout=10.0): <NEW_LINE> <INDENT> conn = httplib.HTTPSConnection(url, timeout=timeout) <NEW_LINE> try: <NEW_LINE> <INDENT> conn.request("HEAD", "/") <NEW_LINE> conn.close() <NEW_LINE> return True <NEW_LINE> <DEDENT> except (httplib.HTTPException, socket.error): <NEW_LINE> <IN...
Check connection against url. Parameters: url (str, optional): URL to check connection against timeout (float, optional): Connection timeout Returns: bool: True, if there is a connection, False otherwise
625941f207f4c71912b11a5f
def test_plotDayPlot(self): <NEW_LINE> <INDENT> start = UTCDateTime(0) <NEW_LINE> st = self._createStream(start, start + 3 * 3600, 100) <NEW_LINE> image_name = 'waveform_dayplot.png' <NEW_LINE> with ImageComparison(self.path, image_name) as ic: <NEW_LINE> <INDENT> st.plot(outfile=ic.name, type='dayplot', timezone='EST'...
Plots day plot, starting Jan 1970.
625941f292d797404e304767
def test_models_WisonLT_stress2(): <NEW_LINE> <INDENT> for case in cases.values(): <NEW_LINE> <INDENT> for LM in case.LMs: <NEW_LINE> <INDENT> actual = LM.max_stress.max() <NEW_LINE> df = LM.LMFrame <NEW_LINE> cols = [columns for columns in df.columns if 'stress_f' in columns] <NEW_LINE> expected = df[cols].values.max(...
Make sure maximum stress is found in .max_stress for different points (p).
625941f28c0ade5d55d3ef9a
def xy_to_detyz(coor, o11, o12, o21, o22, dety_size, detz_size): <NEW_LINE> <INDENT> if abs(o11) == 1: <NEW_LINE> <INDENT> if (abs(o22) != 1) or (o12 != 0) or (o21 != 0): <NEW_LINE> <INDENT> raise ValueError('detector orientation makes no sense 1') <NEW_LINE> <DEDENT> <DEDENT> elif abs(o12) == 1: <NEW_LINE> <INDENT> if...
Transforming (x,y) coordinates of the raw image to (dety, detz) coordinates according to the detector orientation matrix given. The definition of (dety,detz) is defined in "3DXRD and TotalCryst Geometry - Version 1.0.2" by H.F. Poulsen, S. Schmidt, J. Wright, H.O. Sorensen Detector_orientation: o= [[o11,o12], ...
625941f2507cdc57c63072c4
def get_simulation_phase(line, simulation_phase): <NEW_LINE> <INDENT> if "Starting setup..." in line: simulation_phase = "SETUP" <NEW_LINE> elif "Starting the stellar emission phase..." in line: simulation_phase = "STELLAR EMISSION" <NEW_LINE> elif "Starting the dust self-absorption phase..." in line: simulation_phase ...
This function ... :param line: :param simulation_phase: current simulation phase :return:
625941f255399d3f05588c92
def test_SearchQuery_produces_terms_query_with_ids(): <NEW_LINE> <INDENT> params = { 'ids': [ '13283cd2bd45ef385aae962b144c7e6a', '00000062461c867a39cac531e13a48c1' ] } <NEW_LINE> sq = search_query.SearchQuery(params) <NEW_LINE> assert sq.query['query']['terms'] == { 'id': [ '13283cd2bd45ef385aae962b144c7e6a', '0000006...
If given an 'ids' parameter, SearchQuery produces a 'terms' query with a list of the IDs
625941f2627d3e7fe0d6942c
def p(self, text): <NEW_LINE> <INDENT> self.write('<p>{t}</p>'.format(t=text))
Writes a paragraph tagged text. :param text: The html paragraph text. :type text: str
625941f299cbb53fe67931bf
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='reads in list of LFN and registers them in the DFC') <NEW_LINE> parser.add_argument('missing_lfns', type=str, help='file containing list of LFNs to register') <NEW_LINE> args = parser.parse_args() <NEW_LINE> ctxt = gfal2.creat_context() <NEW_...
setups all the necessary infrastucture, reads in file containing LFNs to be registered and finally calls the register function
625941f2fb3f5b602dac3c74
def test_list_item_complex_map (): <NEW_LINE> <INDENT> pm = PathMap() <NEW_LINE> assert_equal(pm.metadata({"level1":[{"level2":"level2-value1"}]}, 1), 1) <NEW_LINE> assert_equal(pm.metadata({"level1":[{"level2":"level2-value2"}]}, 2), 2) <NEW_LINE> assert_equal(pm.metadata({"level1":[{"level2":"level2-value1"}]}), 1) <...
list path mapping - item level, multiple items present
625941f2ab23a570cc250762
def ReadWord(self, *args, **kwargs): <NEW_LINE> <INDENT> pass
Read a word (integer).
625941f29f2886367277ae62
def visualize(img, cam): <NEW_LINE> <INDENT> _, _, H, W = img.shape <NEW_LINE> cam = F.interpolate(cam, size=(H, W), mode='bilinear', align_corners=False) <NEW_LINE> cam = 255 * cam.squeeze() <NEW_LINE> heatmap = cv2.applyColorMap(np.uint8(cam), cv2.COLORMAP_JET) <NEW_LINE> heatmap = torch.from_numpy(heatmap.transpose(...
Synthesize an image with CAM to make a result image. Args: img: (Tensor) shape => (1, 3, H, W) cam: (Tensor) shape => (1, 1, H', W') Return: synthesized image (Tensor): shape =>(1, 3, H, W)
625941f2fff4ab517eb2fa1a
def testUpdateOfMissingAttr(t, env): <NEW_LINE> <INDENT> sess = env.c1.new_client_session(env.testname(t)) <NEW_LINE> open_op = open_create_file_op(sess, env.testname(t), open_create=OPEN4_CREATE) <NEW_LINE> res = sess.compound(open_op + [op.close(0, current_stateid)]) <NEW_LINE> check(res, NFS4_OK) <NEW_LINE> fh = res...
Server MUST return NFS4ERR_NOXATTR on update of missing attribute. FLAGS: xattr CODE: XATT5
625941f2d486a94d0b98e721
def ST1K(self): <NEW_LINE> <INDENT> return _trellis.trellis_pccc_decoder_b_sptr_ST1K(self)
ST1K(self) -> int
625941f2d53ae8145f87a83e
def generic_equivalent_for_bnf_code(bnf_code): <NEW_LINE> <INDENT> if len(bnf_code) != 15: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if EXCLUSIONS_RE.match(bnf_code): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> chemical = bnf_code[0:9] <NEW_LINE> generic_strength_and_formulation = bnf_code[13:15] <NEW_LINE> has...
Return the generic equivalent BNF code for a supplied BNF code or None if there is no such equivalent
625941f291f36d47f21acad4
def to_latex(self): <NEW_LINE> <INDENT> latex_code = latex(self.A) <NEW_LINE> latex_code = latex_code.replace(r'\left[\begin{matrix}', r'\begin{pmatrix}') <NEW_LINE> latex_code = latex_code.replace(r'\end{matrix}\right]', r'\end{pmatrix}') <NEW_LINE> format_args = self.source.to_latex(), self.target.to_latex() <NEW_LIN...
Return the homomorphism as a :math:`\LaTeX` string. Returns ------- latex : str The HomLCA formatted as a LaTeX string. Examples -------- >>> phi = HomLCA([1]) >>> phi.to_latex() '\\begin{pmatrix}1\\end{pmatrix}:\\mathbb{Z} \\to \\mathbb{Z}'
625941f2a17c0f6771cbe629
def build_dc_classifier(batch_size=128): <NEW_LINE> <INDENT> return nn.Sequential( Unflatten(batch_size, 3, 32, 32), nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1), nn.LeakyReLU(negative_slope=0.01, inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(in_channels=32, out_channels=64, kern...
Build and return a PyTorch model for the DCGAN discriminator implementing the architecture above.
625941f256ac1b37e626479d
def forward(self, sents_tensor, lengths, target_tensor): <NEW_LINE> <INDENT> seq_embed = self.embedding_layer(sents_tensor) <NEW_LINE> lstm_out, _ = self.bilstm(seq_embed, lengths) <NEW_LINE> lstm_out = self.cls_dropout(lstm_out) <NEW_LINE> lstm_feats = self.classifier(lstm_out) <NEW_LINE> loss = cal_loss(lstm_feats, t...
前向传播,计算loss Args: sents_tensor (torch.Tensor): 输入的训练样本 [batch_size, max_seq_len, embed_dim] lengths (torch.Tensor): batch中每个句子pad之前的长度 [batch_size] target_tensor (torch.Tensor): 标签 [batch_size, max_seq_len] Returns: -loss
625941f24e4d5625662d49a9
def getMyPeriod(self, name): <NEW_LINE> <INDENT> if not self.proxy: <NEW_LINE> <INDENT> self.proxy = ALProxy("ALDarknessDetection") <NEW_LINE> <DEDENT> return self.proxy.getMyPeriod(name)
Gets the period for a specific subscription. :param str name: Name of the module which has subscribed. :returns int: Refresh period (in milliseconds).
625941f21f5feb6acb0c5123
def RidgeRegression(H, y, l): <NEW_LINE> <INDENT> Nf = H.shape[1] <NEW_LINE> I = np.eye(Nf) <NEW_LINE> A = np.array(np.linalg.inv(H.T.dot(H) + 2 * l * I)) <NEW_LINE> B = np.array(H.T.dot(y)) <NEW_LINE> C = A.dot(B) <NEW_LINE> y_est = np.array(H.dot(C)) <NEW_LINE> return C, y_est
Функция, осуществляющая поиск линейных параметров 'C' с помощью МНК :param H: матрица функций :param y: вектор выходных значений (энергии) :param l: параметр регуляризации :return: линейные коэффициенты, приближенное значение энергий (y)
625941f2287bf620b61d403a
def writeSetting(self,attribute,value): <NEW_LINE> <INDENT> if type(value) == datetime: <NEW_LINE> <INDENT> value = mktime(value.timetuple()) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> QgsProject.instance().writeEntry("TimeManager",attribute, value ) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> QMessageB...
write plugin settings to QgsProject instance
625941f285dfad0860c3b437
def getInput(self,channel): <NEW_LINE> <INDENT> for i in self.inputs: <NEW_LINE> <INDENT> if i.getChannel() == channel: <NEW_LINE> <INDENT> return i
get input by channel id :param channel: :return: Input
625941f266656f66f7cbc787
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ELP.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure it'...
Run administrative tasks.
625941f276e4537e8c351c52
def create_station_label(): <NEW_LINE> <INDENT> global station_label, radio_logo <NEW_LINE> station = vlc.get_title() <NEW_LINE> if station != '': <NEW_LINE> <INDENT> for line in playlist: <NEW_LINE> <INDENT> line = line.split(';') <NEW_LINE> if line[0] in station: <NEW_LINE> <INDENT> if line[1]: <NEW_LINE> <INDENT> st...
Generate station name label amd radio logo item
625941f2a8370b7717052e78