code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def instantiate_class(self): <NEW_LINE> <INDENT> return bases.Instance(self)
return Instance of ClassDef node, else return self
625941cda934411ee37517ab
def get_token(self, token_string): <NEW_LINE> <INDENT> return self.session.query(Token).filter(Token.token == token_string).first()
Gets from database the information about a token from the token string :param token_string: :return: Token object
625941cd30bbd722463cbede
def _downloadJsonFile(self, occupancyLFN, filePath): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filePath, 'wt') as fd: <NEW_LINE> <INDENT> res = requests.get(occupancyLFN) <NEW_LINE> res.raise_for_status() <NEW_LINE> fd.write(res.content) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDEN...
Download the json file at the location using requests :param occupancyLFN: this is actually a full https URL :param filePath: destination path for the file
625941cd73bcbd0ca4b2c18e
def make_tectonic_map(self): <NEW_LINE> <INDENT> self.call_planet_subprocess() <NEW_LINE> self.make_tectonic_arr() <NEW_LINE> height_map_path = os.path.join(self.dir_path, HEIGHT_MAP_NAME) <NEW_LINE> lat_lon_map = GreyLatLonMap( height=1302, width=2048, path=height_map_path) <NEW_LINE> cube_map = GreyCubeMap(height=102...
Creates cube map from lat-lon map :return: None
625941cd56b00c62f0f14771
def BFS(seeds, record): <NEW_LINE> <INDENT> x_way, y_way = [-1, 0, 1, 0], [0, -1, 0, 1] <NEW_LINE> min_x, max_x = seeds[0][0], seeds[0][0] <NEW_LINE> min_y, max_y = seeds[0][1], seeds[0][1] <NEW_LINE> flag = 0 <NEW_LINE> while len(seeds) > 0: <NEW_LINE> <INDENT> currentSeed = seeds.pop(0) <NEW_LINE> for i in range(4): ...
广度优先搜索寻找各数字 使用队列,列表头为队首
625941cd0a366e3fb873e932
def test_is_new_order_file_directory_not_file(): <NEW_LINE> <INDENT> with tempfile.TemporaryDirectory(suffix=".json") as tmp: <NEW_LINE> <INDENT> obj = om.OrderMonitor(tempfile.gettempdir()) <NEW_LINE> assert os.path.isdir(tmp) is True <NEW_LINE> assert obj._is_new_order_file(os.path.basename(tmp)) is False
_is_new_order_file method returns False if file-like is directory
625941cdf7d966606f6aa11c
def test_check_map_var_len_not_specified(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, check_map, self.valid_mapping_data_var_len_bcs)
Raises error if var len bcs detected but not specified
625941cdcdde0d52a9e5314b
def set_is_accepting_photos(self, flag): <NEW_LINE> <INDENT> self.is_accepting_photos = flag
Assign flag to is_accepting_photos.
625941cddc8b845886cb564c
def get_children(self): <NEW_LINE> <INDENT> return self._internal_group
Return a list of the children sprites
625941cd21a7993f00bc7e07
def densenet169(pretrained=False, **kwargs): <NEW_LINE> <INDENT> model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 32, 32), **kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> _load_state_dict(model, model_urls['densenet169']) <NEW_LINE> <DEDENT> return model
Densenet-169 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
625941cd29b78933be1e57c4
def __call__(self, imgs): <NEW_LINE> <INDENT> img = imgs[0] <NEW_LINE> w, h = img.size <NEW_LINE> th, tw = self.size <NEW_LINE> x1 = int(round((w - tw) / 2.)) <NEW_LINE> y1 = int(round((h - th) / 2.)) <NEW_LINE> return tuple([img.crop((x1, y1, x1 + tw, y1 + th)) for img in imgs])
Args: imgs (PIL.Image): images to be cropped. Returns: PIL.Image: Cropped images.
625941cd004d5f362079a44b
def superseded(self): <NEW_LINE> <INDENT> for triple in self.arcsOut: <NEW_LINE> <INDENT> if (triple.target != None and triple.arc.id == "supersededBy"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Has this property been superseded? (i.e. deprecated/archaic)
625941cd4f88993c3716c17f
def bubble_sort(x): <NEW_LINE> <INDENT> blist = [] <NEW_LINE> c = 0 <NEW_LINE> for a in range(len(x)- 1): <NEW_LINE> <INDENT> if x[c] < x[c + 1]: <NEW_LINE> <INDENT> blist.append(x[c]) <NEW_LINE> x.pop(c) <NEW_LINE> <DEDENT> c += 1 <NEW_LINE> <DEDENT> return blist, x
Returns lists of intergers sorted. Args: numbers(numeric). Returns: Number: Returns a sorted list. Examples:
625941cd26068e7796caedf7
def WhiteList(link): <NEW_LINE> <INDENT> valid = False <NEW_LINE> transformed = link <NEW_LINE> if isinstance(transformed, ndb.model._BaseValue): <NEW_LINE> <INDENT> transformed = transformed.b_val <NEW_LINE> <DEDENT> pattern_tripit = ('^(?P<protocol>(http|https|webcal)://|)www.tripit.com/feed/' 'ical/private/[A-Za-z0-...
Determines if a link is on the whitelist and transforms it if needed. Args: link: A url corresponding to a calendar feed Returns: A tuple (valid, transformed) where valid is a boolean which indicates whether the link is on the whitelist and transformed is an (possibly different) equivalent value of li...
625941cd6e29344779a6272a
def clean_doc(doc, stopws): <NEW_LINE> <INDENT> doc = doc.lower() <NEW_LINE> doc = re.sub(r'-', ' ', doc) <NEW_LINE> doc = re.sub(r' +', ' ', doc) <NEW_LINE> doc = re.sub(r'\n', ' ', doc) <NEW_LINE> doc = re.sub(r'[^a-z ]', '', doc) <NEW_LINE> words = [word for word in doc.split() if word not in stopws] <NEW_LINE> stem...
Strip punctuation etc. from a single document
625941cd45492302aab5e3db
def __move_track(self, distance, speed, track, sleep=True): <NEW_LINE> <INDENT> if self._DEBUG: <NEW_LINE> <INDENT> print("DEBUG: Distance -", distance, "speed:", speed, "track:", track) <NEW_LINE> return None <NEW_LINE> <DEDENT> motor = ev3.Motor(track) <NEW_LINE> motor.reset() <NEW_LINE> motor.run_to_abs_pos(position...
Moves the specified track of the robot based on the motor it's hooked to. The motor that controls the left and right tracks were established on init Keyword arguments: distance -- count of tacho units that the motor will be moved speed -- speed that tacho motor will run at track -- left or right motor ...
625941cdb7558d58953c502c
def __exit__(self, *args): <NEW_LINE> <INDENT> self.queries_df.sort_index(inplace=True) <NEW_LINE> self.queries_df.to_csv(self.queries_path)
Save the `queries_df` for later use.
625941cdd164cc6175782e66
def render_column(self, row, column): <NEW_LINE> <INDENT> if column == 'id': <NEW_LINE> <INDENT> if row.hrn_code: <NEW_LINE> <INDENT> return row.hrn_code <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(row.id) <NEW_LINE> <DEDENT> <DEDENT> if column == 'transaction_date': <NEW_LINE> <INDENT> return row.transact...
Overriden method to render a column (a hook on BaseDatatableView)
625941cd3539df3088e2e463
def sha256(self, raw_output=False): <NEW_LINE> <INDENT> res = hashlib.sha256( str(self.generator.random.random()).encode()) <NEW_LINE> if raw_output: <NEW_LINE> <INDENT> return res.digest() <NEW_LINE> <DEDENT> return res.hexdigest()
Generate a random SHA256 hash. If ``raw_output`` is ``False`` (default), a hexadecimal string representation of the SHA56 hash will be returned. If ``True``, a ``bytes`` object representation will be returned instead. :sample: raw_output=False :sample: raw_output=True
625941cd85dfad0860c3af73
def testgetTaskID4(self): <NEW_LINE> <INDENT> self.assertListEqual(sorted(fcts.getTaskID(openfile('commit-msg4'))), ['T135304', 'T98116111'])
2 tasks + blank lines
625941cda4f1c619b28b0151
@cachetools.cached(cache=cachetools.TTLCache(maxsize=999, ttl=300)) <NEW_LINE> def get_existing_arms_data(site_id: str) -> pd.DataFrame: <NEW_LINE> <INDENT> return feedback.enumerate_keys(site_ids=list(site_id), experiments=['default'], recommender_ids=['fmv1', 'collb'])
Query Allocator DB, return all recommender trials per site_id TODO: implement real DB query
625941cde8904600ed9f2045
def __init__(self, options=None): <NEW_LINE> <INDENT> self.set_options(options, default) <NEW_LINE> self._monitor = None
Instantiate the object and set options
625941cd21a7993f00bc7e08
def requirements_file_to_list(fn="requirements.txt"): <NEW_LINE> <INDENT> with open(fn, 'r') as f: <NEW_LINE> <INDENT> return [x.rstrip() for x in list(f) if x and not x.startswith('#')]
read a requirements file and create a list that can be used in setup.
625941cdd18da76e235325ee
def list_entries(): <NEW_LINE> <INDENT> _, filenames = default_storage.listdir("entries") <NEW_LINE> return list(sorted(re.sub(r"\.html$", "", filename) for filename in filenames if filename.endswith(".html")))
Returns a list of all names of encyclopedia entries.
625941cdfb3f5b602dac37ab
def get_query_set(self): <NEW_LINE> <INDENT> return Topic.objects.filter(tribe__private=False)
Used when the entire index for model is updated.
625941cd3cc13d1c6d3c7492
def get_version(self): <NEW_LINE> <INDENT> if self.hash_dict: <NEW_LINE> <INDENT> return str(self.hash_dict["version"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Getter for the version of the hash dictionary. :return str: version if a hash dictionary is present, otherwise None
625941cd4d74a7450ccd42dc
def postorderTraversal3(self, root): <NEW_LINE> <INDENT> white,grey = 0,1 <NEW_LINE> res_list = [] <NEW_LINE> if root is None: return res_list <NEW_LINE> stack = [(white,root)] <NEW_LINE> while stack: <NEW_LINE> <INDENT> color,tree_node = stack.pop() <NEW_LINE> if tree_node is None:continue <NEW_LINE> if color == white...
迭代法,标记颜色 :type root: TreeNode :rtype: List[int]
625941cd711fe17d82542484
def as_scalarunit(meth): <NEW_LINE> <INDENT> @wraps(meth) <NEW_LINE> def wrapped(self, other): <NEW_LINE> <INDENT> result = meth(self, other) <NEW_LINE> if isinstance(other, ScalarUnit) and isinstance(result, Quantity): <NEW_LINE> <INDENT> return ScalarUnit(result._value, result._dimension, result._display_unit) <NEW_L...
Decorate a method to return a :class:`ScalarUnit` if both arguments are :class:`ScalarUnit` instances and the result is not dimensionless.
625941cdcc0a2c11143dcfa9
def move(self): <NEW_LINE> <INDENT> self.pos = Vector(*self.velocity) + self.pos
Change ball position using velocity.
625941cd460517430c39429d
def setOptimizeTarget(self, target): <NEW_LINE> <INDENT> self.optimizeTarget = target
设置优化目标字段
625941cd0a50d4780f666fab
def main(): <NEW_LINE> <INDENT> module = GcpModule( argument_spec=dict( state=dict(default='present', choices=['present', 'absent'], type='str'), default_service=dict(required=True, type='dict'), description=dict(type='str'), host_rules=dict(type='list', elements='dict', options=dict( description=dict(type='str'), host...
Main function
625941cd7c178a314d6ef578
def _search(request_data, objects_list): <NEW_LINE> <INDENT> data = json.loads(request_data) if request_data else {} <NEW_LINE> term = data.get('query') <NEW_LINE> if not term: <NEW_LINE> <INDENT> return json.dumps(objects_list) <NEW_LINE> <DEDENT> term = term.lower() <NEW_LINE> results = [] <NEW_LINE> for event in obj...
Search for the given term in the given objects list, and return matching objects. :param request_data: The request data. :param objects_list: The list of object JSONs to search in. :return: The list of matching objects, or the entire list if no filtering term was given.
625941cdde87d2750b85feab
def load_attribs(self, tree_widget): <NEW_LINE> <INDENT> QtGui.QTreeWidgetItem(tree_widget, ["design shape", str(self.dataset.X.shape)]) <NEW_LINE> QtGui.QTreeWidgetItem(tree_widget, ["topo shape", str(self.topo_shape)]) <NEW_LINE> QtGui.QTreeWidgetItem(tree_widget, ["axes", str(self.dataset.axes)]) <NEW_LINE> QtGui.QT...
Load the attributes from undelying object.
625941cdc4546d3d9de72b4d
def get_outlinks(self, node): <NEW_LINE> <INDENT> if node in self._nodes: <NEW_LINE> <INDENT> connections = [] <NEW_LINE> for edge in self._edges: <NEW_LINE> <INDENT> if edge[0] == node: <NEW_LINE> <INDENT> connections.append(edge[1]) <NEW_LINE> <DEDENT> <DEDENT> return frozenset(connections)
Requires: node is a node in self. Returns a frozenset of the nodes to which node is connected.
625941cd5fc7496912cc3a96
def closest_orthogonal_masks(M, number=1, fast_mode=True, norm_function=lambda x: x*x): <NEW_LINE> <INDENT> arg_max=np.argmax(M,1) <NEW_LINE> n=M.shape[0] <NEW_LINE> m=M.shape[1] <NEW_LINE> best_mask=np.zeros(M.shape) <NEW_LINE> best_mask[range(n),arg_max]=1. <NEW_LINE> if number <= 1: <NEW_LINE> <INDENT> return [best_...
Finds a given number of closest orthogonal matrices and returns their masks.
625941cd3cc13d1c6d3c7493
def integration_1d(): <NEW_LINE> <INDENT> def P0(f): <NEW_LINE> <INDENT> return lambda x0: f(x0) <NEW_LINE> <DEDENT> def P1(f): <NEW_LINE> <INDENT> return lambda x0, x1: integrate(f, x0, x1) <NEW_LINE> <DEDENT> return P0, P1
>>> P0, P1 = integration_1d() >>> P1(lambda x: x)(x0=0, x1=1) 0.5 >>> P1(lambda x: 1)(x0=0, x1=1) 1.0 >>> P1(lambda x: x**2)(x0=0, x1=1) 0.33333333333333337
625941cdad47b63b2c50a098
def query_one_res(chaindata, chainschema, variables): <NEW_LINE> <INDENT> return _query(chaindata, chainschema, variables)
Documentation
625941cd283ffb24f3c55a1a
def test_func(self): <NEW_LINE> <INDENT> photo = self.get_object() <NEW_LINE> return photo.owner.user == self.request.user
Override the userpassestest test_func.
625941cdab23a570cc25029b
def updateCheckpointAttributes(self, modelID, attributes): <NEW_LINE> <INDENT> checkpointDirPath = self._getCurrentCheckpointRealPath(modelID) <NEW_LINE> attributesFilePath = os.path.join(checkpointDirPath, self._CHECKPOINT_ATTRIBUTES_FILE_NAME) <NEW_LINE> (tempFd, tempPath) = tempfile.mkstemp( suffix=self._CHECKPOINT_...
Update model checkpoint attributes :param modelID: unique model ID hex string :param attributes: checkpoint attributes; a JSONifiable object to save as an integral component of the checkpoint. It may later be retrieved separately via ModelCheckpointMgr.loadCheckpointAttributes() :raises: ModelNotFound if the mod...
625941cdd10714528d5ffdfc
def make_lorentzian_model(self, prefix=None): <NEW_LINE> <INDENT> lorentz_model, params = self.make_lorentzianwithoutoffset_model(prefix=prefix) <NEW_LINE> constant_model, params = self.make_constant_model(prefix=prefix) <NEW_LINE> lorentz_offset_model = lorentz_model + constant_model <NEW_LINE> if prefix is None: <NEW...
Create a Lorentz model with amplitude and offset. @param str prefix: optional, if multiple models should be used in a composite way and the parameters of each model should be distinguished from each other to prevent name collisions. @return tuple: (object model, object params), f...
625941cdbd1bec0571d90748
@pytest.fixture(name="buggy_thermostat") <NEW_LINE> def buggy_thermostat_fixture(device_factory): <NEW_LINE> <INDENT> device = device_factory( "Buggy Thermostat", capabilities=[ Capability.temperature_measurement, Capability.thermostat_cooling_setpoint, Capability.thermostat_heating_setpoint, Capability.thermostat_mode...
Fixture returns a buggy thermostat.
625941cd097d151d1a222f72
def test_updating_record_with_dictionary_args(self, test_domain): <NEW_LINE> <INDENT> person = test_domain.repository_for(Person)._dao.create( id="2", first_name="Johnny", last_name="John", age=2 ) <NEW_LINE> test_domain.repository_for(Person)._dao.update(person, {"age": 10}) <NEW_LINE> u_person = test_domain.repositor...
Update an existing entity in the repository
625941cdfff4ab517eb2f555
def dsin(f_degrees): <NEW_LINE> <INDENT> return math.sin(math.radians(f_degrees))
DOCUMENT ME!
625941cda79ad161976cc25e
def get_tickers(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> def done(): <NEW_LINE> <INDENT> yield result <NEW_LINE> <DEDENT> def callback(msg): <NEW_LINE> <INDENT> nonlocal result <NEW_LINE> self.ws.close() <NEW_LINE> print(msg) <NEW_LINE> if msg != None: <NEW_LINE> <INDENT> if msg: <NEW_LINE> <INDENT> if msg['re...
Returns ticker data for all tokens :return: ticker data :rtype: object
625941cd76d4e153a657ec4a
@click.group('volume') <NEW_LINE> def volume(): <NEW_LINE> <INDENT> pass
Volume management commands
625941cd507cdc57c6306df3
def get_world_view(self, step): <NEW_LINE> <INDENT> return { 'objects': self.get_world_objects(), 'agents': self.data.get('agents', {}), 'current_step': self.current_step, 'projection': self.data['projection'], 'assets': self.assets }
returns a list of world objects, and the current step of the calculation
625941cd4527f215b584c56f
def artifacts(token, username, project, build_num): <NEW_LINE> <INDENT> url = "/".join([ "https://circleci.com/api/v1/project", username, project, str(build_num), "artifacts"]) <NEW_LINE> r = requests.get( url, params={'circle-token': token}, headers={'accept': 'application/json'}) <NEW_LINE> return r.json()
Retrieve a list of build artifacts
625941cdaad79263cf390b5a
def cosine_similarity(v1: Vector, v2: Vector) -> float: <NEW_LINE> <INDENT> return dot_product(v1, v2) / (vector_len(v1) * vector_len(v2))
Returns the cosine of the angle between the two vectors. Results range from -1 (very different) to 1 (very similar).
625941cdbde94217f3682f0a
def is_image_file(filename): <NEW_LINE> <INDENT> return has_file_allowed_extension(filename, IMG_EXTENSIONS)
Checks if a file is an allowed image extension. Args: filename (string): path to a file Returns: bool: True if the filename ends with a known image extension
625941cd56b00c62f0f14772
def _create_temp_dir(convert_from_saved_model): <NEW_LINE> <INDENT> if convert_from_saved_model: <NEW_LINE> <INDENT> return tempfile.TemporaryDirectory() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return DummyContextManager()
Creates temp dir, if True is given.
625941cd99fddb7c1c9de4aa
def getAction(self, gameState): <NEW_LINE> <INDENT> result = self.value(gameState, 0, -float("inf"), float("inf")) <NEW_LINE> return result[0] <NEW_LINE> util.raiseNotDefined()
Returns the minimax action using self.depth and self.evaluationFunction
625941cd15fb5d323cde0c29
def testOrigin(self): <NEW_LINE> <INDENT> im = afwImage.ImageF(10, 20) <NEW_LINE> x0 = y0 = 0 <NEW_LINE> self.assertEqual(im.getX0(), x0) <NEW_LINE> self.assertEqual(im.getY0(), y0) <NEW_LINE> self.assertEqual(im.getXY0(), lsst.geom.Point2I(x0, y0)) <NEW_LINE> x0, y0 = 3, 5 <NEW_LINE> im.setXY0(x0, y0) <NEW_LINE> self....
Check that we can set and read the origin
625941cdcb5e8a47e48b7bc3
def __init__(self, fm): <NEW_LINE> <INDENT> self.fm = fm
fm: a FeatureMap parameterizing the kernel. This feature map is expected to take in a Pytorch tensor as the input.
625941cd4f6381625f114b54
def distrib_search(self, msg): <NEW_LINE> <INDENT> self.search.process_search_request(msg.searchterm, msg.user, msg.searchid, direct=False) <NEW_LINE> self.pluginhandler.distrib_search_notification(msg.searchterm, msg.user, msg.searchid)
Distrib code: 3
625941cd1f5feb6acb0c4c69
def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/Utilities/Authentication/OAuth2/FinalizeOAuth')
Create a new instance of the FinalizeOAuth Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied.
625941cd4c3428357757c440
def test_tar_extraction(self, mw_tarball, mw_extract_dir, mw_version): <NEW_LINE> <INDENT> with tarfile.open(mw_tarball) as tar: <NEW_LINE> <INDENT> tar.extractall(mw_extract_dir) <NEW_LINE> <DEDENT> assert os.path.exists( _mw_file(mw_extract_dir, mw_version)), 'Bad tar extraction'
Extract the tarfile
625941cd3346ee7daa2b2e84
def match(self, ra, dec, radius, maxmatch=1, file=None): <NEW_LINE> <INDENT> ra = np.array(ra, dtype="f8", ndmin=1, copy=False) <NEW_LINE> dec = np.array(dec, dtype="f8", ndmin=1, copy=False) <NEW_LINE> radius = np.array(radius, dtype="f8", ndmin=1, copy=False) <NEW_LINE> if ra.size != dec.size: <NEW_LINE> <INDENT> rai...
match to the input set of ra,dec points ra: scalar or array right ascension in degrees to match against dec: scalar or array in degrees to match against declination radius: scalar or array search radius in degrees. Can be a scalar or an array the same size as ra,dec maxmatch: int, optional Maximum...
625941cd67a9b606de4a7fd3
def parsebit(self, pos): <NEW_LINE> <INDENT> alpha = pos.globalpha() <NEW_LINE> self.add(FormulaConstant(alpha)) <NEW_LINE> self.type = 'alpha'
Parse alphabetic text
625941cd57b8e32f524835b4
def __init__(self, vertices, edges): <NEW_LINE> <INDENT> self.nodes = {} <NEW_LINE> for v in vertices: <NEW_LINE> <INDENT> nv = GraphNode(data=v) <NEW_LINE> self.nodes[v] = nv <NEW_LINE> <DEDENT> for e in edges: <NEW_LINE> <INDENT> self.nodes[e[0]].add_adj(e[1], e[2]) <NEW_LINE> self.nodes[e[1]].add_adj(e[0], e[2])
The default c'tor. :param vertices: List of all vertices. For example ['a', 'b', 'c', ...]. :param edges: List of all edges and their scores [ ['a', 'b', 1'], ['a', 'c', 2], ... ]
625941cd63d6d428bbe44608
def parse_config(self,config_path): <NEW_LINE> <INDENT> self.config = configparser.ConfigParser() <NEW_LINE> self.config.read(config_path,encoding="utf-8") <NEW_LINE> self.uerdict_path = self.config.get('DEFAULT', 'uerdict_path') <NEW_LINE> self.stopwords_path = self.config.get('DEFAULT', 'stopwords_path') <NEW_LINE> s...
解析config文件,根据不同的参数,解析情况可能不一致 :return:
625941cd3346ee7daa2b2e85
def _search(self, val): <NEW_LINE> <INDENT> curr = self._root <NEW_LINE> while curr: <NEW_LINE> <INDENT> if val == curr.value: <NEW_LINE> <INDENT> return curr <NEW_LINE> <DEDENT> elif val < curr.value: <NEW_LINE> <INDENT> if curr.left: <NEW_LINE> <INDENT> curr = curr.left <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r...
Search for the node that contains the value.
625941cdd7e4931a7ee9e037
def test_setVersion(self): <NEW_LINE> <INDENT> tempfile = NamedTemporaryFile().name <NEW_LINE> np.random.seed(815) <NEW_LINE> st = Stream([Trace(data=np.random.randn(1000))]) <NEW_LINE> st.write(tempfile, format="SAC") <NEW_LINE> st2 = read(tempfile, format="SAC") <NEW_LINE> os.remove(tempfile) <NEW_LINE> self.assertEq...
Tests if SAC version is set when writing
625941cd851cf427c661a628
def _prepare_annotations(self, annotations, document): <NEW_LINE> <INDENT> for ann in annotations: <NEW_LINE> <INDENT> refined_ann = {} <NEW_LINE> for field in self.source_fields_to_persist: <NEW_LINE> <INDENT> if field in document: <NEW_LINE> <INDENT> refined_field = "%s.%s" % (self.FIELD_META_PREFIX, field) <NEW_LINE...
Returns a generator to create annotation documents -- used for ES bulk indexing
625941cda4f1c619b28b0152
def get_delivery_locations(self): <NEW_LINE> <INDENT> delivery_locations = list() <NEW_LINE> for each_job in self.curr_jobs: <NEW_LINE> <INDENT> delivery_locations.append(each_job[3]) <NEW_LINE> <DEDENT> return delivery_locations
returns the delivery locations of all packages that are currently being carried in a list
625941cd379a373c97cfac5e
def strength(self): <NEW_LINE> <INDENT> age_modifier = self.__AGE_MODIFIER[self.relative_age()] <NEW_LINE> return self._strength - age_modifier
returns the strength :rtype: int
625941cd046cf37aa974ce61
def increasingBST(self, root): <NEW_LINE> <INDENT> dummy=TreeNode(0) <NEW_LINE> self.prev=dummy <NEW_LINE> def inorder(root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> inorder(root.left) <NEW_LINE> root.left=None <NEW_LINE> self.prev.right=root <NEW_LINE> self.prev=self.prev.right ...
:type root: TreeNode :rtype: TreeNode
625941cd435de62698dfdd66
def clear(): <NEW_LINE> <INDENT> print(ESC + FF)
Clears the screen. On a real Tektronix, this flashes the screen white
625941cd293b9510aa2c33b0
def fetch__update_database(): <NEW_LINE> <INDENT> categories_updated = list() <NEW_LINE> categories_inserted = list() <NEW_LINE> events_updated = list() <NEW_LINE> events_inserted = list() <NEW_LINE> for u in create_urls(1, json.load(urllib2.urlopen(create_urls(1, 1)[0]))['totalPages']): <NEW_LINE> <INDENT> for e in js...
Fetch & Update the database. Return : tuple (categoriesUpdated, categoriesInserted, eventsUpdated, eventsInserted)
625941cd9f2886367277a9a6
def test_record_basic(self): <NEW_LINE> <INDENT> def pbool(b): <NEW_LINE> <INDENT> if b: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return 0 <NEW_LINE> <DEDENT> r = Fasta.Record() <NEW_LINE> if sys.version_info[0] == 3: <NEW_LINE> <INDENT> assert pbool(type(r.title) is str) <NEW_LINE> assert pbool(type(r.sequence...
Basic test on Record
625941cde5267d203edcddb6
def __db_set(self, value): <NEW_LINE> <INDENT> string = "Cannot assign directly to db object! " <NEW_LINE> string += "Use db.attr=value instead." <NEW_LINE> raise Exception(string)
Stop accidentally replacing the db object
625941cdbf627c535bc132e8
@pytest.mark.capsule <NEW_LINE> def test_positive_check_hotfix_installed(setup_hotfix_check, ansible_module): <NEW_LINE> <INDENT> contacted = ansible_module.command( Health.check( {"label": "check-hotfix-installed", "whitelist": "check-non-redhat-repository"} ) ) <NEW_LINE> for result in contacted.values(): <NEW_LINE> ...
Verify check-hotfix-installed check. :id: d9023293-4173-4223-bbf5-328b41cf87cd :setup: 1. foreman-maintain should be installed. 2. modify some files of satellite. :steps: 1. Run foreman-maintain health check --label check-hotfix-installed :expectedresults: check-hotfix-installed check should detect mod...
625941cdadb09d7d5db6c8a9
def right(cls): <NEW_LINE> <INDENT> for key,value in Right.__dict__.iteritems(): <NEW_LINE> <INDENT> if not hasattr(cls,key): <NEW_LINE> <INDENT> setattr(cls,key,value) <NEW_LINE> <DEDENT> <DEDENT> return cls
class decorator: inspired by "total ordering" copy the contents of 'Right' into the given class. skip entries that the class already has.
625941cd30bbd722463cbedf
def go_to_movie(url): <NEW_LINE> <INDENT> movie_html = requests.get(url, headers=headers).content <NEW_LINE> return movie_html
Get IMDb page of a movie.
625941cd956e5f7376d70f87
def pad(number, width=0, decimal_places=None): <NEW_LINE> <INDENT> if decimal_places == 0: <NEW_LINE> <INDENT> return futils.native_str(number).partition(".")[0].zfill(width) <NEW_LINE> <DEDENT> if decimal_places is not None: <NEW_LINE> <INDENT> if not isinstance(number, decimal.Decimal): <NEW_LINE> <INDENT> number = d...
Return the zero-padded string of a given number. Args: number (int, float, or decimal.Decimal): the number to pad width (int): width for zero padding the integral component decimal_places (int): number of decimal places to use in frame range Returns: str:
625941cd91f36d47f21ac60c
def estimate_parameters(fluor, p = 2, sn = None, g = None, range_ff = [0.25,0.5], method = 'logmexp', lags = 5, fudge_factor = 1): <NEW_LINE> <INDENT> if sn is None: <NEW_LINE> <INDENT> sn = GetSn(fluor,range_ff,method) <NEW_LINE> <DEDENT> if g is None: <NEW_LINE> <INDENT> g = estimate_time_constant(fluor,p,sn,lags,fud...
Estimate noise standard deviation and AR coefficients if they are not present
625941cd50485f2cf553ceb3
def heappe_user_and_limitation_management_authenticate_user_open_id_post_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = ['body'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.appen...
Provide user authentication via OpenId token. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.heappe_user_and_limitation_management_authenticate_user_open_id_post_with_http_info(async_req=True) >>> result = thread....
625941cde1aae11d1e749dd1
def __init__(self, stage_id, title='mystage'): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.stage_id = stage_id
Initialises userModel class with name.
625941cdb57a9660fec3399d
def Npatron(comando): <NEW_LINE> <INDENT> global gi <NEW_LINE> i= gi + 1 <NEW_LINE> while i <= len(txtArchivo)-1: <NEW_LINE> <INDENT> if patron in txtArchivo[i]: <NEW_LINE> <INDENT> print(str("%3d : " % i) + txtArchivo[i][:-1]) <NEW_LINE> break <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> gi = i
Buscar la primera instancia patrón en el texto Entrada : comando Salida : la siguiente línea que contiene el patrón debidamente enumerada Restricción : Ninguna
625941cdf548e778e58cd697
def intersection(self, rs): <NEW_LINE> <INDENT> new_list = SortedList() <NEW_LINE> for i in self._values: <NEW_LINE> <INDENT> for j in rs._values: <NEW_LINE> <INDENT> if i == j and j not in new_list: <NEW_LINE> <INDENT> new_list.insert(j) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return new_list
------------------------------------------------------- Returns a list that contains only values that appear in both the current List and rs. Use: new_list = sl.intersection(rs) ------------------------------------------------------- Preconditions: rs - another sorted list (SortedList) Postconditions: returns ...
625941cdd268445f265b4f88
def dimension(self, expand=(0, 0, 0, 0)): <NEW_LINE> <INDENT> return expand_range_distinct(self.limits, expand)
The phyical size of the scale, if a position scale Unlike limits, this always returns a numeric vector of length 2
625941cd4e696a04525c9565
def setup_platform(hass, config, add_devices, discovery_info=None): <NEW_LINE> <INDENT> ads_hub = hass.data.get(DATA_ADS) <NEW_LINE> name = config.get(CONF_NAME) <NEW_LINE> ads_var = config.get(CONF_ADS_VAR) <NEW_LINE> add_devices([AdsSwitch(ads_hub, name, ads_var)], True)
Set up switch platform for ADS.
625941cd30bbd722463cbee0
def map_ensembl_ids(ensembl_ids, lookup_dict, tmp_file=None): <NEW_LINE> <INDENT> input_db = 'Ensembl Gene ID' <NEW_LINE> output_db = ['Gene Symbol'] <NEW_LINE> species = 9606 <NEW_LINE> service = BioDBNet() <NEW_LINE> gene_symbols = [] <NEW_LINE> buffer = [] <NEW_LINE> missing = 0 <NEW_LINE> num_run = 200 <NEW_LINE> f...
Map Ensembl identifiers to Gene symbol using BioDBNet :param ensembl_ids: :param lookup_dict: :param tmp_file: :return:
625941cd0383005118ecf6fc
def __init__(self, task=None, msg=None, num_errors=None, num_warnings=None, errors=None, warnings=None): <NEW_LINE> <INDENT> super().__init__(msg) <NEW_LINE> self.task = task <NEW_LINE> if self.task is not None and hasattr(self.task, "report") and self.task.report is not None: <NEW_LINE> <INDENT> report = self.task.rep...
If the task has a report all the information will be extracted from it, otherwise the arguments will be used. Args: task: the abiflows Task msg: the error message num_errors: number of errors in the abinit execution. Only used if task doesn't have a report. num_warnings: number of warning in the abinit...
625941cd73bcbd0ca4b2c190
def pair_score(center, area, obj, weight = (1, 1)): <NEW_LINE> <INDENT> dist = math.sqrt((center[0] - obj.get_last_center()[0]) ** 2 + (center[1]- obj.get_last_center()[1]) ** 2) <NEW_LINE> area_diff = abs(area - obj.get_last_area()) <NEW_LINE> return dist * weight[0] + area_diff * weight[1]
根据距离、面积计算两轮廓匹配程度 center: 待匹配轮廓中心坐标 area: 待匹配轮廓面积 old_contour: 原目标 [num, frame1, x1, y1, area1,img1], [num, frame2, x2, y2, area2, img2] weight: 权 (距离, 面积)
625941cd5f7d997b87174bb2
def get_filaments_where(array, id_name, typ, case): <NEW_LINE> <INDENT> if typ == 'str': <NEW_LINE> <INDENT> filament_names = np.unique(array[id_name]) <NEW_LINE> if case == 0: <NEW_LINE> <INDENT> filament_list = [] <NEW_LINE> for entry in filament_names: <NEW_LINE> <INDENT> indices = np.where(array[id_name] == entry)[...
Calculate the size and members of each filament with numpy
625941cd0fa83653e46570d5
def __init__(self, req_models, name='Simulation', *args, **kwargs): <NEW_LINE> <INDENT> def_opts = {'sens_mode': [str, 'ser', None, None, '', 'Method of sensitivity calculation, can be' ' "ser" for serial "mpi" for mpi and' ' "runjob" for runjob'], 'fd_tol': [float, 1E-21, 0.0, 1.0, '', 'Minimum threshold for sensitivi...
Instantiates the object. Args: req_models(dict): A dictionary in the form {key: type} of the names and types of the mandatory physics models this Experiment uses Options can be set by passing them as keyword arguments
625941cd91f36d47f21ac60d
def equals(self, other): <NEW_LINE> <INDENT> if self is other: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if not isinstance(other, MultiIndex): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.nlevels != other.nlevels: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if len(self) != len(other):...
Determines if two MultiIndex objects have the same labeling information (the levels themselves do not necessarily have to be the same) See also -------- equal_levels
625941cd099cdd3c635f0d74
def test_no_students(self): <NEW_LINE> <INDENT> CourseStudent.objects.all().delete() <NEW_LINE> response = self.client.get(reverse('studentsubmission-list', kwargs={'pk': 1})) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertContains(response, 'No Assignments')
If no students are enrolled in the course, the appropriate message should be displayed
625941cd60cbc95b062c665d
def page(strng, start=0, screen_lines=0, pager_cmd=None): <NEW_LINE> <INDENT> start = max(0, start) <NEW_LINE> ip = ipapi.get() <NEW_LINE> if ip: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ip.hooks.show_in_pager(strng) <NEW_LINE> return <NEW_LINE> <DEDENT> except TryNext: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> ...
Print a string, piping through a pager after a certain length. The screen_lines parameter specifies the number of *usable* lines of your terminal screen (total lines minus lines you need to reserve to show other information). If you set screen_lines to a number <=0, page() will try to auto-determine your screen size ...
625941cd236d856c2ad448f4
def create_board(self, flop=False, next_card=False, all_cards=False): <NEW_LINE> <INDENT> if flop: <NEW_LINE> <INDENT> self.flop = self.deal(3) <NEW_LINE> self.board += self.flop <NEW_LINE> <DEDENT> elif next_card: <NEW_LINE> <INDENT> if self.flop and not self.turn: <NEW_LINE> <INDENT> self.turn = self.deal(1) <NEW_LIN...
Method that deals the flop, turn, and river cards (flop+turn+river = board). Sets the self.board attribute and the self.river, self.turn, and self.flop attributes if set to True. :param flop: Bool :param next_card: Bool :param all_cards: Bool :return: None
625941cd29b78933be1e57c6
def set_arbitrary_waveform_memory_ch1(self): <NEW_LINE> <INDENT> logging.debug(__name__ + ' : Set the device to the arbitrary waveform menu for the channel 1') <NEW_LINE> self._visainstrument.write('source1:function ememory')
Set the device to the arbitrary waveform menu for the channel 1 Input: None Output: None
625941cd4f88993c3716c181
def agrupar_por_aerolinea(datos, filtro=None): <NEW_LINE> <INDENT> dicc_aerol = {} <NEW_LINE> for dato in datos: <NEW_LINE> <INDENT> if filtro==None or dato.carrier_type==filtro: <NEW_LINE> <INDENT> clave = dato.airline <NEW_LINE> if clave in dicc_aerol: <NEW_LINE> <INDENT> dicc_aerol[clave].append(dato) <NEW_LINE> <DE...
Muestra por pantalla el listado de aerolineas que operan, dependiendo si son en territorio nacional (DOMESTIC) o al extranjero (FOREIGN) ENTRADA: - datos: lista de tuplas de tipo DatoTrafico - filtro: variable, según si queremos escoger vuelos nacionales o extranjero. None los muestra todos SALIDA: - Lista ...
625941cd8a43f66fc4b5417f
@task <NEW_LINE> def remote(): <NEW_LINE> <INDENT> require('environment', provided_by=[stage]) <NEW_LINE> if (not exists('%(application_path)s' % env['application']) or confirm('\n%(application_path)s already exists. Do you want to continue?' % env['application'], default=False)): <NEW_LINE> <INDENT> with settings(hide...
Bootstraps deployment remotely
625941cdb7558d58953c502e
def __call__(self, value): <NEW_LINE> <INDENT> return self.reverse[value]
Find key from value using reverse lookup. Args: value (hashable): reverse lookup
625941cdc432627299f04d60
def setup_logdir(self): <NEW_LINE> <INDENT> print("creating logdir") <NEW_LINE> assert self.jobs <NEW_LINE> head_job = self.jobs[0] <NEW_LINE> assert head_job.tasks <NEW_LINE> head_task = head_job.tasks[0] <NEW_LINE> assert head_task.initialized, "Head task not initialized, must wait_until_ready" <NEW_LINE> find_comman...
Create logdir (using first task of first job). This is necessary to be called, and must run after first job/task is ready.
625941cd50812a4eaa59c43c
def get_results(path): <NEW_LINE> <INDENT> k = [] <NEW_LINE> n = [] <NEW_LINE> m = [] <NEW_LINE> outdirs = [os.path.join(path,i) for i in os.listdir(path)] <NEW_LINE> outdirs.sort() <NEW_LINE> cols = [] <NEW_LINE> fmap = {} <NEW_LINE> c=1 <NEW_LINE> for o in outdirs: <NEW_LINE> <INDENT> if not os.path.isdir(o): <NEW_LI...
Fetch results for all dirs and aggregate read counts
625941cd099cdd3c635f0d75
def __init__(self, other = None): <NEW_LINE> <INDENT> if other!=None: <NEW_LINE> <INDENT> self.docs = map(lambda d: Document(d), other.docs) <NEW_LINE> self.sampleCount = other.sampleCount <NEW_LINE> self.wordCount = other.wordCount <NEW_LINE> self.dnrDocInsts = other.dnrDocInsts <NEW_LINE> self.dnrCluInsts = other.dnr...
Basic setup, sets a whole bunch of stuff to sensible parameters, or a copy constructor if provided with another Corpus.
625941cdd486a94d0b98e260
def test_permissions_nonpublic_admin(self): <NEW_LINE> <INDENT> TeamMembership.objects.create( user=self.user, team=self.team, is_admin=True) <NEW_LINE> self.assertEquals(self.image_set.get_perms(self.user), { 'annotate', 'create_export', 'delete_annotation', 'delete_export', 'edit_annotation', 'edit_set', 'read', })
Test if the permissions are correct.
625941cd5166f23b2e1a5273
def get_invoice_number(self): <NEW_LINE> <INDENT> return self.get("InvoiceNumber")
Returns the invoice number.
625941cd31939e2706e4cf84
def interpolTool(self): <NEW_LINE> <INDENT> subw = self.getCurrentSubWindow() <NEW_LINE> if subw is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> pltw = subw.widget() <NEW_LINE> curvinfo = pltw.curvelist[pltw.activcurv] <NEW_LINE> xnam = curvinfo.xvinfo.name <NEW_LINE> blkno = curvinfo.xvinfo.blkpos <NEW_LINE> x...
Launch the interactive Interpolation tool. Work on all the vectors of a data block. :return: nothing
625941cd2c8b7c6e89b358db