code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def is_match(self, g, tup): <NEW_LINE> <INDENT> if len(tup) != len(self.port_labels): <NEW_LINE> <INDENT> raise(ValueError(f'tuple {tup} and port_labels {self.port_labels} do not have the same length.')) <NEW_LINE> <DEDENT> mate_sets = [] <NEW_LINE> for nodeid, port_label in zip(tup, self.port_labels): <NEW_LINE> <INDE... | tup must have same length as self.port_labels. | 625941d32c8b7c6e89b35989 |
def test_getting_state(self): <NEW_LINE> <INDENT> no_replicates = 25 <NEW_LINE> replicate(experiment2, no_replicates) <NEW_LINE> for i in range(no_replicates): <NEW_LINE> <INDENT> self.assertNotIn('result', state[SUBSTATE_KEY_PATTERN % i]) | Test getting
| 625941d376e4537e8c35183c |
def import_class(class_path): <NEW_LINE> <INDENT> components = class_path.split(".") <NEW_LINE> mod = __import__(components[0]) <NEW_LINE> for comp in components[1:]: <NEW_LINE> <INDENT> mod = getattr(mod, comp) <NEW_LINE> <DEDENT> return mod | Imports a class having dynamic name/path.
Args:
class_path: str
Path to class (exp: "model.MmdetDetectionModel")
Returns:
mod: class with given path | 625941d37d847024c06be486 |
@with_setup(setup_resources) <NEW_LINE> def test_security_enabled_object(): <NEW_LINE> <INDENT> myobj = LocalSecurityEnabledObject(title='Unit01Web', vpc=vpc, template=template) <NEW_LINE> assert_equals(myobj.title, 'Unit01Web') <NEW_LINE> assert_equals(myobj.trop_security_group.title, 'Unit01WebSg') <NEW_LINE> assert_... | Test title, security group title, template | 625941d38e7ae83300e4b196 |
def get(id): <NEW_LINE> <INDENT> individual = LajiStoreAPI.get_individual(id) <NEW_LINE> return Individual(**individual) | Gets a device from LajiStore
:param id: The LajiStore ID of the individual
:return: A Individual object | 625941d30a50d4780f66705c |
def run_tests(nb_path): <NEW_LINE> <INDENT> with open(nb_path) as f: <NEW_LINE> <INDENT> nb = json.load(f) <NEW_LINE> <DEDENT> print('Run the ok tests before you publish to make sure they work!') | Run ok tests in the autograder version of the notebook. | 625941d3be383301e01b564d |
def upload_file(self, file_path, chunk_size=1024): <NEW_LINE> <INDENT> file_to_send = open(file_path, 'rb') <NEW_LINE> file_guid = self.client.service.BeginChunkedFileUpload( file_path, False) <NEW_LINE> while True: <NEW_LINE> <INDENT> data = b64encode(file_to_send.read(chunk_size)) <NEW_LINE> if not data: <NEW_LINE> <... | Uploads given file to memoQ Server. Returns guid of uploaded file. | 625941d301c39578d7e75004 |
def swissPairings(): <NEW_LINE> <INDENT> db = connect() <NEW_LINE> tournament_cursor = db.cursor() <NEW_LINE> tournament_cursor.execute('select * from swiss_pairings_view;') <NEW_LINE> rows = tournament_cursor.fetchall() <NEW_LINE> db.close() <NEW_LINE> if countPlayers() % 2 != 0: <NEW_LINE> <INDENT> insertByeMatch(row... | Returns a list of pairs of players for the next round of a match.
Assuming that there are an even number of players registered, each player
appears exactly once in the pairings. Each player is paired with another
player with an equal or nearly-equal win record, that is, a player adjacent
to him or her in the standing... | 625941d34c3428357757c4f0 |
def get_zone_requested_mode(self, thermostat_id=None, zone_id=0): <NEW_LINE> <INDENT> return self._get_zone_key("requested_zone_mode", thermostat_id=thermostat_id, zone_id=zone_id).upper() | Returns the requested mode of the zone. This should match the zone's
mode on the thermostat.
Available options can be found in NexiaThermostat.OPERATION_MODES
:param thermostat_id: int - the ID of the thermostat to use
:param zone_id: The index of the zone, defaults to 0.
:return: str | 625941d355399d3f0558887e |
@cache <NEW_LINE> def importIGG(): <NEW_LINE> <INDENT> df = load_file("data-luminex-igg") <NEW_LINE> df = pd.melt(df, id_vars=["subject"]) <NEW_LINE> df["variable"] = df["variable"].str.replace("IgG.", "", regex=False) <NEW_LINE> return df | Import the IgG measurements. | 625941d3d18da76e235326a0 |
def _smtp_server_bind(self, _type=None): <NEW_LINE> <INDENT> dn = self.useraddr.split("@")[-1] <NEW_LINE> if dn in ("qq.com", "foxmail.com", "vip.qq.com"): <NEW_LINE> <INDENT> _type = "QQ" <NEW_LINE> <DEDENT> elif dn in ("163.com"): <NEW_LINE> <INDENT> _type = "163" <NEW_LINE> <DEDENT> if _type == "QQ": <NEW_LINE> <IND... | 根据email后缀绑定邮件服务器信息 | 625941d32ae34c7f2600d2fa |
def test_monthly_indicator_start_date_none_ipca(self): <NEW_LINE> <INDENT> start_date = None <NEW_LINE> end_date = datetime.date(2010, 3, 5).strftime('%d/%m/%Y') <NEW_LINE> url = f'https://api.bcb.gov.br/dados/serie/bcdata.sgs.433/dados?formato=json&dataInicial={start_date}&dataFinal={end_date}' <NEW_LINE> expected = {... | When start_date is an invalid value (such as an alphabetic character
or None), the api will query all results, not respecting the end_date.
This test proves that the end_date is not respected. | 625941d33c8af77a43ae396a |
def get_k_data(self, symbol, freq, start_date, end_date): <NEW_LINE> <INDENT> data_frame = self.data_source.coinbar(exchange='huobi', symbol=symbol, freq=freq, start_date=start_date, end_date=end_date) <NEW_LINE> water_data = to_water_data_structure(data_frame) <NEW_LINE> return water_data | symbol 可以直接用
period 也可以用
start_date 和 stop_date 需要按period 化成多大的size
获取行情数据
:param symbol:
:param freq:
:param start_date:
:param stop_date:
:return: | 625941d3ec188e330fd5a966 |
def vgg16_bn(args, pretrained=False, progress=True, mask=False, fourth_dim=False, **kwargs): <NEW_LINE> <INDENT> return _vgg('vgg16_bn', 'D', True, pretrained, project_path=args.project_path, **kwargs) | VGG 16-layer model (configuration "D") with batch normalization
`"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the downlo... | 625941d316aa5153ce362641 |
def read_list(sents, max_chars=None): <NEW_LINE> <INDENT> dataset = [] <NEW_LINE> textset = [] <NEW_LINE> for sent in sents: <NEW_LINE> <INDENT> data = ['<bos>'] <NEW_LINE> text = [] <NEW_LINE> for token in sent: <NEW_LINE> <INDENT> text.append(token) <NEW_LINE> if max_chars is not None and len(token) + 2 > max_chars: ... | read raw text file. The format of the input is like, one sentence per line
words are separated by ' '
:param sents:
:param max_chars: int, the number of maximum characters in a word, this
parameter is used when the model is configured with CNN word encoder.
:return: | 625941d3187af65679ca52e9 |
def verify(self, sig, *args): <NEW_LINE> <INDENT> if self.challenge(sig, *args): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise authme.exc.SignatureBad("Incorrect HMAC challenge.") | Verifies HMAC signature by rehashing *args.
sig bstr bytestring challenge signature.
*args arglist arguments to be hashed.
returns boolean True or raises SignatureBad exception. | 625941d3d7e4931a7ee9e0e8 |
def FBConfigFile(self,pConfigFileName,pConfigFilePath,pVirtualMode,pClearFile): <NEW_LINE> <INDENT> pass | Constructor.
This will open the desired config file in the designed folder. The file will be created if it does not exists. By prefixing the character '@' to the file name, this will automatically prepend the current machine name to the config file, the way it is done for the other config files of the application.
pCo... | 625941d3236d856c2ad449a6 |
def validate_new_password( x: str, req: Optional["CamcopsRequest"] = None) -> None: <NEW_LINE> <INDENT> _ = req.gettext if req else dummy_gettext <NEW_LINE> if not x or not x.strip(): <NEW_LINE> <INDENT> raise ValueError(_("Passwords can't be blank")) <NEW_LINE> <DEDENT> if len(x) < MINIMUM_PASSWORD_LENGTH: <NEW_LINE> ... | Validate a proposed new password. Enforce our password policy. | 625941d3aad79263cf390c0c |
def assignClassAndPath(self, dataArr, classArr,splitNodeIndex, entropy0, entropy1): <NEW_LINE> <INDENT> class0Arr = np.array([]) <NEW_LINE> class1Arr = np.array([]) <NEW_LINE> if entropy0==0: <NEW_LINE> <INDENT> index0Arr = np.where(dataArr[:,splitNodeI... | given function takes dataArr, classArr and entropies;
It returns class and path values | 625941d3adb09d7d5db6c958 |
def getEvaluation(self): <NEW_LINE> <INDENT> if not hasattr(self, "_evaluation"): <NEW_LINE> <INDENT> self._evaluation = None <NEW_LINE> <DEDENT> return self._evaluation | gets the evaluation to which this question belongs. | 625941d3d18da76e235326a1 |
def _derive_names_path(self): <NEW_LINE> <INDENT> base, ext = path.splitext(self._input_filename) <NEW_LINE> return '%s.names' % base | Guess unique names file path produced by Mothur | 625941d34527f215b584c61f |
def returnNetVio2 (self, system_option): <NEW_LINE> <INDENT> number_vios = len(config.systems.get(system_option)) <NEW_LINE> self.vio1 = config.systems.get(system_option)[0] <NEW_LINE> self.vio2 = config.systems.get(system_option)[1] <NEW_LINE> if number_vios == 4: <NEW_LINE> <INDENT> self.vionet1 = config.systems.get(... | Indicating the system, returns the NETWORK VIO2 | 625941d3c4546d3d9de72bfe |
def __convert_inputcode(self): <NEW_LINE> <INDENT> inputcodes = [] <NEW_LINE> if self.__mainset: <NEW_LINE> <INDENT> main_input = self.__mainset <NEW_LINE> inputcode = '{0} = self.prj({1})'.format(main_input.name, self.__filters['main'].code) <NEW_LINE> if main_input.idx: <NEW_LINE> <INDENT> inputcode += '[{}]'.format(... | Method to convert input code for building custom code
:return: | 625941d3796e427e537b0790 |
def has_duplicates(self, filename: str) -> bool: <NEW_LINE> <INDENT> with open(filename, "r", encoding = "utf-8") as f: <NEW_LINE> <INDENT> all_lines = f.readlines() <NEW_LINE> <DEDENT> all_lines = [l.strip() for l in all_lines] <NEW_LINE> shortcut_dict = collections.defaultdict(dict) <NEW_LINE> found_ctxt = False <NEW... | Checks if the given file has duplicate shortcut keys. | 625941d3293b9510aa2c345e |
def test_already_existing_username(self): <NEW_LINE> <INDENT> reg_data = { 'username':'chrisevans', 'email': 'test1@example.com', 'password': 'J@yd33n', 'cpassword': 'J@yd33n' } <NEW_LINE> self.register_user(self.user_data) <NEW_LINE> res = self.register_user(reg_data) <NEW_LINE> self.assertEqual(res.status_code, 302) ... | Test if username already exists. | 625941d360cbc95b062c670d |
def testNoData(self): <NEW_LINE> <INDENT> self.assertRaises(ElectionProfileError, ElectionProfile) | exception if no profile data supplied | 625941d310dbd63aa1bd2d6c |
def QLearning(mdp, alpha, epsilon, iterNum, maxWalkLen=100, echoSE=False): <NEW_LINE> <INDENT> qFunc = { (state, action): 0.0 for state in mdp.states for action in mdp.actions } <NEW_LINE> if echoSE: <NEW_LINE> <INDENT> squareErrors = [] <NEW_LINE> <DEDENT> for _ in range(iterNum): <NEW_LINE> <INDENT> if echoSE: <NEW_L... | alpha: learning rate
q(s, a) = q(s, a) + \alpha * (r + \gamma * max_{a'}(q(s', a')) - q(s, a))
Q-learning is off-policy: it can learn from other policies, such as random policy. | 625941d3656771135c3eba39 |
def __lt__(self, other): <NEW_LINE> <INDENT> return sqrt(self.x * self.x + self.y * self.y) < sqrt(other.x * other.x + other.y * other.y) | Smaller point is closer to the origin | 625941d36fb2d068a760f268 |
def _check_lsb_name(self, pkg): <NEW_LINE> <INDENT> name = pkg.name <NEW_LINE> if name and not self.name_regex.search(name): <NEW_LINE> <INDENT> self.output.add_info('E', pkg, 'non-lsb-compliant-package-name', pkg.name) | Check if the package name is LSB compliant (only lowercase
letters, numbers, '.', '+' or '-' characters). | 625941d3293b9510aa2c345f |
def processIncomingPacket(self, data, callback): <NEW_LINE> <INDENT> self.addToFrame(data) <NEW_LINE> while True: <NEW_LINE> <INDENT> if self.isFrameReady(): <NEW_LINE> <INDENT> if self.checkFrame(): <NEW_LINE> <INDENT> self._process(callback) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if len(self.__buffer): <NEW_LI... | The new packet processing pattern
This takes in a new request packet, adds it to the current
packet stream, and performs framing on it. That is, checks
for complete messages, and once found, will process all that
exist. This handles the case when we read N + 1 or 1 / N
messages at a time instead of 1.
The processed ... | 625941d37b180e01f3dc49c5 |
def do_weight_decay_and_make_grads_zero(self): <NEW_LINE> <INDENT> assert self.masks <NEW_LINE> for name, module in self.model.named_modules(): <NEW_LINE> <INDENT> if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear): <NEW_LINE> <INDENT> if 'classifiers' in name: <NEW_LINE> <INDENT> continue <NEW_LINE> <DE... | Sets grads of fixed weights to 0. | 625941d3956e5f7376d71036 |
@fixture <NEW_LINE> def u_admin(): <NEW_LINE> <INDENT> return Mock(roles=[ADMIN], userID='luigi') | An instance of authuser with some roles | 625941d3442bda511e8be5e1 |
def addReactionLibraryToEdge(self, reactionLibrary): <NEW_LINE> <INDENT> database = rmgpy.data.rmg.database <NEW_LINE> self.newReactionList = [] <NEW_LINE> self.newSpeciesList = [] <NEW_LINE> numOldEdgeSpecies = len(self.edge.species) <NEW_LINE> numOldEdgeReactions = len(self.edge.reactions) <NEW_LINE> logging.info('Ad... | Add all species and reactions from `reactionLibrary`, a
:class:`KineticsPrimaryDatabase` object, to the model edge. | 625941d350812a4eaa59c4ea |
def test_tree_all_pairs_lowest_common_ancestor1(self): <NEW_LINE> <INDENT> assert_equal(dict(tree_all_pairs_lca(self.DG)), self.ans) | Specifying the root is optional. | 625941d329b78933be1e5874 |
def _setupScene(self): <NEW_LINE> <INDENT> self.client = self.simulation_manager.launchSimulation(gui=self.gui) <NEW_LINE> self.pepper = self.simulation_manager.spawnPepper( self.client, spawn_ground_plane=True) <NEW_LINE> self.pepper.goToPosture("Stand", 1.0) <NEW_LINE> self.pepper.setAngles("RHand", 0.7, 1.0) <NEW_LI... | Setup a scene environment within the simulation | 625941d3498bea3a759b9c78 |
def write_partition_multiple(data, labels, partition_size, dataset_path, basefile="partition", writer=None): <NEW_LINE> <INDENT> assert (len(data) == len(labels)), "Data must be of the same length as the labels" <NEW_LINE> if writer is None: <NEW_LINE> <INDENT> writer = libsvm_write_partition <NEW_LINE> <DEDENT> datase... | Write a new record to the dataset
Parameters
----------
data : ndarray or list[ndarray]
Data to be stored. Shape: (nexamples, ...)
Alternatively: list[ndarray] with one array for each example
labels : ndarray or list
The labels for this data. Shape: (nexamples, )
Alternatively: list with one input for ... | 625941d3a4f1c619b28b0200 |
def calc_jp1d(uk, unkm): <NEW_LINE> <INDENT> jp = [jp_no_norm(p, uk, unkm) for p in uk] <NEW_LINE> return np.array(jp) | Calculate J(p) from n(k) | 625941d34c3428357757c4f1 |
def native_readfile(mode, mypath, none_on_missing=False, encoding=None): <NEW_LINE> <INDENT> f = None <NEW_LINE> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f = open(mypath, mode, encoding=encoding) <NEW_LINE> return f.read() <NEW_LINE> <DEDENT> except IOError as oe: <NEW_LINE> <INDENT> if none_on_missing and oe.... | Read a file, returning the contents.
:param mypath: fs path for the file to read
:param none_on_missing: whether to return None if the file is missing,
else through the exception | 625941d3a8370b7717052a68 |
def check_by_uid(uid): <NEW_LINE> <INDENT> url = UNFORMATTED_URL.format(uid) <NEW_LINE> res = requests.get(url) <NEW_LINE> return res.json() | uid: str | 625941d3fb3f5b602dac385e |
def displayName(self): <NEW_LINE> <INDENT> return self.tr('Summit process using a GDAL tool') | Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name. | 625941d3d99f1b3c44c67756 |
def __get_request_token(self, username, password): <NEW_LINE> <INDENT> body = { 'country': 'DE', 'deviceName': 'tellonym-for-python', 'deviceType': 'ios', 'lang': 'de', 'email': username, 'password': password, 'idfa': '', 'limit': 13 } <NEW_LINE> r = requests.post(self.login_url, json=body, headers=self.non_auth_header... | Used to login to Tellonym
Args:
username (str): your username for Tellonym
password (str): your password for Tellonym
Returns:
req_token (str): the request token used for authenticating our requests | 625941d3fbf16365ca6f6391 |
def make_sql_query(ids, tablename='Papers', id_colname='Paper_ID'): <NEW_LINE> <INDENT> ids_str = format_ids_for_sql(ids) <NEW_LINE> stmt = "SELECT * FROM {tablename} WHERE {id_colname} IN ({ids})".format(tablename=tablename, id_colname=id_colname, ids=ids_str) <NEW_LINE> return db.read_sql(stmt) | Query MySQL database by list of IDs, returning a pandas dataframe | 625941d3cb5e8a47e48b7c72 |
def get_computer_sleep(): <NEW_LINE> <INDENT> ret = salt.utils.mac_utils.execute_return_result("systemsetup -getcomputersleep") <NEW_LINE> return salt.utils.mac_utils.parse_return(ret) | Display the amount of idle time until the computer sleeps.
:return: A string representing the sleep settings for the computer
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' power.get_computer_sleep | 625941d357b8e32f52483665 |
def abort(self, id): <NEW_LINE> <INDENT> return self.request.post("abort", data=dict(id=id)) | Deletes a replacement Dynamic List.
Uses the API documentated at http://dev.datasift.com/docs/rest-api/listreplaceabort
:param id: id of the replacement list to abort
:type id: str
:return: dict of REST API output with headers attached
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.excepti... | 625941d3f7d966606f6aa1cf |
def remotecmd(self, instance, *args, **kwargs): <NEW_LINE> <INDENT> jump_address = self.find_jump_address() <NEW_LINE> address = instance.private_ip_address <NEW_LINE> if not address: <NEW_LINE> <INDENT> raise CommandError("No private IP address available to ssh to") <NEW_LINE> <DEDENT> return self.disco_remote_exec.re... | remotecmd accepts a boto instance followed by a list containing a string
of all arguments, starting with the program to run.
remotecmd optionally accepts four additional named arguments:
stdin -- the bytes to send into program input
nothrow -- when True the method will not throw if the program returns a non-zero resu... | 625941d3004d5f362079a4fc |
@plugin(TEMPLATE_CONTEXT_PROCESSORS) <NEW_LINE> def expose_timezone(request, ctx): <NEW_LINE> <INDENT> ctx['TIME_ZONE'] = request.context.config['timezone'] | exposes the variable 'TIME_ZONE' with the name
of the configured time zone to templates. | 625941d330dc7b7665901b2f |
def highlightPageFull(testUrl, *moreUrls): <NEW_LINE> <INDENT> urls = [testUrl] + list(moreUrls) <NEW_LINE> p = request.path.lstrip("/") <NEW_LINE> for url in urls: <NEW_LINE> <INDENT> if p==url: <NEW_LINE> <INDENT> return " class='active'" <NEW_LINE> <DEDENT> <DEDENT> return "" | If the full path on this site is (testUrl), return
" class='active'". | 625941d3dd821e528d63b372 |
def move_cascade_to_foundation(cascades, foundation, n): <NEW_LINE> <INDENT> topCard = cascades[n].pop() <NEW_LINE> foundation[topCard[1]] = topCard[0] | Move the bottom card of cascade 'n' to a foundation list. | 625941d366656f66f7cbc375 |
def download_buildings(args): <NEW_LINE> <INDENT> bbox = {'north': 57.149, 'south': 45.225, 'east': -9.599, 'west': 28.734} <NEW_LINE> tags = {'building': True} <NEW_LINE> create_path(args.output_path) <NEW_LINE> buildings_file = os.path.join(args.output_path, "buildings.gpkg") <NEW_LINE> print("create bounding box...... | Downloads OSM buildings based on defined bounding box and filters buildings with height
:param args: arguments from argument parser
:return: | 625941d3c432627299f04e11 |
def collectMetadata(self, file): <NEW_LINE> <INDENT> self.file_counter += 1 <NEW_LINE> if not os.path.isfile(file): <NEW_LINE> <INDENT> self.log.info("File no longer exists in archive %s" % os.path.basename(file)) <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> fas = self._collectFilesAndSegments(file) <... | WFCatalogCollector._collectMetadata
> collects the metadata from the ObsPy mseedMetadata class | 625941d3cb5e8a47e48b7c73 |
def pad_defaults_list(defaults_list, expected_length): <NEW_LINE> <INDENT> pad_count = expected_length - len(defaults_list) <NEW_LINE> for value in itertools.chain([inspect.Parameter.empty] * pad_count, defaults_list): <NEW_LINE> <INDENT> yield value | Pads a defaults list to match the expected length | 625941d3627d3e7fe0d6901a |
def findFreeEntryandFill(self): <NEW_LINE> <INDENT> free_Entry = -1 <NEW_LINE> for ientry in self.vlcEntry: <NEW_LINE> <INDENT> if(ientry == INITIAL): <NEW_LINE> <INDENT> free_Entry = self.vlcEntry.index(ientry) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if(free_Entry == -1): <NEW_LINE> <INDENT> return <NEW_LINE> <D... | find a free Entry, if not just return with nothing
occupy a outsdnglist in VLC, if not just return with nothing | 625941d38a43f66fc4b5422e |
def get_uniqueness_constraints(self, label): <NEW_LINE> <INDENT> return [ unique["property_keys"][0] for unique in self._uniqueness_constraint_template.expand(label=label).get().content ] | Fetch a list of unique constraints for a label.
| 625941d3f548e778e58cd748 |
@api_view(['POST']) <NEW_LINE> @permission_classes((AllowAny,)) <NEW_LINE> def save_experiment_result(request, pk): <NEW_LINE> <INDENT> user_data = request.data.get("requiredData") <NEW_LINE> scores = request.data.get("scores") <NEW_LINE> first_name = user_data["firstName"] <NEW_LINE> last_name = user_data["lastName"] ... | API endpoint for saving a new result for an experiment with provided ID.
Returns:
HTTP status | 625941d3167d2b6e31218d60 |
def ToFractional(self, timeunit: int) -> float: <NEW_LINE> <INDENT> return self.microseconds / timeunit | Returns the duration as float, converted to the given time unit.
Examples:
>>> Duration.From(30, SECONDS).ToFractional(MINUTES)
0.5
>>> Duration.From(100, SECONDS).ToFractional(SECONDS)
100.0
>>> Duration.From(6, MINUTES).ToFractional(HOURS)
0.1
Args:
timeunit: A unit of time ranging from rdfvalue.MIC... | 625941d3be8e80087fb20e0b |
def test_login_page_works(self): <NEW_LINE> <INDENT> response = self.client.get("/accounts/login") <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertTemplateUsed(response, "login.html") <NEW_LINE> self.assertIn(b"<title>HI-Ware: Login</title>", response.content) | Test login page is loaded. | 625941d3eab8aa0e5d26dd22 |
def print_nexus_string(self): <NEW_LINE> <INDENT> self._write_nexus_file(write=False) <NEW_LINE> print(self._nexstring) | update nexus string and print | 625941d3656771135c3eba3a |
def test_predict(): <NEW_LINE> <INDENT> K = np.array([[ 1, 2, 4], [ 6, 3, 5]]) <NEW_LINE> a = np.array([1,-1,1]) <NEW_LINE> y = np.array([1,-1,1]) <NEW_LINE> b = 0. <NEW_LINE> y_test = predict(K,a,y,b) <NEW_LINE> assert type(y_test) == np.ndarray <NEW_LINE> assert y_test.shape == (2,) <NEW_LINE> assert np.allclose(y_te... | (3 points) predict | 625941d39b70327d1c4e0fa0 |
def create_request_dict(method, *args, **kwargs): <NEW_LINE> <INDENT> if kwargs: <NEW_LINE> <INDENT> params = kwargs <NEW_LINE> if args: <NEW_LINE> <INDENT> params["__args"] = args <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> params = args <NEW_LINE> <DEDENT> if isinstance(params, tuple): <NEW_LINE> <INDENT> ... | Returns a JSON-RPC-Dictionary for a method
:param method: Name of the method
:param args: Positional parameters
:param kwargs: Named parameters | 625941d399cbb53fe6792db0 |
def process_data(cur, conn, filepath, func): <NEW_LINE> <INDENT> all_files = [] <NEW_LINE> for root, dirs, files in os.walk(filepath): <NEW_LINE> <INDENT> files = glob.glob(os.path.join(root, '*.json')) <NEW_LINE> for f in files: <NEW_LINE> <INDENT> all_files.append(os.path.abspath(f)) <NEW_LINE> <DEDENT> <DEDENT> num_... | Returns list of the pathnames of the json files. | 625941d37d43ff24873a2e6b |
@register.filter <NEW_LINE> def has_role_permission(membership, permission_string): <NEW_LINE> <INDENT> model, permission = permission_string.split(':') <NEW_LINE> return shortcuts.has_role_permission(membership, model, permission) | :param permission_string: 'app_label.model:permission'. | 625941d307f4c71912b1164d |
@not_implemented_for("directed") <NEW_LINE> @not_implemented_for("multigraph") <NEW_LINE> def treewidth_min_fill_in(G): <NEW_LINE> <INDENT> return treewidth_decomp(G, min_fill_in_heuristic) | Returns a treewidth decomposition using the Minimum Fill-in heuristic.
The heuristic chooses a node from the graph, where the number of edges
added turning the neighbourhood of the chosen node into clique is as
small as possible.
Parameters
----------
G : NetworkX graph
Returns
-------
Treewidth decomposition : (int... | 625941d371ff763f4b549857 |
def has_elevations(self): <NEW_LINE> <INDENT> if not self.points: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> found = 0 <NEW_LINE> for track_point in self.points: <NEW_LINE> <INDENT> if track_point.elevation: <NEW_LINE> <INDENT> found += 1 <NEW_LINE> <DEDENT> <DEDENT> return len(self.points) > 2 and float(found... | Returns if points in this segment contains elevation.
The first point, the last point, and at least 75% of the points must
have elevation for this method to return true. | 625941d3e8904600ed9f20f8 |
def verbPhrase(): <NEW_LINE> <INDENT> return random.choice(verbs) + " " + nounPhrase() + " " + prepositionalPhrase() | Builds and returns a verb phrase. | 625941d3090684286d50eeb1 |
def set_ClientID(self, value): <NEW_LINE> <INDENT> super(ListRowsInputSet, self)._set_input('ClientID', value) | Set the value of the ClientID input for this Choreo. ((conditional, string) The Client ID provided by Microsoft. This is requried unless providing a valid AccessToken (see optional inputs).) | 625941d321a7993f00bc7ebc |
@csrf_exempt <NEW_LINE> @require_http_methods(["DELETE", "GET", "POST", "PUT"]) <NEW_LINE> @silk_profile(name='Handle user albums by title') <NEW_LINE> def handle_album_by_title(request): <NEW_LINE> <INDENT> query = get_query(request) <NEW_LINE> params = ["token", "title"] <NEW_LINE> if request.method == "POST": <NEW_L... | create_album creates an album with the specified title associated to the
user
:param request: HTTP REST request with the title of the album and the user
token
:return: JSON containing album_id if all went well, error otherwise | 625941d3f8510a7c17cf98c7 |
def define_backend(self,backend,result,variables): <NEW_LINE> <INDENT> if (backend not in self.possible_options_list): <NEW_LINE> <INDENT> raise ValueError('Invalid backend specified. Should be one of ', self.possible_options_list) <NEW_LINE> <DEDENT> if (backend in self.backend_list): <NEW_LINE> <INDENT> return backen... | Try to make a good guess for the backend... available methods are: (host means Cpu, device means Gpu)
CPU : computations performed with the host from host arrays
GPU_1D_device : computations performed on the device from device arrays, using the 1D scheme
GPU_2D_device : computations performed on the device from ... | 625941d3377c676e91272373 |
def testxmlconfig(file): <NEW_LINE> <INDENT> context = _getContext() <NEW_LINE> processxmlfile(file, context, testing=True) <NEW_LINE> context.execute_actions(testing=True) | xmlconfig that doesn't raise configuration errors
This is useful for testing, as it doesn't mask exception types. | 625941d3b57a9660fec33a4f |
def collection(self, path): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for item in self.get_collection(path): <NEW_LINE> <INDENT> data.append(item) <NEW_LINE> <DEDENT> return data | To return all items generated by get collection. | 625941d38c0ade5d55d3eb86 |
def exp(self, tangent_vec, base_point, **kwargs): <NEW_LINE> <INDENT> log_base_point = SPDMatrices.logm(base_point) <NEW_LINE> dlog_tangent_vec = SPDMatrices.differential_log(tangent_vec, base_point) <NEW_LINE> exp = SymmetricMatrices.expm(log_base_point + dlog_tangent_vec) <NEW_LINE> return exp | Compute the Log-Euclidean exponential map.
Compute the Riemannian exponential at point base_point
of tangent vector tangent_vec wrt the Log-Euclidean metric.
This gives a symmetric positive definite matrix.
Parameters
----------
tangent_vec : array-like, shape=[..., n, n]
Tangent vector at base point.
base_point ... | 625941d391f36d47f21ac6be |
def upwind_flux_maxwell_eq(u_n): <NEW_LINE> <INDENT> right_state = af.shift(u_n[0, :], 0, -1) <NEW_LINE> flux = right_state.copy() <NEW_LINE> flux[:, :, 0] = -right_state[:, :, 1] <NEW_LINE> flux[:, :, 1] = -right_state[:, :, 0] <NEW_LINE> return flux | Finds the upwind flux of all the element edges present inside a domain
for Mode :math:`1` of Maxwell's equations.
Please refer to `maxwell_equation_pbc_1d.pdf`_ for the derivation
of the modes.
.. _maxwell_equation_pbc_1d.pdf: `https://goo.gl/8FS4mv`
Parameters
----------
u_n : arrayfire.Array [N_LGL N_Elements M 1]
... | 625941d307f4c71912b1164e |
def _time_string(minutes): <NEW_LINE> <INDENT> minutes = max(minutes, 0) <NEW_LINE> seconds = int(round((minutes % 1) * 60)) <NEW_LINE> hours, minutes = divmod(int(minutes), 60) <NEW_LINE> days, hours = divmod(hours, 24) <NEW_LINE> return f'{days}-{hours:02}:{minutes:02}:{seconds:02}' | Time D-hh:mm:ss format. | 625941d3b830903b967e9ad5 |
def setup(app): <NEW_LINE> <INDENT> app.add_css_file("theme_overrides.css") <NEW_LINE> app.add_css_file("nimare.css") <NEW_LINE> app.connect("autodoc-process-docstring", generate_example_rst) <NEW_LINE> app.add_config_value("no_underscore_emphasis", False, "env") <NEW_LINE> app.add_config_value("m2r_parse_relative_link... | From https://github.com/rtfd/sphinx_rtd_theme/issues/117 | 625941d3e76e3b2f99f3a9d4 |
def __repr__(self): <NEW_LINE> <INDENT> return "<I2c sensor at %s. Current state: %s>" % ( hex(self._i2c_add), self.current_state_str) | String representation of the i2c sensor | 625941d36e29344779a627dc |
def reload(self): <NEW_LINE> <INDENT> return self.service("{0} force-reload".format(self.service_name)) | A method for reload the redis.
:return: None | 625941d3a4f1c619b28b0201 |
def deepReverse(L): <NEW_LINE> <INDENT> if(L == []): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if(isinstance(L[-1], list)): <NEW_LINE> <INDENT> return [deepReverse(L[-1])] + deepReverse(L[:-1]) <NEW_LINE> <DEDENT> return [L[-1]] + deepReverse(L[:-1]) | return the reversed form of a list. Inner lists are also reversed | 625941d37b25080760e39624 |
def create_fill_dict_entry(self, msg): <NEW_LINE> <INDENT> self.fill_dict[msg.orderId] = { "symbol": msg.contract.m_symbol, "exchange": msg.contract.m_exchange, "direction": msg.order.m_action, "filled": False } | Создает пометку в словаре Fill Dictionary, где перечислены orderID. Это нужно для реализации событийно-ориентированного поведения системы обработки сообщений сервера. | 625941d356ac1b37e6264398 |
def msg(self, text=None, from_obj=None, session=None, **kwargs): <NEW_LINE> <INDENT> super(Bot, self).msg(text=text, from_obj=from_obj, session=session, **kwargs) | Evennia -> outgoing protocol | 625941d363d6d428bbe446ba |
def read(self, amt=None, decode_content=None, cache_content=False): <NEW_LINE> <INDENT> content_encoding = self.headers.get('content-encoding', '').lower() <NEW_LINE> if self._decoder is None: <NEW_LINE> <INDENT> if content_encoding in self.CONTENT_DECODERS: <NEW_LINE> <INDENT> self._decoder = _get_decoder(content_enco... | Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
... | 625941d382261d6c526ab66b |
def test_neg_dst_no_write(self): <NEW_LINE> <INDENT> self.generic_ssc_negative_test_case( dst_access=pike.smb2.FILE_READ_DATA | pike.smb2.DELETE, exp_error=pike.ntstatus.STATUS_ACCESS_DENIED, ) | Try to copychunk with no write access on the destination file | 625941d3dc8b845886cb5700 |
def _retrieve(self, row): <NEW_LINE> <INDENT> cuba = self._position_to_cuba <NEW_LINE> mask = row['mask'] <NEW_LINE> data = row['data'] <NEW_LINE> return DataContainer({ cuba[index]: convert_from_file_type(data[index], cuba[index]) for index, valid in enumerate(mask) if valid}) | Return the DataContainer from a table row instance.
| 625941d382261d6c526ab66c |
def __init__(self): <NEW_LINE> <INDENT> self.Filters = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> self.Order = None <NEW_LINE> self.OrderField = None <NEW_LINE> self.ResourceGroupId = None | :param Filters: 筛选选项
:type Filters: list of Filter
:param Offset: 偏移量,默认为0
:type Offset: int
:param Limit: 返回数量,默认为20,最大值为200
:type Limit: int
:param Order: 输出列表的排列顺序。取值范围:ASC:升序排列 DESC:降序排列
:type Order: str
:param OrderField: 排序的依据字段, 取值范围 "CREATE_TIME", "UPDATE_TIME", "NAME"
:type OrderField: str
:param ResourceGroup... | 625941d3ad47b63b2c50a14a |
def test_object_type_instantiation(self): <NEW_LINE> <INDENT> schema = {'prop': {'type': 'int'}} <NEW_LINE> my_type = ontic_type.create_ontic_type('MyType', schema) <NEW_LINE> expected_dict = {'prop': 3} <NEW_LINE> my_object = my_type() <NEW_LINE> my_object.prop = 3 <NEW_LINE> self.assertDictEqual(expected_dict, my_obj... | OnticType instantiation to confirm dict behavior | 625941d3be383301e01b564e |
def l2_norm(trees): <NEW_LINE> <INDENT> vectorize = lambda tree: [edge.length for edge in tree.edges()] <NEW_LINE> clean_none = lambda length: length if length else 0 <NEW_LINE> clean = lambda vect: np.array(list(map(clean_none, vect))) <NEW_LINE> norm = lambda v1, v2: np.linalg.norm(v1 - v2) <NEW_LINE> return norm(*li... | Calculates the normalized l2 norm between two trees. | 625941d331939e2706e4d034 |
def get_user(self, uid, **kwargs): <NEW_LINE> <INDENT> if 'tenant' in kwargs: <NEW_LINE> <INDENT> uid = kwargs['tenant'] + '$' + uid <NEW_LINE> <DEDENT> params = {'uid': uid} <NEW_LINE> _kwargs_get('format', kwargs, params, 'json') <NEW_LINE> _kwargs_get('stats', kwargs, params, False) <NEW_LINE> response = self.make_r... | Get the user information.
:param str uid: the user id
:returns radosgw.user.UserInfo: the user info
:throws radosgw.exception.RadosGWAdminError: if an error occurs
:see: http://ceph.com/docs/next/radosgw/adminops/#get-user-info | 625941d315baa723493c4141 |
def min(self): <NEW_LINE> <INDENT> pos = self.head.next <NEW_LINE> m = pos.val <NEW_LINE> for _ in range(len(self)-1): <NEW_LINE> <INDENT> pos = pos.next <NEW_LINE> if pos.val < m: <NEW_LINE> <INDENT> m = pos.val <NEW_LINE> <DEDENT> <DEDENT> return m | Returns the minimum value in this list. | 625941d30a50d4780f66705e |
def make_delete_request(self, url, payload=None, params=None): <NEW_LINE> <INDENT> if params is not None and params.get('key', False) is False: <NEW_LINE> <INDENT> params['key'] = self.key <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> params = self.default_params <NEW_LINE> <DEDENT> if payload is not None: <NEW_LINE> <... | Make a DELETE request using the provided ``url`` and the optional
arguments.
The ``payload`` must be a dict that can be converted into a JSON
object (via ``json.dumps``)
If the ``params`` are not provided, use ``default_params`` class field.
If params are provided and the provided dict does not have ``key`` key,
the d... | 625941d3be7bc26dc91cd7c9 |
def admin_required(fn): <NEW_LINE> <INDENT> @wraps(fn) <NEW_LINE> def decorated_function(*args, **kwargs): <NEW_LINE> <INDENT> if not current_user.is_admin: <NEW_LINE> <INDENT> abort(403) <NEW_LINE> <DEDENT> return fn(*args, **kwargs) <NEW_LINE> <DEDENT> return decorated_function | Only allow administrators to access the view. | 625941d301c39578d7e75006 |
def find_closest(location, centroids): <NEW_LINE> <INDENT> return min(centroids, key=lambda x: distance(location, x)) | Return the item in CENTROIDS that is closest to LOCATION. If two
centroids are equally close, return the first one.
>>> find_closest([3, 4], [[0, 0], [2, 3], [4, 3], [5, 5]])
[2, 3] | 625941d34c3428357757c4f2 |
def getRgbImage(self): <NEW_LINE> <INDENT> self.rgbImage, _ = freenect.sync_get_video() <NEW_LINE> self.rgbImage = cv2.cvtColor(self.rgbImage, cv2.COLOR_RGB2BGR) <NEW_LINE> return self.rgbImage | Get rgb image from kinect camera
return:
rgbImage: rgb image | 625941d33346ee7daa2b2f38 |
def complementary_arrays(self): <NEW_LINE> <INDENT> portfolio_returns_array = [] <NEW_LINE> market_returns_array = [] <NEW_LINE> for portfolio_date_point in self.portfolio_returns: <NEW_LINE> <INDENT> for market_date_point in self.market_data_returns: <NEW_LINE> <INDENT> if portfolio_date_point['date'] == market_date_p... | :returns: [float,...],[float,...] | 625941d3956e5f7376d71037 |
def getData(self): <NEW_LINE> <INDENT> print("Enter getData") <NEW_LINE> self.hasColor = False <NEW_LINE> sql = str() <NEW_LINE> sender = self.sender() <NEW_LINE> if sender.objectName() == "pushButtonExecute": <NEW_LINE> <INDENT> selectFrom = "SELECT {slct} FROM {frm}_now".format( slct=self.toolwidgetmain.comboBoxField... | Fetches data given SQL query
:return: List of tuples | 625941d3a05bb46b383ec9ec |
def addRadioButton(self, title, name, row=None, column=0, colspan=0, rowspan=0): <NEW_LINE> <INDENT> ident = title + "-" + name <NEW_LINE> self.widgetManager.verify(WIDGET_NAMES.RadioButton, ident) <NEW_LINE> var = None <NEW_LINE> newRb = False <NEW_LINE> if (title in self.widgetManager.group(WIDGET_NAMES.RadioButton, ... | adds a radio button, to thr group 'title' with the text 'name' | 625941d3435de62698dfde18 |
def _set_peak_initial_fwhm(self, fun, fwhm): <NEW_LINE> <INDENT> if not self.getWidthParameterNameOf(fun) or not self.isParameterExplicitlySetOf(fun, self.getWidthParameterNameOf(fun)): <NEW_LINE> <INDENT> self.setPeakFwhmOf(fun, fwhm) | Overwrite fwhm if has not been set already - this is for back to back exponential type funcs
which have had the width parameter (S) as func d-spacing refined for a standard sample (coefs stored in
instrument Paramters.xml) and has already been set.
:param fun: peak function prefix
:param fwhm: estimated fwhm of peak ad... | 625941d37b25080760e39623 |
def _render_interfaces(self, network_state, render_hwaddress=False): <NEW_LINE> <INDENT> lo = { "name": "lo", "type": "physical", "inet": "inet", "subnets": [{"type": "loopback", "control": "auto"}], } <NEW_LINE> for iface in network_state.iter_interfaces(): <NEW_LINE> <INDENT> if iface.get("name") == "lo": <NEW_LINE> ... | Given state, emit etc/network/interfaces content. | 625941d37d847024c06be489 |
def _postNewUser(user_id): <NEW_LINE> <INDENT> data = { "username": user_id, "password": user_id } <NEW_LINE> response = requests.post(config.URL+"Token/create", data = data, verify=False) <NEW_LINE> res=response.json() <NEW_LINE> print(response.text) <NEW_LINE> if (not res["is_exist"]): <NEW_LINE> <INDENT> return res[... | Token if not exist; None if exist | 625941d3498bea3a759b9c7a |
def init(): <NEW_LINE> <INDENT> @click.group(cls=cli.make_commands(__name__)) <NEW_LINE> @click.option('--aliases-path', required=False, envvar='TREADMILL_ALIASES_PATH', help='Colon separated command alias paths') <NEW_LINE> def node_group(aliases_path): <NEW_LINE> <INDENT> if aliases_path: <NEW_LINE> <INDENT> os.envir... | Return top level command handler. | 625941d338b623060ff0afb9 |
def render(self): <NEW_LINE> <INDENT> s = self.scene <NEW_LINE> if s is not None: <NEW_LINE> <INDENT> s.render() <NEW_LINE> <DEDENT> elif self.running: <NEW_LINE> <INDENT> for actor in self.actors: <NEW_LINE> <INDENT> if hasattr(actor, 'mapper'): <NEW_LINE> <INDENT> m = actor.mapper <NEW_LINE> if m is not None: <NEW_LI... | Invokes render on the scene, this in turn invokes Render on
the VTK pipeline. | 625941d36fece00bbac2d90b |
def losses(self, seg_logit, seg_label): <NEW_LINE> <INDENT> seg_logit, se_seg_logit = seg_logit <NEW_LINE> loss = dict() <NEW_LINE> loss.update(super(EncHead, self).losses(seg_logit, seg_label)) <NEW_LINE> se_loss = self.loss_se_decode( se_seg_logit, self._convert_to_onehot_labels(seg_label, self.num_classes)) <NEW_LIN... | Compute segmentation and semantic encoding loss. | 625941d39f2886367277aa58 |
def _setQuantity(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> self._quantity = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> floatValue = float(value) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError("Quantity must be interpretable as a float") <N... | Property target used to set the quantity
The value must be interpretable as a float if it is not None
Raises:
ValueError: If the value is an empty string
ValueError: If the value is not a valid floating point number
ValueError: If the value is less than zero | 625941d3f7d966606f6aa1d1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.