code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def calculate_input_size(self, actor_or_critic_scope): <NEW_LINE> <INDENT> dummy_state = [0 for _ in range(self.net_depth+self.binned_data_dist_length)] <NEW_LINE> return len(self.phi(dummy_state))
Calculate input size for MLP (depends on the length of the history) :return:
625941eb5e10d32532c5f40b
def moveZeroes(self, nums): <NEW_LINE> <INDENT> zero_num = 0 <NEW_LINE> no_zero = [] <NEW_LINE> for i in nums: <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> zero_num += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> no_zero.append(i) <NEW_LINE> <DEDENT> <DEDENT> no_zero_num = len(nums)-zero_num <NEW_LINE> for i i...
Do not return anything, modify nums in-place instead.
625941eb379a373c97cfb02d
def get_policy(self, value): <NEW_LINE> <INDENT> return self._get(policy.Policy, value)
Get a single policy :param value: The value can be the ID of a policy or a :class:`~openstack.identity.v3.policy.Policy` instance. :returns: One :class:`~openstack.identity.v3.policy.Policy` :raises: :class:`~openstack.exceptions.ResourceNotFound` when no resource can be found.
625941eb56ac1b37e62646ab
def find_answer(question): <NEW_LINE> <INDENT> links=search(question) <NEW_LINE> results={} <NEW_LINE> for l in links: <NEW_LINE> <INDENT> ans=search_page(get_page(l),question) <NEW_LINE> for a in ans: <NEW_LINE> <INDENT> if a in results: <NEW_LINE> <INDENT> results[a]+=1; <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ...
return the ans argument: question: your question return: the answer
625941eb656771135c3ebd5a
def __init__(self, state_dim, cuda=False): <NEW_LINE> <INDENT> super(SRLBaseClass, self).__init__() <NEW_LINE> self.state_dim = state_dim <NEW_LINE> self.cuda = cuda <NEW_LINE> self.model = None
:param state_dim: (int) :param cuda: (bool)
625941ebc432627299f0512f
def get_heaps(self, ps_ad, peb): <NEW_LINE> <INDENT> num_heaps = peb.NumberOfHeaps.v() <NEW_LINE> heap_count = 0 <NEW_LINE> heaps = obj.Object('Array', offset = peb.ProcessHeaps.v(), vm = ps_ad, targetType = 'unsigned long', count = num_heaps) <NEW_LINE> heaps_list = list(heaps) <NEW_LINE> heaps_list.append(peb.ReadOnl...
Get the heaps and heap related data structures
625941eb9c8ee82313fbbc5d
def createCombobox(self, pos, size, data, key=""): <NEW_LINE> <INDENT> comboBox = QtGui.QComboBox(self) <NEW_LINE> if key == "comp": <NEW_LINE> <INDENT> comboBox.setEditable(True) <NEW_LINE> c = QtGui.QCompleter(data) <NEW_LINE> c.setCaseSensitivity(QtCore.Qt.CaseInsensitive) <NEW_LINE> c.setCompletionMode(QtGui.QCompl...
Wrapper to create a combo box element
625941ebff9c53063f47c6d7
def percentage(x, pos): <NEW_LINE> <INDENT> return '{}%'.format(int(x * 100))
The two args are the value and tick position
625941eb287bf620b61d3f46
def cmdset_slc(self, *args): <NEW_LINE> <INDENT> from .slc import name_slc_command, theNULL <NEW_LINE> self.stream.write('Special Line Characters:\r\n{}'.format( '\r\n'.join(['{:>10}: {}'.format( name_slc_command(slc_func), slc_def) for (slc_func, slc_def) in sorted( self.server.stream.slctab.items()) if not (slc_def.n...
Display special line editing characters.
625941eb01c39578d7e75321
def _get_full_container_list(container_name, **kwargs): <NEW_LINE> <INDENT> limit = 10000 <NEW_LINE> kwargs['limit'] = limit <NEW_LINE> seed = [] <NEW_LINE> _, page = get_conn().get_container(container_name, **kwargs) <NEW_LINE> seed.extend(page) <NEW_LINE> while len(page) == limit: <NEW_LINE> <INDENT> kwargs['marker']...
Return a listing of filenames in container `container_name` :param container_name: :param kwargs: :return:
625941eb1d351010ab856001
def __init__(self, *args): <NEW_LINE> <INDENT> self._ssl_conn = SSL.Connection(*args) <NEW_LINE> self._lock = threading.RLock()
Initialize SSLConnection instance.
625941eb236d856c2ad44cc7
def test_fusiform_similarity_07(self): <NEW_LINE> <INDENT> body = {"min_neighbors": 2, "min_similars": 4} <NEW_LINE> code, res = Algorithm().post_fusiform_similarity(body, auth=auth) <NEW_LINE> id = res["task_id"] <NEW_LINE> if id > 0: <NEW_LINE> <INDENT> result = get_task_res(id, 120, auth=auth) <NEW_LINE> print(resul...
:return:
625941eb3d592f4c4ed1d546
def get_B_chi(vals, mass_range, nbins, A, lamb): <NEW_LINE> <INDENT> bin_heights, bin_edges = np.histogram(vals, range = mass_range, bins = nbins) <NEW_LINE> half_bin_width = 0.5*(bin_edges[1] - bin_edges[0]) <NEW_LINE> ys_expected = get_B_expectation(bin_edges + half_bin_width, A, lamb) <NEW_LINE> chi = 0 <NEW_LINE> f...
Calculates the chi-square value of the no-signal hypothesis (i.e background only) for the passed values. Need an expectation - use the analyic form, using the hard coded scale of the exp. That depends on the binning, so pass in as argument. The mass range must also be set - otherwise, its ignored.
625941eb7d847024c06be7a6
def check_pattern(sequences): <NEW_LINE> <INDENT> result = "D" <NEW_LINE> for pattern in sequences: <NEW_LINE> <INDENT> for player in ("X", "O"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(re.search(re.compile("[{}]+".format(player)), pattern).group(0)) == 3: <NEW_LINE> <INDENT> result = player <NEW_LINE> <DED...
Check if any of the sequences contains three consecutive entries from the same player, which would identify the winner. If there is no winner, return a 'D'. Args: sequences [list(list)]: The sequences to check. Returns: The player who won the game or a 'D' in case of a draw [str].
625941eb76d4e153a657f019
def __call__(self, wrapped): <NEW_LINE> <INDENT> self._wrapped = wrapped <NEW_LINE> return CacheWrapper(self)
Wrap the original function Args: wrapped: The function to be wrapped. Returns: A function wrapping the original function and performing the caching.
625941ebc432627299f05130
def login_helper(test_client, user): <NEW_LINE> <INDENT> response = test_client.post('/v1/auth/login', data=json.dumps(user), content_type='application/json') <NEW_LINE> token_data = dict(Authorization="Bearer " + json.loads(response.data)["Access_token"]) <NEW_LINE> assert response.status_code == 200 <NEW_LINE> return...
Logs in a user passed in as an argument
625941eb15fb5d323cde0ffd
def check_category(self, category, item): <NEW_LINE> <INDENT> stored_category = self.category_dict.get_category(item) <NEW_LINE> if category != stored_category: <NEW_LINE> <INDENT> self.unsane_categories.append((item, category, stored_category))
make list of conflicting categories
625941eb8e7ae83300e4b4b4
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Eligibility): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
625941eb91f36d47f21ac9de
def is_entities_blocking(wiz, closest_snaffle, entities, my_team_id): <NEW_LINE> <INDENT> entity_blocking = False <NEW_LINE> for entity_id, entity in entities.items(): <NEW_LINE> <INDENT> if (entity.entity_type == closest_snaffle.entity_type and entity.entity_id == closest_snaffle.entity_id) or (entity.entity_type == w...
Are the entities, the wizard and the closest_snaffle on the same line?
625941eb0fa83653e465749e
def on_vty(dh, command, ifd, **kwargs): <NEW_LINE> <INDENT> cmd_list = [] <NEW_LINE> if isinstance(command, str): <NEW_LINE> <INDENT> command = command.split(',') <NEW_LINE> <DEDENT> if isinstance(command, list): <NEW_LINE> <INDENT> for cmd in command: <NEW_LINE> <INDENT> if(re.match(r'^\s*\'(.*)\'\s*$',cmd)): <NEW_LIN...
run_shell commands
625941eb566aa707497f4a48
def test_check_dimension2(self): <NEW_LINE> <INDENT> gf3 = griddedfield.GriddedField3() <NEW_LINE> gf3.grids = [np.arange(5), np.arange(5), []] <NEW_LINE> gf3.gridnames = ["A", "B", "C"] <NEW_LINE> with pytest.raises(TypeError): <NEW_LINE> <INDENT> gf3.data = np.ones((5, 5))
Test if grid and data dimension agree (negative).
625941eb85dfad0860c3b342
@app.route('/reservandoF1', methods=['GET', 'POST']) <NEW_LINE> def reservaF1(): <NEW_LINE> <INDENT> global usuarioL,reservaU,i1,cnt <NEW_LINE> entries=[] <NEW_LINE> lista=[] <NEW_LINE> i1=0 <NEW_LINE> while i1<int(cnt[str(usuarioL)]): <NEW_LINE> <INDENT> entries.append(reservaU[str(usuarioL),str(i1)][0]) <NEW_LINE> en...
funcion en la que se relaciona un usuario y la reserva que halla seleccionado
625941eb0383005118ecfac7
def entropy(votes, allocations, divisor_gen): <NEW_LINE> <INDENT> assert(type(votes) == list) <NEW_LINE> assert(all(type(v) == list for v in votes)) <NEW_LINE> assert(type(allocations) == list) <NEW_LINE> assert(all(type(a) == list for a in allocations)) <NEW_LINE> e = 0 <NEW_LINE> for c in range(len(votes)): <NEW_LINE...
Calculate entropy of the election, taking into account votes and allocations. $\sum_i \sum_j \sum_k \log{v_{ij}/d_k}$, more or less.
625941eb7cff6e4e81117e6c
def take_damage(self, damage): <NEW_LINE> <INDENT> list_operators_experience = [i.get_experience / 1000 for i in self.operators] <NEW_LINE> damage -= 0.1 + sum(list_operators_experience) <NEW_LINE> self.set_health(self.get_health - damage * 0.6) <NEW_LINE> random_operator = random.randint(0, len(self.operators) - 1) <N...
The damage of the vehicle. The damage afflicted by a vehicle is calculated: 0.1 + sum(operators.experience / 100) The total damage inflicted on the vehicle is distributed to the operators as follows: 60% of the total damage is inflicted on the vehicle 20% of the total damage is inflicted on a random vehicle operator...
625941ebd4950a0f3b08c82e
def post_test(self): <NEW_LINE> <INDENT> self.report.add('stop_time', time.time())
Called when test is done. Call super if overriden.
625941eb32920d7e50b286bb
def post(self, status): <NEW_LINE> <INDENT> sender = self.request.get('from') <NEW_LINE> im_from = datastore_types.IM('xmpp', bare_jid(sender)) <NEW_LINE> suspend = (status == 'unavailable')
POST handler for XMPP presence. Args: status: A string which will be either available or unavailable and will indicate the status of the user.
625941eb30c21e258bdfa989
def setup_domain_socket(location): <NEW_LINE> <INDENT> clientsocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) <NEW_LINE> clientsocket.settimeout(timeout) <NEW_LINE> clientsocket.connect(location) <NEW_LINE> return clientsocket
Setup Domain Socket Setup a connection to a Unix Domain Socket -- @param location:str The path to the Unix Domain Socket to connect to. @return <class 'socket._socketobject'>
625941eb31939e2706e4d349
def test_02_02_median_bigger(): <NEW_LINE> <INDENT> np.random.seed(0) <NEW_LINE> img = np.random.uniform(size=(20,20)) <NEW_LINE> result = median_filter(img, np.ones((20,20),bool),40) <NEW_LINE> sorted = np.ravel(img) <NEW_LINE> sorted.sort() <NEW_LINE> min_acceptable = sorted[198] <NEW_LINE> max_acceptable = sorted[20...
Use an image of more than 255 values to test approximation
625941ebbde94217f36832d2
def cleanup(self): <NEW_LINE> <INDENT> for client in self.clients.itervalues(): <NEW_LINE> <INDENT> client.queue_thread.join()
Provide an opportunity to join processes and threads.
625941eb1f5feb6acb0c5030
def include(header): <NEW_LINE> <INDENT> gbl.gInterpreter.ProcessLine('#include "%s"' % header)
Load (and JIT) header file <header> into Cling.
625941ebf8510a7c17cf9be6
def getWeights(self): <NEW_LINE> <INDENT> return copy(self._weights)
Returns a copy of weights.
625941ebb7558d58953c53f0
def goToStart(self): <NEW_LINE> <INDENT> self.file_obj.seek(0, 0) <NEW_LINE> self.line_no = 1 <NEW_LINE> self.offset = 0
Move pointer to the start of file. :return:
625941ebf7d966606f6aa4f0
def fizzbuzz(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> first_arg = args[0] <NEW_LINE> second_arg = args[1] <NEW_LINE> output = second_arg <NEW_LINE> if isinstance(output, int): <NEW_LINE> <INDENT> output = funktion(first_arg) <NEW_LINE> <DEDENT> else:...
I'm a decorator
625941ebd8ef3951e3243a24
def record(self, flat_outputs, inference_args, input_tangents): <NEW_LINE> <INDENT> backward_function, to_record = self._backward(flat_outputs) <NEW_LINE> tape.record_operation(self._inference_function.signature.name, to_record, inference_args + input_tangents, backward_function)
Record the function call operation. _DelayedRewriteGradientFunctions supports only first-order backprop tape gradients (and then only when graph building). It does not work with higher-order tape gradients or forward autodiff, but does work with higher-order symbolic gradients (tf.gradients). Args: flat_outputs: Th...
625941eb63b5f9789fde75cc
def get_poetry(input_term, search_term=None, output=None, output_format=None, search_type=None): <NEW_LINE> <INDENT> uri = 'http://poetrydb.org' <NEW_LINE> if search_type is not None and input_term != 'linecount': <NEW_LINE> <INDENT> search_term = search_term + ':abs' <NEW_LINE> <DEDENT> if output_format is not None or...
Primary function for interfacing with the PoetryDB API. Parameters ---------- input_term : {'author', 'title', 'lines', 'linecount'} The desired input term for searching PoetryDB. Must be one of or any combination of 'author', 'title', 'lines', or 'linecount'. search_term : str or None, optional Relates to...
625941eb30bbd722463cc2af
def findObjects(binaryMatrix, color): <NEW_LINE> <INDENT> objectFound = False <NEW_LINE> output = [] <NEW_LINE> binaryMatrix = morphOps(binaryMatrix) <NEW_LINE> contours, hierarchy = cv2.findContours( binaryMatrix, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) <NEW_LINE> cont = sorted(contours, key=cv2.contourArea, reverse=T...
Locate objects of a specific color and return the positions (and color) of the located objects. Parameters ---------- binaryMatrix : val Something color : set of RGB values The color of the object. Returns ------- output : array of arrays Each entry holds an array containing the x, y position and color of...
625941eb97e22403b379d482
def restore(self, restored_tensors, restored_shapes): <NEW_LINE> <INDENT> pass
Restore the same value into both variables.
625941eb8e05c05ec3eea85f
def copy_dir_or_file(src: str, dst: str): <NEW_LINE> <INDENT> if os.path.isfile(src): <NEW_LINE> <INDENT> shutil.copy2(src, dst) <NEW_LINE> <DEDENT> elif os.path.isdir(src): <NEW_LINE> <INDENT> shutil.copytree(src, dst) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise IOError("{} is neither file nor directory. Can't...
Just something from src to dst. If src is a dir it gets copied recursively.
625941eb2ae34c7f2600d617
def rob(self, root): <NEW_LINE> <INDENT> result1, result2 = self.dfs(root) <NEW_LINE> return max([result1, result2])
:type root: TreeNode :rtype: int
625941ebcdde0d52a9e5351e
def combinationSum(self, candidates, target): <NEW_LINE> <INDENT> candidates.sort() <NEW_LINE> res = [] <NEW_LINE> self.dfs(res, candidates,0,target,[]) <NEW_LINE> return res
:type candidates: List[int] :type target: int :rtype: List[List[int]]
625941eb63d6d428bbe449d7
def test_2_ChargeSimpleAndComplex_Exchange_part(self): <NEW_LINE> <INDENT> logging.debug("test_2_ChargeSimpleAndComplex_Exchange_part") <NEW_LINE> if globals()['shopping_order_id'] is not None: <NEW_LINE> <INDENT> exchange_order_id = globals()['shopping_order_id'] + "_0" <NEW_LINE> recharge_param = { 'sub_order_id': ex...
组合商品与普通商品余额方式门店混合 普通商品腰背夹’:M216C237C0458 2件换货58换64 :return:
625941eb29b78933be1e5b8c
def mjd_to_datetime(mjd): <NEW_LINE> <INDENT> return jd_to_datetime( mjd_to_jd( mjd ) )
convert mjd to datetime
625941eb293b9510aa2c3777
def removedirs(name): <NEW_LINE> <INDENT> if listdir(name): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> os.rmdir(name) <NEW_LINE> head, tail = os.path.split(name) <NEW_LINE> if not tail: <NEW_LINE> <INDENT> head, tail = os.path.split(head) <NEW_LINE> <DEDENT> while head and tail: <NEW_LINE> <INDENT> try: <NEW_LINE> ...
special version of os.removedirs that does not remove symlinked directories or junction points if they actually contain files
625941ebbde94217f36832d3
def __iter__(self): <NEW_LINE> <INDENT> _dict = self._dict <NEW_LINE> return iter((key, _dict[key]) for key in self._list)
Return an iterable over the items in the dictionary. Items are iterated over in their sorted order. Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.
625941eb5fdd1c0f98dc071c
def reload_rovers(self): <NEW_LINE> <INDENT> self.set_new_grid() <NEW_LINE> x_grid_coord = self.grid_x_dimension <NEW_LINE> y_grid_coord = self.grid_y_dimension <NEW_LINE> num_of_rovers = self.spinNumOfRovers.value() <NEW_LINE> for x in range(num_of_rovers): <NEW_LINE> <INDENT> rover_coords = self.rover_coords["rover" ...
Reload rovers list after user input
625941eb66656f66f7cbc693
def detach( self, intf ): <NEW_LINE> <INDENT> self.cmd( 'ivs-ctl', 'del-port', '--datapath', self.name, intf )
Disconnect a data port
625941eb283ffb24f3c55de3
def install_step(self): <NEW_LINE> <INDENT> src_gctf_bin = os.path.join(self.builddir, 'bin', self.gctf_bin) <NEW_LINE> if not os.path.exists(src_gctf_bin): <NEW_LINE> <INDENT> raise EasyBuildError("Specified CUDA version has no corresponding Gctf binary") <NEW_LINE> <DEDENT> bindir = os.path.join(self.installdir, 'bin...
Install binary and a wrapper that loads correct CUDA version.
625941eb796e427e537b0ab1
def __init__(self, project_name, dataset_format="csv"): <NEW_LINE> <INDENT> check_dataset_format(dataset_format) <NEW_LINE> self.dataset_format = dataset_format.lower() <NEW_LINE> self.project_name = project_name
:param str project_name: Project Name :param str dataset_format: Specify format of the Datasets (either `csv` or `xml`)
625941eb4527f215b584c938
def print_load_save(): <NEW_LINE> <INDENT> global load_ok <NEW_LINE> global save_ok <NEW_LINE> global time_save <NEW_LINE> global time_load <NEW_LINE> screen = pentagoGUI.get_screen() <NEW_LINE> fixedtext = pentagoGUI.get_fixedtext() <NEW_LINE> screen.blit(fixedtext[2][0], fixedtext[2][1]) <NEW_LINE> screen.blit(fixedt...
Affiche les boutons "Sauvegarder" et "Quitter".
625941eb91af0d3eaac9bf04
def tokenize_list_of_sentences(self, sentence_list, char_level=False): <NEW_LINE> <INDENT> return [self.tokenize_sentence(sentence, char_level=char_level) for sentence in sentence_list]
Splits and converts a list of sequences to a list numerical indices Accepts: sentence_list: List of sentences to be converted char_level: (bool) Whether to tokenize at char level Returns: A list of list of numerical indices
625941ebfbf16365ca6f66b5
def run(principal: str, keytab: str): <NEW_LINE> <INDENT> if not keytab: <NEW_LINE> <INDENT> log.debug("Keytab renewer not starting, no keytab configured") <NEW_LINE> sys.exit(0) <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> renew_from_kt(principal, keytab) <NEW_LINE> time.sleep(conf.getint('kerberos', 'reinit_fr...
Run the kerbros renewer. :param principal: principal name :param keytab: keytab file :return: None
625941ebf7d966606f6aa4f1
def check_class(obj, target_class, allow_none = False): <NEW_LINE> <INDENT> if not isinstance(obj, target_class): <NEW_LINE> <INDENT> if not (allow_none and obj is None): <NEW_LINE> <INDENT> raise TypeError("obj must be a of type {}, got: {}" .format(target_class, type(obj)))
Checks that the obj is a (sub)type of target_class. Raises a TypeError if this is not the case.
625941ebf548e778e58cda67
def add_logged_in_cookie_session( self, protocol: str, host: str, email: str, password: str ) -> None: <NEW_LINE> <INDENT> data = {"email": email, "password": password} <NEW_LINE> url = f"{protocol}://{host}/index.php?route=account/login" <NEW_LINE> request = Request(method="POST", url=url, data=data) <NEW_LINE> sessio...
Add logged in cookie session.
625941eba8370b7717052d84
def print_topic_terms(self, vectorizer, topn_words=10, importances=True): <NEW_LINE> <INDENT> idx_to_word = np.array(vectorizer.get_feature_names()) <NEW_LINE> if importances: <NEW_LINE> <INDENT> _print_topic_terms_with_importances_from_matrices( self.x_weights, self.y_weights, idx_to_word, topn_words=topn_words) <NEW_...
For interpreting the results when using CMF for labeled topic modeling. Prints out the topics acquired along with the words included. Parameters ---------- vectorizer : {sklearn.VectorizerMixin} The vectorizer that maps words to tfidf/count vectors. CMF currently expects the input to be preprocessed using Coun...
625941eb596a897236089fa0
def encode_dict(obj): <NEW_LINE> <INDENT> def replace_key(key): <NEW_LINE> <INDENT> if isinstance(key,six.string_types): <NEW_LINE> <INDENT> return key.replace(".", self.DOT_MAGIC_VALUE) <NEW_LINE> <DEDENT> return key <NEW_LINE> <DEDENT> return dict([(replace_key(key),value) for key, value in obj.items()])
Encodes a dictionary by replacing dots in the keys with a MAGIC value.
625941eb96565a6dacc8fbb0
def train_logreg_model(X, y): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> logger.info("Building Logistic Regression Model...") <NEW_LINE> logreg = lm.LogisticRegression() <NEW_LINE> logreg.fit(X, y) <NEW_LINE> return logreg
Trains a Logistic Regression Model
625941eba219f33f34628e49
def MakePointBuffer(self, *args, **kwargs): <NEW_LINE> <INDENT> pass
Creates a point buffer
625941eb16aa5153ce36295f
def insert(self, root, i): <NEW_LINE> <INDENT> interval = Interval(i[0], i[1]) <NEW_LINE> if root is None: <NEW_LINE> <INDENT> if len(i) > 2: <NEW_LINE> <INDENT> y_interval = Interval(i[2], i[3]) <NEW_LINE> return Node(interval, y_interval) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return YNode(interval) <NEW_LINE>...
inserts interval to the tree; Usage: test_tree = intervalTree() test_tree.root = test_tree.insert(test_tree.root, [4, 7, 3, 3]) :param root: root of the tree :param i: interval to be inserted to the tree; a list of 4 integers, [x_low,x_high, y_low, y_high] :return: updated tree
625941eb94891a1f4081bf92
def rehighlight(self): <NEW_LINE> <INDENT> if self.highlighter is not None: <NEW_LINE> <INDENT> self.highlighter.rehighlight()
Rehighlight the whole document to rebuild class browser data and import statements data from scratch
625941ebfbf16365ca6f66b6
def _decompile_suffix(main_dom, node, options): <NEW_LINE> <INDENT> sfx = node.get_suffix_number().simplify() <NEW_LINE> if sfx != _math_cst.ONE: <NEW_LINE> <INDENT> sfx_dom = _decompile_operand(sfx, False, options) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sfx_dom = None <NEW_LINE> <DEDENT> if sfx_dom is None: <NE...
Decompile suffix part of specified node. :type node: _ml_ast_base._ASTNodeWithSuffix :type options: _opt.Option :param main_dom: The main DOM node. :param node: The AST node. :param options: The BCE options. :return: The decompiled DOM node.
625941eb94891a1f4081bf93
def flush(self): <NEW_LINE> <INDENT> buf = bytearray() <NEW_LINE> for i in self._write_queue: <NEW_LINE> <INDENT> buf += i <NEW_LINE> <DEDENT> self._write_queue.clear() <NEW_LINE> if buf: <NEW_LINE> <INDENT> self.socket.sendall(buf)
Send all buffered data
625941eb26238365f5f0f35c
def __init__(self, hidden_dims, input_dim=3*32*32, num_classes=10, dropout=0, use_batchnorm=False, reg=0.0, weight_scale=1e-2, dtype=np.float32, seed=None): <NEW_LINE> <INDENT> self.use_batchnorm = use_batchnorm <NEW_LINE> self.use_dropout = dropout > 0 <NEW_LINE> self.reg = reg <NEW_LINE> self.num_layers = 1 + len(hid...
Initialize a new FullyConnectedNet. Inputs: - hidden_dims: A list of integers giving the size of each hidden layer. - input_dim: An integer giving the size of the input. - num_classes: An integer giving the number of classes to classify. - dropout: Scalar between 0 and 1 giving dropout strength. If dropout=0 then th...
625941eb4a966d76dd5514fb
def set_stages(w: wd.World): <NEW_LINE> <INDENT> return w
Set stages.
625941eb5166f23b2e1a5640
def get_stream_by_path(self, path_names, start="y", end="t", calculation="calculated", interval="1h", sumType="All", label=None, WebID_dic=None ): <NEW_LINE> <INDENT> if isinstance(path_names, list): <NEW_LINE> <INDENT> streams_df = pd.DataFrame() <NEW_LINE> for path_name in path_names: <NEW_LINE> <INDENT> Web_ID = sel...
This method gets the stream given a the the path. Since the path is the key of the database the call to the API does not use the dataserver as before (points names are are unique only on a dataserver) -> the url composed is a bit different It calls get_webID_by_path to get a single Web ID by path Then it calls the...
625941eba4f1c619b28b0514
def create_test_data(container_name): <NEW_LINE> <INDENT> _command_executer( ['docker', 'exec', container_name, 'python', '/src/client.py', '-l', 'INFO', '--username', 'test-user', '-url', 'http://web:8000', 'create-test-labs'] )
Runs create test labs command. Used for test suite setup :param container_name:
625941eb7047854f462a18eb
def dispatch_url(urlmap, url, request): <NEW_LINE> <INDENT> for p in urlmap.keys(): <NEW_LINE> <INDENT> foo_url = re.sub(p, "", url) <NEW_LINE> if url != foo_url: <NEW_LINE> <INDENT> obj = urlmap[p] <NEW_LINE> url = foo_url <NEW_LINE> return obj().root(request, url) <NEW_LINE> <DEDENT> <DEDENT> raise Http404
转发 url地址,若没有对应的地址配置,生成Http 404错误
625941ebcad5886f8bd274bf
def get_queryset_for_role(self, role): <NEW_LINE> <INDENT> raise NotImplementedError()
Get a queryset with all objects of :obj:`~.View.model` that the current role can access.
625941eb8c3a8732951588a8
def test_query_button_name(self): <NEW_LINE> <INDENT> button_name = '注销' <NEW_LINE> button_code = '' <NEW_LINE> button_page = ButtonPage(self.dr) <NEW_LINE> button_page.query_information(button_name, button_code) <NEW_LINE> self.assertIn(button_name, button_page.return_result) <NEW_LINE> insert_img(self.dr, "根据按钮名称查询.j...
根据正确的按钮名称查询
625941eb23e79379d52eea44
def test_delete_queues_tile_ingest(self): <NEW_LINE> <INDENT> status = 'complete' <NEW_LINE> db_host = 'bar' <NEW_LINE> job_id = 300 <NEW_LINE> job = { 'collection': 90, 'experiment': 141, 'channel': 985, 'task_id': job_id, 'resolution': 0, 'ingest_type': TILE_INGEST } <NEW_LINE> fake_upload_q = self.make_mock('activit...
Should only delete 4 different queues for tile ingests.
625941eb7d43ff24873a318b
def create_dummy_layer(self, dep_loop_exception): <NEW_LINE> <INDENT> print( ("ReuseParams: layer %r does not exist yet and there is a dependency loop, " + "thus creating it on dummy inputs now") % self.layer_name, file=log.v4) <NEW_LINE> def opt_get_layer(layer_name): <NEW_LINE> <INDENT> if layer_name in self.network....
:param TFNetwork.NetworkConstructionDependencyLoopException dep_loop_exception: :rtype: LayerBase
625941eb99cbb53fe67930cc
def run_wsgi(self, req): <NEW_LINE> <INDENT> cmd = req.form.get('cmd', [''])[0] <NEW_LINE> if not mercurial.hgweb.protocol.iscmd(cmd): <NEW_LINE> <INDENT> req.respond( mercurial.hgweb.common.ErrorResponse( mercurial.hgweb.common.HTTP_BAD_REQUEST), mercurial.hgweb.protocol.HGTYPE ) <NEW_LINE> return [''] <NEW_LINE> <DED...
Check the request has a valid command, failing fast otherwise.
625941eb29b78933be1e5b8d
def __init__(self, series=None, openstack=None): <NEW_LINE> <INDENT> self.openstack = None <NEW_LINE> super(OpenStackAmuletDeployment, self).__init__(series) <NEW_LINE> if openstack: <NEW_LINE> <INDENT> self.openstack = openstack
Initialize the deployment environment.
625941eb099cdd3c635f1140
def _col_names(): <NEW_LINE> <INDENT> return ["duration","protocol_type","service","flag","src_bytes", "dst_bytes","land","wrong_fragment","urgent","hot","num_failed_logins", "logged_in","num_compromised","root_shell","su_attempted","num_root", "num_file_creations","num_shells","num_access_files","num_outbound_cmds", "...
Column names of the dataframe
625941eb711fe17d82542847
def __init__(self): <NEW_LINE> <INDENT> self.cache = [] <NEW_LINE> self.queue = []
Initialize your data structure here.
625941ebd6c5a10208144536
def render(self, mode='human'): <NEW_LINE> <INDENT> outfile = StringIO() if mode == 'ansi' else sys.stdout <NEW_LINE> snapshot = "" <NEW_LINE> out = self.desc.copy().tolist() <NEW_LINE> out = [[c.decode('utf-8') for c in line] for line in out] <NEW_LINE> for position in self.position_to_coordinates: <NEW_LINE> <INDENT>...
Visualization in conjunction with create_visual_grid
625941eb7b180e01f3dc4cda
def moveZeroes(self, nums: List[int]) -> None: <NEW_LINE> <INDENT> i2 = 0 <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> if nums[i] != 0: <NEW_LINE> <INDENT> nums[i2], nums[i] = nums[i], nums[i2] <NEW_LINE> i2 += 1
Do not return anything, modify nums in-place instead.
625941eb4e696a04525c9935
def last(mention): <NEW_LINE> <INDENT> return "last", mention.attributes["tokens"][-1].lower()
Compute the last token of a mention. Args: mention (Mention): A mention. Returns: The tuple ('last', TOKEN), where TOKEN is the (lowercased) last token of the mention.
625941eb442bda511e8be8f8
def psa_want_symbol(name: str) -> str: <NEW_LINE> <INDENT> if name.startswith('PSA_'): <NEW_LINE> <INDENT> return name[:4] + 'WANT_' + name[4:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Unable to determine the PSA_WANT_ symbol for ' + name)
Return the PSA_WANT_xxx symbol associated with a PSA crypto feature.
625941eb63f4b57ef00015f2
def users_notes(self, userId, includeReplies=True, limit=10, sinceId=None, untilId=None, sinceDate=None, untilDate=None, includeMyRenotes=True, includeRenotedMyNotes=True, includeLocalRenotes=True, withFiles=False, fileType=None, excludeNsfw=False): <NEW_LINE> <INDENT> payload = { 'userId': userId, 'includeReplies': in...
Show timeline from specified user. :param limit: Maximum number to get. You can specify from 1 to 100. :param sinceId: Acquired from the specified ID. :param untilId: Get up to the specified ID. :param sinceDate: Get from the specified date. :param untilDate: Gets until the specified date. :param includeMyRenotes: Spe...
625941eb8c0ade5d55d3eea6
def __eq__(self, other: 'UpdatedLabelsOut') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Return `true` when self and other are equal, false otherwise.
625941eb63d6d428bbe449d8
def __init__(self, sourceFile, delimiter=','): <NEW_LINE> <INDENT> self._csvFile= panda.read_csv(sourceFile, sep=delimiter, nrows=1000)
Constructor _sourceFile: .csv file path _delimiter: delimiter of fields
625941eb91af0d3eaac9bf05
def response(question_id: str, document: dict) -> Any: <NEW_LINE> <INDENT> responses = [ response for response in document["responses"] if response["question"]["token"] == question_id ] <NEW_LINE> if not responses: <NEW_LINE> <INDENT> raise NoSuchQuestionError(f"No question with id/token '{question_id}' in document {do...
Response value for *question_id* in the enrollment *document*. Returns a string, number, tuple of strings, or None. Raises a :class:`NoSuchQuestionError` if *question_id* is not found in the responses contained by *document*. Raises a :class:`TooManyResponsesError` if the *question_id* is not unique among responses ...
625941eb851cf427c661a9f2
@task <NEW_LINE> def delete_env(env_key): <NEW_LINE> <INDENT> if env_key: <NEW_LINE> <INDENT> _local(_env.dokku_command + " config:unset %s %s " % (_env.app_name_dokku, env_key))
Unset a specific environment variable on dokku
625941eb4f88993c3716c54a
def TranslateRetryParameters(retry): <NEW_LINE> <INDENT> params = taskqueue_service_pb2.TaskQueueRetryParameters() <NEW_LINE> if retry.task_retry_limit is not None: <NEW_LINE> <INDENT> params.retry_limit = int(retry.task_retry_limit) <NEW_LINE> <DEDENT> if retry.task_age_limit is not None: <NEW_LINE> <INDENT> params.ag...
Populates a `TaskQueueRetryParameters` from a `queueinfo.RetryParameters`. Args: retry: A `queueinfo.RetryParameters` that is read from `queue.yaml` that describes the queue's retry parameters. Returns: A `taskqueue_service_pb2.TaskQueueRetryParameters` proto populated with the data from `retry`. Raises:...
625941ebac7a0e7691ed45aa
def _call_return_index(func, index, *args, **kwargs): <NEW_LINE> <INDENT> return func(*args, **kwargs)[index]
Return index of func called with *args and **kwargs. Use with functools.partial to wrap func.
625941eb7b25080760e3993d
def p_nonEqual2(p): <NEW_LINE> <INDENT> logger(p, 'Rule36.2: equal -> >')
equal: GT
625941ebbe8e80087fb21123
def send_command(self, *args, **kwargs): <NEW_LINE> <INDENT> self._ceph_send_command(*args, **kwargs)
Called by the plugin to send a command to the mon cluster.
625941eb7b25080760e3993e
def __get__(self, instance, owner): <NEW_LINE> <INDENT> if instance._location is None: <NEW_LINE> <INDENT> raise AttributeError('Cannot find URL of %s relative to URL-less %s' % (self.cls.__name__, owner.__name__)) <NEW_LINE> <DEDENT> newurl = urlparse.urljoin(instance._location, self.api_name) <NEW_LINE> return self.c...
Generates the RemoteObject for the target resource of this Link. By default, target resources are at a URL relative to the "parent" object's URL, named by the `api_name` attribute of the `Link` instance. Override this method to define some other strategy for building links for your target API.
625941eb5510c4643540f8bf
def MDS(mat, n=2): <NEW_LINE> <INDENT> h = np.eye(len(mat)) - np.ones(mat.shape) / len(mat) <NEW_LINE> k = -0.5 * h.dot(mat * mat).dot(h) <NEW_LINE> if np.any(np.isnan(k)): <NEW_LINE> <INDENT> k[np.isnan(k)] = 0 <NEW_LINE> <DEDENT> w, v = np.linalg.eig(k) <NEW_LINE> max_ = np.argsort(w)[:-n - 1:-1] <NEW_LINE> co = np.r...
Multidimensional scaling, MDS. Parameters ---------- mat : numpy.ndarray Distance matrix of the data points. n : int, optional The dimension of the projected points. The default is 2. Returns ------- co : numpy.ndarray Coordinates of the projected points.
625941eb187af65679ca5607
def str_to_int(s: str) -> int: <NEW_LINE> <INDENT> def len_of_int(n: int) -> int: <NEW_LINE> <INDENT> temp = n <NEW_LINE> res = 0 <NEW_LINE> while temp > 0: <NEW_LINE> <INDENT> res += 1 <NEW_LINE> temp = temp // 10 <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> int_s = ord(s[0]) <NEW_LINE> for i in range(1, len(s))...
This function transforms some string s to an integer. :param s: String that will be transformed. :type s: str. :returns int.
625941eb9f2886367277ad71
def _process_dataset(dataset, output_dir, here): <NEW_LINE> <INDENT> if not path.exists(output_dir): <NEW_LINE> <INDENT> os.makedirs(output_dir) <NEW_LINE> <DEDENT> with DirectoryContext(output_dir) as d: <NEW_LINE> <INDENT> requires_download = False <NEW_LINE> for f in dataset.get('files', []): <NEW_LINE> <INDENT> if ...
Process each download spec in datasets.yml Typically each dataset list entry in the yml has "files" and "url" and "title" keys/values to show local files that must be present / extracted from a decompression of contents downloaded from the url. If a url endswith '/', then all files given are assumed to be added to th...
625941eb31939e2706e4d34a
def calc_altitude(altitude, velocity): <NEW_LINE> <INDENT> altitude -= velocity <NEW_LINE> return altitude
This function is called to calculate altitude after every fuel burn. - Arguments:= *float* - current altitude and velocity. - Return value type:= *float*.
625941ebd99f1b3c44c67a6d
def cactus(self,i,j): <NEW_LINE> <INDENT> if not 0 < i <= j <= self.size(): <NEW_LINE> <INDENT> raise ValueError("integers out of bounds") <NEW_LINE> <DEDENT> if i == j: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> if i == 1: <NEW_LINE> <INDENT> h = list(self)[:j] <NEW_LINE> t = list(self)[j:] <NEW_LINE> T = sel...
Return the action of the generator `s_{i,j}` of the cactus group on ``self``. INPUT: ``i`` -- a positive integer ``j`` -- a positive integer weakly greater than ``i`` EXAMPLES:: sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0]) sage: t.cactus(1,5) [0, 1, 0, 1, 2, 1, 0] sage: t.cactus(1,6) [0, 1...
625941eb1d351010ab856002
def resolve(self, name): <NEW_LINE> <INDENT> function = self._EXPORTED_EFILTER_FUNCTIONS.get(name) <NEW_LINE> if function: <NEW_LINE> <INDENT> return function <NEW_LINE> <DEDENT> meta = self.session.plugins.plugin_db.GetActivePlugin(name) <NEW_LINE> if meta != None: <NEW_LINE> <INDENT> wrapper = CommandWrapper(meta.plu...
Find and return a CommandWrapper for the plugin 'name'.
625941eb16aa5153ce362960
def __init__(self, mcastAddress, serverAddress): <NEW_LINE> <INDENT> self.mcastAddress = mcastAddress <NEW_LINE> if not mcastAddress[0].is_multicast: <NEW_LINE> <INDENT> raise TypeError("mcastAddress must be a multicast address!") <NEW_LINE> <DEDENT> self.serverAddress = serverAddress <NEW_LINE> if isinstance(mcastAddr...
Both *mcastAddress* and *serverAddress* must be 2-tuples of an ipaddress.IPv4Address or ipaddress.IPv6Address and the integer port number.
625941eb2ae34c7f2600d618
def srv_fence_getall(self, req, bridge): <NEW_LINE> <INDENT> with self._fence_lock: <NEW_LINE> <INDENT> p = lambda i: apmsg.Fencepoint(i.lat, i.lng) <NEW_LINE> return self._getall_points('FENCE_TOTAL', self._get_fence_point, p)
service to get list of fence points
625941eba219f33f34628e4a
def posterize(img, bits): <NEW_LINE> <INDENT> shift = 8 - bits <NEW_LINE> img = np.left_shift(np.right_shift(img, shift), shift) <NEW_LINE> return img
Posterize an image (reduce the number of bits for each color channel) Args: img (ndarray): Image to be posterized, uint8. bits (int): Number of bits (1 to 8) to use for posterizing. Returns: ndarray: The posterized image.
625941ebcc0a2c11143dd379
def main(): <NEW_LINE> <INDENT> import sys <NEW_LINE> import os <NEW_LINE> filename = os.path.splitext(os.path.basename(sys.argv[0]))[0] <NEW_LINE> if len(sys.argv) < 3: <NEW_LINE> <INDENT> print('usage:') <NEW_LINE> print(' python %s %s.npy [save_dir] [layer names seperated by comma]' % (sys.argv[0],...
a tool used to convert caffe model to fluid
625941eb5e10d32532c5f40d
def getenv(): <NEW_LINE> <INDENT> if not local._env: <NEW_LINE> <INDENT> raise EnvError("No GDAL environment exists") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.debug("Got a copy of environment %r options", local._env) <NEW_LINE> return local._env.options.copy()
Get a mapping of current options.
625941eb5fcc89381b1e1bab
def main(): <NEW_LINE> <INDENT> CheckRucioSetup() <NEW_LINE> CheckRemainingProxyTime() <NEW_LINE> RunOptions = getArgumentParser().parse_args() <NEW_LINE> List = ClearFromDuplicates(ReadListFromFile(RunOptions.list)) <NEW_LINE> initiateReplication(ListOfDataSets=List, Rucio=RunOptions.rucio, RSE=RunOptions.RSE, lifeTim...
Request datasets to RSE location.
625941eb56ac1b37e62646ad