code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_create_consistencygroup(self): <NEW_LINE> <INDENT> driver = mock.MagicMock() <NEW_LINE> driver.VERSION = "VERSION" <NEW_LINE> p = self.proxy( self.default_storage_info, mock.MagicMock(), test_mock.cinder.exception, driver) <NEW_LINE> p.ibm_storage_cli = mock.MagicMock() <NEW_LINE> group_obj = self._create_test...
test a successful cg create
625941b87b25080760e392be
def parseLinks(self, linkParams): <NEW_LINE> <INDENT> links = {} <NEW_LINE> for addr1, addr2, p1, p2, c12, c21 in linkParams: <NEW_LINE> <INDENT> link = Link(addr1, addr2, c12, c21, self.latencyMultiplier) <NEW_LINE> links[(addr1,addr2)] = (p1, p2, c12, c21, link) <NEW_LINE> <DEDENT> return links
Parse links from linkParams, dict
625941b8baa26c4b54cb0f87
def update_zone_index(self, direction): <NEW_LINE> <INDENT> if direction == "north": <NEW_LINE> <INDENT> for key, value in self.zone_index.items(): <NEW_LINE> <INDENT> value[0] = value[0] + 1 <NEW_LINE> <DEDENT> <DEDENT> if direction == "west": <NEW_LINE> <INDENT> for key, value in self.zone_index.items(): <NEW_LINE> <...
Updates the `zone_index` when new rows or columns are added to the `zone_array`. Indices are only increased when zones are added to the North (i.e. a new row is added to the 0th index of the array) or to the West (i.e. a new column is added in the 0th index of each row). :param direction: Direction in which...
625941b830c21e258bdfa301
def select_random_move(self): <NEW_LINE> <INDENT> return self._move_function.select_random_move( self.current_neighbourhood)
A method used to generate a random move from the current neighbourhood. Note that this function will only be useable if the neighbourhood given to the constructor is a MultiNeighbourhood. Returns ------- tuple of int A random valid move from the current neighbourhood. Raises ------ WrongMoveTypeError If the ...
625941b863f4b57ef0000f86
def test_stage2_bootstrap_signals(self): <NEW_LINE> <INDENT> soledad.events.signal.reset_mock() <NEW_LINE> sol = self._soledad_instance( secrets_path='alternative.json', local_db_path='alternative.u1db') <NEW_LINE> soledad.events.signal.mock_calls.reverse() <NEW_LINE> soledad.events.signal.call_args = soleda...
Test that a fresh soledad emits all bootstrap signals.
625941b8e5267d203edcdb05
def _create_signals(self): <NEW_LINE> <INDENT> self.exit_item.triggered.connect(self.close)
Привязывает логику к графическим элементом парами "сигнал-слот". @return: -
625941b891af0d3eaac9b878
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> pass
Do nothing here for __init__ will be called every time cls is instanced
625941b8009cb60464c63220
def get_mailinfo(self, box, index): <NEW_LINE> <INDENT> req = self.set_req(MAIL + '/%s/%s' % (box, index)) <NEW_LINE> return self.send_req(req)
:param box: inbox|outbox|deleted :param index: :return:
625941b8090684286d50eb44
def linenum(self): <NEW_LINE> <INDENT> return self.tos().linenum
Return linenum of current tos
625941b8b7558d58953c4d7f
def is_boolean(self): <NEW_LINE> <INDENT> return self.tree._root.get("profileType") == "booleanTerms"
Does the VDEX profile type denote a boolean type vocabulary?
625941b850812a4eaa59c189
def apply_default_labels(self, other): <NEW_LINE> <INDENT> other_updated = other.copy() <NEW_LINE> other_updated.units_label = self.units_label <NEW_LINE> other_updated.name_label = self.name_label <NEW_LINE> other_updated.notes_label = self.notes_label <NEW_LINE> other_updated.desc_label = self.desc_label <NEW_LINE> o...
Applies labels for default meta labels from self onto other. Parameters ---------- other : Meta Meta object to have default labels applied Returns ------- Meta
625941b8d18da76e23532336
def _construct_monthly_climate(self, cl, now, end): <NEW_LINE> <INDENT> if self.simulation: <NEW_LINE> <INDENT> if self.md.duration_unit=='month': <NEW_LINE> <INDENT> months = range(self.timestep_length) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> months = range(12 * self.timestep_length) <NEW_LINE> <DEDENT> <DEDENT>...
Summarizes the monthly climate data into rain, temp and amplitude given the start and end dates cl -- climate dictionary now -- start date end -- end date
625941b8d58c6744b4257ac4
def get_bader_charges(atoms, calc, charge_source="all-electron", gridrefinement=4): <NEW_LINE> <INDENT> if spawn.find_executable("bader") is None: <NEW_LINE> <INDENT> error(( "Cannot find the \"bader\" executable in PATH. The bader " "executable is provided in the pysic/tools folder, or it can be " "downloaded from htt...
This function uses an external Bader charge calculator from http://theory.cm.utexas.edu/henkelman/code/bader/. This tool is provided also in pysic/tools. Before using this function the bader executable directory has to be added to PATH. Parameters: atoms: ASE Atoms The structure from which we want to calcu...
625941b8cc40096d615957b7
def IP_Source7(self): <NEW_LINE> <INDENT> url = ['http://www.xdaili.cn/ipagent/freeip/getFreeIps?page=1&rows=10'] <NEW_LINE> try: <NEW_LINE> <INDENT> res = requests.get(url[0], headers=self.headers) <NEW_LINE> proxies = res.json()['RESULT']['rows'] <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print('s...
IP代理源:讯代理 http://www.xdaili.cn
625941b8a79ad161976cbfa9
def _add_data_to_model(self, qinfos): <NEW_LINE> <INDENT> if self.gps is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> qinfos = [qinfo for qinfo in qinfos if qinfo.val != EVAL_ERROR_CODE] <NEW_LINE> if len(qinfos) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> new_points = [qinfo.point for qinfo in qinfos]...
Add data to self.gp
625941b8187af65679ca4f81
def pltlf_and(self, args): <NEW_LINE> <INDENT> if len(args) == 1: <NEW_LINE> <INDENT> return args[0] <NEW_LINE> <DEDENT> elif (len(args) - 1) % 2 == 0: <NEW_LINE> <INDENT> subformulas = args[::2] <NEW_LINE> return PLTLfAnd(subformulas) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ParsingError
Parse PLTLf And.
625941b8283ffb24f3c55770
def dochdir(thedir): <NEW_LINE> <INDENT> if flag_echo or flag_dryrun: <NEW_LINE> <INDENT> sys.stderr.write("cd " + thedir + "\n") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> os.chdir(thedir) <NEW_LINE> <DEDENT> except OSError as err: <NEW_LINE> <INDENT> u.error("chdir failed: %s" % err)
Switch to dir.
625941b8e1aae11d1e749b18
def setPublisherRef(self, publisherRef): <NEW_LINE> <INDENT> self.logPublisher = publisherRef
Sets the publisher handle so this class can publish log messages :param publisherRef: publisher handle (passed by reference) :type: ZeroMQPublisher()
625941b8adb09d7d5db6c5f7
def deploy_local_data(): <NEW_LINE> <INDENT> require('settings', provided_by=[production, staging]) <NEW_LINE> write_www_files() <NEW_LINE> _gzip_www() <NEW_LINE> local(('s3cmd -P --add-header=Cache-control:max-age=5 --add-header=Content-encoding:gzip --guess-mime-type put gzip/*.json s3://%(s3_bucket)s/') % env) <NEW_...
Deploy the local data files to S3.
625941b8dd821e528d63b00f
def _parse_outer(self): <NEW_LINE> <INDENT> begin = self._consumer.get_pos() <NEW_LINE> end = begin <NEW_LINE> begin_line = self._consumer.get_line() <NEW_LINE> begin_row = self._consumer.get_row() <NEW_LINE> ch = self._consumer.peek() <NEW_LINE> while ch != '\0': <NEW_LINE> <INDENT> if ch == '{': <NEW_LINE> <INDENT> a...
外层解析函数 将输入拆分成字符串(Literal)和表达式(Expression)两个组成。 遇到'{%'开始解析Expression,在解析Expression时允许使用'%%'转义,即'%%'->'%',这使得'%%>'->'%>'而不会结束表达式。 :return: 类型, 内容, 起始行, 起始列
625941b86aa9bd52df036c06
def load_point_rdd(csv_rdd): <NEW_LINE> <INDENT> def load_record(record): <NEW_LINE> <INDENT> result = StringIO.StringIO(record) <NEW_LINE> fieldnames = ['longitude', 'latitude', 'month', 'maximum', 'mean'] <NEW_LINE> reader = csv.DictReader(result, fieldnames) <NEW_LINE> return reader.next() <NEW_LINE> <DEDENT> return...
Return an RDD of Point objects. The rdd argument must be an RDD of CSV records representative of Point objects.
625941b8287bf620b61d38d3
def bfgs(self, f, x0, d0, g0, Q0, epslon, i, alpha): <NEW_LINE> <INDENT> g = Gradient(f, x0) <NEW_LINE> if sum(abs(d0)) < epslon or i is not 0: <NEW_LINE> <INDENT> Q = [self.params['hessian']['initial'] if self.params['hessian']['initial'] else np.identity(len(x0))][0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> q = ...
Broyden-Fletcher-Goldfarb-Shanno ..fun as callable object; must be a function of x0 and return a single number ..x0 as a numeric array; point from which to start
625941b8167d2b6e31218a02
def _crop_pool_layer(bottom, rois, max_pool=True): <NEW_LINE> <INDENT> rois = rois.detach() <NEW_LINE> batch_size = bottom.size(0) <NEW_LINE> D = bottom.size(1) <NEW_LINE> H = bottom.size(2) <NEW_LINE> W = bottom.size(3) <NEW_LINE> roi_per_batch = rois.size(0) / batch_size <NEW_LINE> x1 = rois[:, 1::4] / 16.0 <NEW_LINE...
[ x2-x1 x1 + x2 - W + 1 ] [ ----- 0 --------------- ] [ W - 1 W - 1 ] [ ] [ y2-y1 y1 + y2 - H + 1 ] [ 0 ----- --------------- ] [ H - 1 H - 1 ]
625941b815fb5d323cde096e
def test_deprecated(caplog): <NEW_LINE> <INDENT> schema = vol.Schema({ 'venus': cv.boolean, 'mars': cv.boolean }) <NEW_LINE> deprecated_schema = vol.All( cv.deprecated('mars'), schema ) <NEW_LINE> deprecated_schema({'venus': True}) <NEW_LINE> assert len(caplog.records) == 0 <NEW_LINE> deprecated_schema({'mars': True}) ...
Test deprecation log.
625941b85fc7496912cc37ea
def cnst_c(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Compute constant component :math:`\mathbf{c}` of ADMM problem constraint. This method should not be used or overridden: all calculations should make use of components :meth:`cnst_c0` and :meth:`cnst_c1` so that these methods can return scalar zeros instead of zero arrays if appropriate.
625941b885dfad0860c3acbd
def move(self): <NEW_LINE> <INDENT> location = self.check_grid(int) <NEW_LINE> if location and not self.moved: <NEW_LINE> <INDENT> assert abs(self.x-location[0])<=1 and abs(self.y-location[1])<=1 and abs(self.z-location[2])<=1, "Error in move" <NEW_LINE> self.island.remove(self) <NEW_LINE> self.x = locati...
Move to an open, neighbouring position
625941b8d8ef3951e32433a1
def gen_W(users, items, ratings): <NEW_LINE> <INDENT> user = users.tolist() <NEW_LINE> item = items.tolist() <NEW_LINE> rating = ratings.tolist() <NEW_LINE> B = nx.Graph() <NEW_LINE> B.add_nodes_from(user, bipartite=0) <NEW_LINE> B.add_nodes_from(item, bipartite=1) <NEW_LINE> for i in range(len(user)): <NEW_LINE> <INDE...
This function generates sparse matrix represantation of bipartite graph for players and linups Input: users - pandas series items - pandas series ratings - pandas series Output: sparse biadjacency matrix W
625941b823e79379d52ee3cc
def copy_visibility(vis: Union[Visibility, BlockVisibility], zero=False) -> Union[Visibility, BlockVisibility]: <NEW_LINE> <INDENT> newvis = copy.copy(vis) <NEW_LINE> newvis.data = copy.deepcopy(vis.data) <NEW_LINE> if zero: <NEW_LINE> <INDENT> newvis.data['vis'][...] = 0.0 <NEW_LINE> <DEDENT> return newvis
Copy a visibility Performs a deepcopy of the data array
625941b8507cdc57c6306b38
def submit_button(*args, **kwargs): <NEW_LINE> <INDENT> submit_button = wtforms.SubmitField(*args, **kwargs) <NEW_LINE> submit_button.input_type = 'submit_button' <NEW_LINE> return submit_button
Create a submit button
625941b8cb5e8a47e48b7913
def set_axis(self, axis): <NEW_LINE> <INDENT> assert is_integer(axis), LOGGER.error("rotation symmetry axis must be an integer") <NEW_LINE> axis = INT_TYPE(axis) <NEW_LINE> assert axis>=0, LOGGER.error("rotation symmetry axis must be positive.") <NEW_LINE> assert axis<=2,LOGGER.error("rotation symmetry axis must be sma...
Set the symmetry axis index to rotate about. :Parameters: #. axis (integer): Must be 0,1 or 2 for respectively the main, secondary or tertiary symmetry axis
625941b855399d3f05588518
def mesh_pattern_coordinate(mesh_pattern): <NEW_LINE> <INDENT> coordinate_list = [] <NEW_LINE> for rownum, row in enumerate(mesh_pattern): <NEW_LINE> <INDENT> for colnum, value in enumerate(row): <NEW_LINE> <INDENT> if value == 1: <NEW_LINE> <INDENT> coordinate_list.append((rownum, colnum)) <NEW_LINE> <DEDENT> <DEDENT>...
List all coordinates of prohibited areas in the mesh pattern @param mesh_pattern: 4x4 list showing prohibited areas in pattern @return: coordinates of prohibited areas labelled as 1 >>> mesh_pattern_coordinate([[0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0]]) ... [(0, 2), (2, 2), (3, 2)]
625941b86e29344779a6247a
def Clone(self): <NEW_LINE> <INDENT> pass
Clone(self: VectorKeyFrameCollection) -> VectorKeyFrameCollection Creates a modifiable clone of this System.Windows.Media.Animation.VectorKeyFrameCollection, making deep copies of this object's values. When copying dependency properties,this method copies resource references and data bindings (but they might...
625941b830bbd722463cbc27
@csrf_protect <NEW_LINE> @login_required(login_url='/userprofile/login/') <NEW_LINE> def like(request, comment_id, next=None): <NEW_LINE> <INDENT> comment = get_object_or_404(get_comment_model(), pk=comment_id, site__pk=get_current_site_id(request)) <NEW_LINE> if not has_app_model_option(comment)['allow_feedback']: <NE...
Like a comment. Confirmation on GET, action on POST. Templates: :template:`django_comments_xtd/like.html`, Context: comment the flagged `comments.comment` object
625941b88e71fb1e9831d612
def transform(self, y): <NEW_LINE> <INDENT> check_is_fitted(self) <NEW_LINE> y = column_or_1d(y, warn=True) <NEW_LINE> if _num_samples(y) == 0: <NEW_LINE> <INDENT> return np.array([]) <NEW_LINE> <DEDENT> return _encode(y, uniques=self.classes_)
Transform labels to normalized encoding. Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- y : array-like of shape (n_samples,) Labels as normalized encodings.
625941b8fbf16365ca6f6021
def __init__(self, name, book_value, profits, mu=0.058, brownian_delta=0.00396825396, brownian_sigma=0.125, dividend_rate=1): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.book_value = book_value <NEW_LINE> self.profit = profits[-1] <NEW_LINE> self.dividend_rate = dividend_rate <NEW_LINE> self.profit_history = p...
Creates a new trader
625941b8d10714528d5ffb44
def test_12_update_application(self): <NEW_LINE> <INDENT> self.register() <NEW_LINE> self.new_application() <NEW_LINE> res = self.update_application(method="GET") <NEW_LINE> assert self.html_title("Update the application: Sample App") in res.data, res <NEW_LINE> assert 'input id="id" name="id" type="hidd...
Test WEB update application works
625941b83539df3088e2e1b0
def test_prev_next(self) -> None: <NEW_LINE> <INDENT> sample_to_sample_datas = defaultdict(lambda: []) <NEW_LINE> for sample_data in self.nuim.sample_data: <NEW_LINE> <INDENT> sample_to_sample_datas[sample_data['sample_token']].append(sample_data['token']) <NEW_LINE> <DEDENT> print('Checking prev-next pointers for comp...
Test that the prev and next points in sample_data cover all entries and have the correct ordering.
625941b8d164cc6175782bb2
def load_pretrained_weights(model, file_path='', pretrained_dict=None, extra_prefix=''): <NEW_LINE> <INDENT> def _remove_prefix(key, prefix): <NEW_LINE> <INDENT> prefix = prefix + '.' <NEW_LINE> if key.startswith(prefix): <NEW_LINE> <INDENT> key = key[len(prefix):] <NEW_LINE> <DEDENT> return key <NEW_LINE> <DEDENT> if ...
Loads pretrianed weights to model. Imported from openvinotoolkit/deep-object-reid. Features:: - Incompatible layers (unmatched in name or size) will be ignored. - Can automatically deal with keys containing "module.". Args: model (nn.Module): network model. file_path (str): path to pretrained weights.
625941b8a4f1c619b28afea6
def is_stale(self): <NEW_LINE> <INDENT> return True
With attributes set on self, return a boolean. Calc lat/lng bounds of this tile (include half-dot-width of padding) SELECT count(uid) FROM points WHERE modtime < modtime_tile
625941b845492302aab5e125
def get_city_data(city_id) : <NEW_LINE> <INDENT> def clean_data(data) : <NEW_LINE> <INDENT> keys = {'name', 'display_name', 'statistics'} <NEW_LINE> missing_keys = keys - set(data.keys()) <NEW_LINE> if missing_keys : <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> city_stats = data['statistics']['all'] <NEW_LINE> city_d...
Returns all city data
625941b85510c4643540f25c
def connect_JSON(config): <NEW_LINE> <INDENT> testnet = config.get('testnet', '0') <NEW_LINE> testnet = (int(testnet) > 0) <NEW_LINE> if not 'rpcport' in config: <NEW_LINE> <INDENT> config['rpcport'] = 16990 if testnet else 6990 <NEW_LINE> <DEDENT> connect = "http://%s:%[email protected]:%s"%(config['rpcuser'], config['rpcpa...
Connect to a hotchain JSON-RPC server
625941b8c432627299f04aa9
def getAgentsOfActiveMap(self): <NEW_LINE> <INDENT> return self.getAgentsOfMap(self.active_map.map.getId())
Returns the agents that are on active map @return: A dictionary with the agents of the map
625941b8796e427e537b0427
def write_table(self, anffd, timeq, flags, swid, phases, delays, rates): <NEW_LINE> <INDENT> timeq2 = timeq + " AND (ANTENNA1 = {} OR ANTENNA2 = {})".format(self.ref_antenna, self.ref_antenna) <NEW_LINE> obsid, field, scan = [ffd.distinct_thing(self.msname, timeq2, col) for col in ['OBSERVATION_ID', 'FIELD_ID', 'SCAN_N...
Write out the results in the approved FringeJones table format. We use 'make_table' to handle the details of the table.
625941b8462c4b4f79d1d535
def history(self, hist_type=None, hist_subtype=0, force_time_axis=False, reference_time=None, sync_to_index=None): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> hist_str = None <NEW_LINE> hist_defined = [c for c in dir(Enum) if c.startswith("HIST_")] <NEW_LINE> if hist_type is None: <NEW_LINE> <INDENT> all_hist = ...
Returns the values of any history charting window as a dataframe. Calling the function without arguments returns a dictionary of all available histories :param hist_type: History Type. :type hist_type: str, int, ifm.Enum or None. :param hist_subtype: History Sub-Type (int) :type hist_subtype: i...
625941b89f2886367277a6f6
def _validate(self, rdn, properties, basedn): <NEW_LINE> <INDENT> if properties is None: <NEW_LINE> <INDENT> raise ldap.UNWILLING_TO_PERFORM('Invalid request to create. Properties cannot be None') <NEW_LINE> <DEDENT> if type(properties) != dict: <NEW_LINE> <INDENT> raise ldap.UNWILLING_TO_PERFORM("properties must be a ...
Used to validate a create request. This way, it can be over-ridden without affecting the create types. It also checks that all the values in _must_attribute exist in some form in the dictionary. It has the useful trick of returning the dn, so subtypes can use extra properties to create the dn's here for this.
625941b8d164cc6175782bb3
def test_horovod_allgather(self): <NEW_LINE> <INDENT> hvd.init() <NEW_LINE> rank = hvd.rank() <NEW_LINE> size = hvd.size() <NEW_LINE> dtypes = ['int32', 'int64', 'float32', 'float64'] <NEW_LINE> dims = [1, 2, 3] <NEW_LINE> ctx = self._current_context() <NEW_LINE> for dtype, dim in itertools.product(dtypes, dims): <NE...
Test that the allgather correctly gathers 1D, 2D, 3D tensors.
625941b894891a1f4081b90d
def parse(description): <NEW_LINE> <INDENT> measurements = {'teaspoons', 'tablespoons', 'cup', 'cups', 'pints', 'pint', 'quarts', 'quart', 'ounce', 'ounces', 'dash', 'pinch', 'cube', 'cubes'} <NEW_LINE> printable = set(string.printable) <NEW_LINE> description = filter(lambda x: x in printable, descri...
Parse an ingredient text and insert into measurement/ingredients tables
625941b8435de62698dfdab9
def save_result(df): <NEW_LINE> <INDENT> df.to_csv(("../submit/submit_" + datetime.now().strftime('%Y%m%d_%H%M%S') + ".csv"), header=None, index=False)
导出数据结果 :param data: :return:
625941b89c8ee82313fbb5da
def gauss_seidel_iteration(A, b, tol=1e-9, Max_iter=5000): <NEW_LINE> <INDENT> D = np.diag(np.diag(A)) <NEW_LINE> L = -1 * np.tril(A - D) <NEW_LINE> U = -1 * np.triu(A - D) <NEW_LINE> B = np.linalg.inv(D - L).dot(U) <NEW_LINE> f = np.linalg.inv(D - L).dot(b) <NEW_LINE> x = np.ones_like(b) <NEW_LINE> k = 1 <NEW_LINE> y ...
Solve linear equations by Gauss Seidel iteration method. Args: A: ndarray, coefficients matrix. b: ndarray, constant vector. tol: double, iteration accuracy, default=1e-9. Max_iter: int, maximum iteration number, default=5000. Returns: y: ndarray, solution vector. k: int, iteration number.
625941b8e8904600ed9f1d8e
def number_of_subscribers(subreddit): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = requests.get( url="{}/r/{}/about.json".format(base_url, subreddit), headers={'user-agent': 'APP-NAME by REDDIT-USERNAME'}, ) <NEW_LINE> data = response.json()['data'] <NEW_LINE> return data['subscribers'] <NEW_LINE> <DEDENT> e...
return the number of subscribers
625941b8be7bc26dc91cd46a
def find_shortest_path(graph, start, end, path=[]): <NEW_LINE> <INDENT> path = path + [start] <NEW_LINE> if start == end: <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> if not graph.has_key(start): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> shortest = None <NEW_LINE> for node in graph[start]: <NEW_LINE> <...
Find the shortest path between two nodes of a graph. Works on graphs like this: graph ={'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']}
625941b8d486a94d0b98dfb2
def expm1(*args, **kwargs): <NEW_LINE> <INDENT> pass
Return exp(x)-1. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
625941b80fa83653e4656e22
def post_ui_autopilot_waypoint(self, add_to_beginning, clear_other_waypoints, destination_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.post_ui_autopilot_waypoint_with_http_info(add_to_beginning, clear_other_waypoints, de...
Set Autopilot Waypoint Set a solar system as autopilot waypoint --- This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread...
625941b850485f2cf553cbfe
def assert_equal(first, second): <NEW_LINE> <INDENT> if _test is None: <NEW_LINE> <INDENT> assert first == second <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _test.assertEqual(first, second)
Assert two objects are equal.
625941b824f1403a926009cf
def _find_K(self, I): <NEW_LINE> <INDENT> K = 0 <NEW_LINE> for tuples in it.product(I, repeat=3): <NEW_LINE> <INDENT> K += self.triple[tuples] <NEW_LINE> <DEDENT> return K
We compute: K^I = \sum_{i,j,k \in I} triple[i,j,k] Parameters ---------- I : list list of Kähler indices send to inf triple : np.array[h11, h11, h11] triple intersection numbers Returns ------- int K^I
625941b8b545ff76a8913c84
def __consumerAction(self, idx:int, dist:np.array) -> tuple: <NEW_LINE> <INDENT> _consumer = self.getConsommateur(idx) <NEW_LINE> _1 = _consumer.getDecision() <NEW_LINE> rayon = _consumer.getDecision() <NEW_LINE> _vrai = dist<=rayon <NEW_LINE> _who = dist[_vrai] <NEW_LINE> _2 = np.array(_consumer.preference) <NEW_LINE>...
On détermine le reward On fait l'updateModel @return un vecteur de booléen + choix + récompense
625941b8d18da76e23532337
def get_string(self): <NEW_LINE> <INDENT> return self.string
Return passport string
625941b8097d151d1a222cc1
def distance(self, *arg): <NEW_LINE> <INDENT> (start, end) = normalize_argv(arg, 2) <NEW_LINE> if to_int(start) is None or (to_int(end) is None and not self._is_running()): <NEW_LINE> <INDENT> self._missing_argument() <NEW_LINE> <DEDENT> sp = None <NEW_LINE> if end is None: <NEW_LINE> <INDENT> sp = peda.getreg("sp") <N...
Calculate distance between two addresses Usage: MYNAME address (calculate from current $SP to address) MYNAME address1 address2
625941b863f4b57ef0000f87
def test_search_exit_status_code_when_finds_no_package(): <NEW_LINE> <INDENT> env = reset_env(use_distribute=True) <NEW_LINE> result = run_pip('search', 'non-existant-package', expect_error=True) <NEW_LINE> assert result.returncode == NO_MATCHES_FOUND
Test search exit status code for no matches
625941b8711fe17d825421d8
def test_blockquote(self): <NEW_LINE> <INDENT> text = '> This line should be wrapped in blockquotes\n> ##This is an H2 in a blockquote\nThis is not in blockquotes' <NEW_LINE> self.assertEqual( run_markdown(text), '<blockquote>\n<p>This line should be wrapped in blockquotes</p>\n<h2>This is an H2 in a blockquote</h2>\n<...
Lines preceeded by > should be wrapped in 'blockquote' tags until the first line with no >
625941b8f548e778e58cd3e1
def get_uni_version(self): <NEW_LINE> <INDENT> version, major_version = None, None <NEW_LINE> target_uri = "/%s/system/version" % self.U4V_VERSION <NEW_LINE> response = self.get_request(target_uri, 'version') <NEW_LINE> if response and response.get('version'): <NEW_LINE> <INDENT> version = response['version'] <NEW_LINE...
Get the unisphere version from the server. :return: version and major_version(e.g. ("V8.4.0.16", "84"))
625941b80a50d4780f666cf5
def isDraw(self, board): <NEW_LINE> <INDENT> for i in range(9): <NEW_LINE> <INDENT> if board[i] == '-': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Was the game a draw? Return: True|False
625941b8a219f33f346287da
def get_currently_display_image(self): <NEW_LINE> <INDENT> return self.images[self.current_frame]
Get the image that is currently displaying in this animation.
625941b899fddb7c1c9de1f9
def number_of_lines(filename=""): <NEW_LINE> <INDENT> with open(filename, encoding='utf-8') as f: <NEW_LINE> <INDENT> linenum = 0 <NEW_LINE> for lines in f: <NEW_LINE> <INDENT> linenum += 1 <NEW_LINE> <DEDENT> return linenum
Args: filename (file): The first parameter. Returns: int: number of lines in text file
625941b8e5267d203edcdb07
def copy_designer_template(self): <NEW_LINE> <INDENT> template_files = glob.glob('{}*.sdt'.format( FilePaths().defaultConfigPath() )) <NEW_LINE> templates_path = composer_template_path() <NEW_LINE> for temp_file in template_files: <NEW_LINE> <INDENT> destination_file = os.path.join( templates_path, os.path.basename(tem...
Copies designer templates from the templates folder in the plugin. :return: :rtype:
625941b8046cf37aa974cbb0
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'iais.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.
625941b87047854f462a1273
def flatlandSpaceStations(n, c): <NEW_LINE> <INDENT> c.sort() <NEW_LINE> c = [-c[0]] + c + [2*(n-1)-c[-1]] <NEW_LINE> return int(max(c[i]-c[i-1] for i in range(1, len(c)))/2)
L'astuce à la con : on crée des points virtuels aux deux extrémités comme si il y avait des stations en miroir de celles au bout pour pouvoir résoudre l'exercice en faisant simplement un max sur le tableau
625941b80a366e3fb873e67d
def freq_peak(pop, bandwidth='silverman', max_precision=0.05): <NEW_LINE> <INDENT> if isinstance(bandwidth, (int, float)): <NEW_LINE> <INDENT> bw = bandwidth / np.std(pop, ddof=1) <NEW_LINE> kde = gaussian_kde(pop, bw_method=bw) <NEW_LINE> <DEDENT> elif isinstance(bandwidth, str): <NEW_LINE> <INDENT> kde = gaussian_kde...
Returns the peak of the frequency ("mode") of a continuous distribution based on the Gaussian kernel density estimator. It uses Scipy's gaussian kde method. Parameters ---------- pop : array_like the diameters of the grains bandwidth : string, positive scalar or callable the method to estimate the bandwidth o...
625941b8009cb60464c63222
def interval(self, irc, msg, args): <NEW_LINE> <INDENT> data = self._interval() <NEW_LINE> if data is None or data == '': <NEW_LINE> <INDENT> irc.error("Failed to retrieve data. Try again later.") <NEW_LINE> return <NEW_LINE> <DEDENT> irc.reply(data)
takes no arguments Shows average interval, in seconds, between last 1000 blocks.
625941b897e22403b379cdff
def test_add_offer_invalid_trade_type(new_order_book: Callable[[], OrderBook]) -> NoReturn: <NEW_LINE> <INDENT> book = new_order_book <NEW_LINE> trade_type = 'foo' <NEW_LINE> price = 1 <NEW_LINE> quantity = 1 <NEW_LINE> with pytest.raises(ParamValueException): <NEW_LINE> <INDENT> book.add_offer(trade_type, price, quant...
Add new offer into invalid trade type
625941b8656771135c3eb6d8
def findCelebrity(self, n): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if n == 1: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> self.crowd = set([i for i in range(n)]) <NEW_LINE> while len(self.crowd) > 1: <NEW_LINE> <INDENT> crowd_list = list(self.crowd) <NEW_LINE> if len(crowd...
:type n: int :rtype: int
625941b8236d856c2ad44644
def _exec_sysprep_tasks(self): <NEW_LINE> <INDENT> tasks = self.list_syspreps() <NEW_LINE> enabled = [t for t in tasks if self.sysprep_enabled(t)] <NEW_LINE> size = len(enabled) <NEW_LINE> enabled = [t for t in enabled if self.sysprep_info(t).name != 'shrink'] <NEW_LINE> if len(enabled) != size: <NEW_LINE> <INDENT> ena...
This function hosts the actual code for executing the enabled sysprep tasks. At the end of this method the VM is shut down if needed.
625941b8e1aae11d1e749b1a
def sample(self, points_to_sample, mode="constant", cval=False, **kwargs): <NEW_LINE> <INDENT> return Image.sample(self, points_to_sample, order=0, mode=mode, cval=cval)
Sample this image at the given sub-pixel accurate points. The input PointCloud should have the same number of dimensions as the image e.g. a 2D PointCloud for a 2D multi-channel image. A numpy array will be returned the has the values for every given point across each channel of the image. Parameters ---------- points...
625941b88e05c05ec3eea1d7
def test_get_next_id(): <NEW_LINE> <INDENT> uid = db.get_next_id() <NEW_LINE> assert type(uid) == int <NEW_LINE> item = client.get('til_stats', 'data') <NEW_LINE> item['idCounter'] -= 1 <NEW_LINE> client.put(item.collection, item.key, item.json, item.ref).raise_for_status()
Testing get_next_id
625941b8d10714528d5ffb45
def get_queryset(self): <NEW_LINE> <INDENT> return Question.objects.order_by('-pub_date')[:5]
Return last five published questions.
625941b88a43f66fc4b53ecf
def point(points, colors, opacity=1, point_radius=0.1, theta=8, phi=8): <NEW_LINE> <INDENT> if np.array(colors).ndim == 1: <NEW_LINE> <INDENT> colors = np.tile(colors, (len(points), 1)) <NEW_LINE> <DEDENT> scalars = vtk.vtkUnsignedCharArray() <NEW_LINE> scalars.SetNumberOfComponents(3) <NEW_LINE> pts = vtk.vtkPoints() ...
Visualize points as sphere glyphs Parameters ---------- points : ndarray, shape (N, 3) colors : ndarray (N,3) or tuple (3,) point_radius : float theta : int phi : int Returns ------- vtkActor Examples -------- >>> from dipy.viz import fvtk >>> ren = fvtk.ren() >>> pts = np.random.rand(5, 3) >>> point_actor = fvtk.po...
625941b8a17c0f6771cbdeba
@builder.rule('ElementList', w=1) <NEW_LINE> def _(m): <NEW_LINE> <INDENT> return m.make('AssignmentExpression')
ElementList: AssignmentExpression
625941b86e29344779a6247b
def __init__(self, servant=None, stewards=None, name='', bufsize=8096, wl=None, ha=None, host=u'', port=None, eha=None, scheme=u'', dictable=False, timeout=None, **kwa): <NEW_LINE> <INDENT> self.stewards = stewards if stewards is not None else dict() <NEW_LINE> self.dictable = True if dictable else False <NEW_LINE> if ...
Initialization method for instance. servant = instance of Server or ServerTls or None stewards = dict of Steward instances kwa needed to pass additional parameters to servant if servantinstances are not provided (None) some or all of these parameters will be used for initialization name = user friendly name for serva...
625941b8711fe17d825421d9
def nextLine(length, arr): <NEW_LINE> <INDENT> line = "" <NEW_LINE> prev = 0 <NEW_LINE> while not length == 0: <NEW_LINE> <INDENT> l = randint(0, length) <NEW_LINE> if l == prev: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> prev = l <NEW_LINE> line = line+nextWord(l, arr)+' ' <NEW_LINE> length -= l <NEW_LINE> <DEDE...
возвращает строку с заданным кол-вом слогов length - "длинна" слова в слогах arr - массив возможных слов
625941b824f1403a926009d0
def _get_components(self, *component_types: _Type) -> _Iterable[_Tuple[int, ...]]: <NEW_LINE> <INDENT> entity_db = self._entities <NEW_LINE> comp_db = self._components <NEW_LINE> try: <NEW_LINE> <INDENT> for entity in set.intersection(*[comp_db[ct] for ct in component_types]): <NEW_LINE> <INDENT> yield entity, [entity_...
Get an iterator for Entity and multiple Component sets. :param component_types: Two or more Component types. :return: An iterator for Entity, (Component1, Component2, etc) tuples.
625941b8b5575c28eb68de64
def setUp(self): <NEW_LINE> <INDENT> self.user_name = os.environ['TRAKT_TEST_USER'] <NEW_LINE> self.calendar = UserCalendar(self.user_name)
Create a PremiereCalendar and hold onto it
625941b8167d2b6e31218a04
def input_signature(self): <NEW_LINE> <INDENT> return _digital_swig.digital_diff_decoder_bb_sptr_input_signature(self)
input_signature(self) -> gr_io_signature_sptr
625941b8d53ae8145f87a0dc
def add_binding(self, *keys, **kwargs): <NEW_LINE> <INDENT> filter = kwargs.pop('filter', None) or NoFilter() <NEW_LINE> assert not kwargs <NEW_LINE> assert keys <NEW_LINE> assert isinstance(filter, Filter), 'Expected Filter instance, got %r' % filter <NEW_LINE> def decorator(func): <NEW_LINE> <INDENT> self.key_binding...
Decorator for annotating key bindings.
625941b816aa5153ce3622de
def send(self, message): <NEW_LINE> <INDENT> if message.control and message.topic == 'mail:new': <NEW_LINE> <INDENT> return self.new_mail(message)
:type message: simargl.message.Message :param message: :return:
625941b8851cf427c661a380
def get_pin_status(self): <NEW_LINE> <INDENT> for p in self.pins: <NEW_LINE> <INDENT> if self.hasGPIO: <NEW_LINE> <INDENT> p.update_status(GPIO.input(p.get_num())) <NEW_LINE> <DEDENT> <DEDENT> return self.pins
:return: an array of Pin objects with updated status (updated by reading the GPIO channels)
625941b8d58c6744b4257ac7
def sort_by_posts(d): <NEW_LINE> <INDENT> rslt = [ {'first_name':u['name'].split()[0], 'last_name':u['name'].split()[-1], 'posts':u['posts']} for u in d if u['posts'] > 0 ] <NEW_LINE> rslt.sort(key=operator.itemgetter('posts')) <NEW_LINE> rslt.reverse() <NEW_LINE> return rslt
task2.2 Write a function that returns a list of objects with the following structure: first_name, last_name, posts, ordered by number of posts, removing any users that have not made any posts.
625941b85fdd1c0f98dc0098
def read_from_file(path="", raw=False): <NEW_LINE> <INDENT> if not path: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if not xbmcvfs.exists(path): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with open(path) as f: <NEW_LINE> <INDENT> log("opened textfile %s." % (path)) <NEW_LINE>...
return data from file with *path
625941b8dd821e528d63b012
def set_exp_priority(self, exp_priority): <NEW_LINE> <INDENT> self.set_param('exp_priority', exp_priority)
Exposure priority (0.8 - exposure 80%, gain 20%).XI_PRM_EXP_PRIORITY
625941b855399d3f0558851a
def hash_pandas_object( obj, index: bool = True, encoding: str = "utf8", hash_key: Optional[str] = _default_hash_key, categorize: bool = True, ): <NEW_LINE> <INDENT> from my_happy_pandas import Series <NEW_LINE> if hash_key is None: <NEW_LINE> <INDENT> hash_key = _default_hash_key <NEW_LINE> <DEDENT> if isinstance(obj,...
Return a data hash of the Index/Series/DataFrame. Parameters ---------- index : bool, default True Include the index in the hash (if Series/DataFrame). encoding : str, default 'utf8' Encoding for data & key when strings. hash_key : str, default _default_hash_key Hash_key for string key to encode. categoriz...
625941b8cc40096d615957ba
def set_intercept(self, X_mean, y_mean, X_std): <NEW_LINE> <INDENT> self.coef_ = self.coef_ / X_std <NEW_LINE> self.intercept_ = y_mean - np.einsum('ij,ij->i',X_mean,self.coef_)
Calculate the intercept_
625941b86e29344779a6247c
def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/Google/Drive/Permissions/List')
Create a new instance of the List Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied.
625941b8c432627299f04aaa
def get_app_secret() -> str: <NEW_LINE> <INDENT> app_secret = _reg.get('tumblr.app_secret') or _reg.get('tumblr.app_secret') <NEW_LINE> if not app_secret: <NEW_LINE> <INDENT> raise _error.AppSecretNotSet("Configuration parameter 'tumblr.app_secret' is not set") <NEW_LINE> <DEDENT> return app_secret
Get application's secret key.
625941b8e64d504609d746a7
def _sample_par_sim_pairs(self, n_samples, n_samples_per_param): <NEW_LINE> <INDENT> self.n_samples_per_param = n_samples_per_param <NEW_LINE> self.accepted_parameters_manager.broadcast(self.backend, 1) <NEW_LINE> rng_pds = self._generate_rng_pds(n_samples) <NEW_LINE> parameters_simulations_pds = self.backend.map(self....
Not for end use; please use `sample_par_sim_pairs`. Samples (parameter, simulation) pairs from the prior distribution from the model distribution. Specifically, parameter values are sampled from the prior and used to generate the specified number of simulations per parameter value. This returns arrays. This is an hel...
625941b850485f2cf553cbff
def test_loopBlocks(self): <NEW_LINE> <INDENT> expfile = path.join(self.exp.prefsPaths['tests'], 'data', 'testLoopsBlocks.psyexp') <NEW_LINE> self.exp.loadFromXML(expfile) <NEW_LINE> datafileBase = os.path.join(self.tmp_dir, 'testLoopsBlocks') <NEW_LINE> datafileBaseRel = os.path.relpath(datafileBase,expfile) <NEW_LINE...
An experiment file with made-up params and routines to see whether future versions of experiments will get loaded.
625941b8099cdd3c635f0ac3
def output_stats(self): <NEW_LINE> <INDENT> aux_shape = (1, len(self.ev_mat)) <NEW_LINE> plt.figure(self.bias_fig.number) <NEW_LINE> per = 20000 <NEW_LINE> ev = self.ev_mat.copy() <NEW_LINE> ev = np.reshape(ev, aux_shape)[np.max([0, len(ev)-per]):] <NEW_LINE> perf = self.perf_mat.copy() <NEW_LINE> perf = np.reshape(per...
plot temporary learning and bias curves
625941b863d6d428bbe44356
def get_corners(self, file_path): <NEW_LINE> <INDENT> file_path = file_path.decode('utf-8') <NEW_LINE> filename = str(file_path).split('/')[-1] <NEW_LINE> pts = np.zeros((4, 2)) <NEW_LINE> rows = self.labels[self.labels['filename']==filename] <NEW_LINE> for idx, row in rows.iterrows(): <NEW_LINE> <INDENT> row_c = row['...
get corners by file path
625941b8fff4ab517eb2f2a1
def unbroadcast(out, in_shape): <NEW_LINE> <INDENT> if in_shape == (1,): <NEW_LINE> <INDENT> sum_axis = None <NEW_LINE> return out.sum(axis=sum_axis).reshape(in_shape) <NEW_LINE> <DEDENT> original_in_shape = in_shape <NEW_LINE> if len(in_shape) == 1: <NEW_LINE> <INDENT> n = in_shape[0] <NEW_LINE> index = out.shape[::-1...
Sum the gradients of the output in the case that broadcasting was performed during the calculation of a result. This effectively avoids explicitly splitting a broadcasting operation into several clone modules beforehand.
625941b8b7558d58953c4d82
def requires_auth(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def decorated(*args, **kwargs): <NEW_LINE> <INDENT> token = get_token_auth_header() <NEW_LINE> jsonurl = urlopen(f'https://{AUTH0_DOMAIN}/.well-known/jwks.json') <NEW_LINE> jwks = json.loads(jsonurl.read()) <NEW_LINE> unverified_header = jwt.get_unverified_...
Determines if the Access Token is valid
625941b8627d3e7fe0d68cb5
def test_failUnlessFalse(self): <NEW_LINE> <INDENT> self._assertTrueFalse(self.failUnless)
L{SynchronousTestCase.failUnless} raises L{SynchronousTestCase.failureException} if its argument is not considered true.
625941b88da39b475bd64dde
def quickselect(l, k, less_fn, pivot_fn): <NEW_LINE> <INDENT> if len(l) == 1: <NEW_LINE> <INDENT> assert k == 0 <NEW_LINE> return l[0] <NEW_LINE> <DEDENT> pivot = pivot_fn(l) <NEW_LINE> lows = [ el for el in l if less_fn(el, pivot) ] <NEW_LINE> highs = [ el for el in l if less_fn(pivot, el) ] <NEW_LINE> pivots = [ el f...
Selects the kth minimum in list (0-based) :param l: List of numerics :param k: Index of minimum :param less_fn: Function of x1 and x2 that returns True if x1 < x2 :param pivot_fn: Function to choose a pivot :return: The kth minimum of l
625941b8435de62698dfdabb