code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def solve_equation(a, b, c): <NEW_LINE> <INDENT> if a == b == c == 0: <NEW_LINE> <INDENT> return 'inf' <NEW_LINE> <DEDENT> if a == b == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if a == 0: <NEW_LINE> <INDENT> return -c/b <NEW_LINE> <DEDENT> D = b ** 2 - 4 * a * c <NEW_LINE> if D > 0: <NEW_LINE> <INDENT> x1 = (-... | input: a, b, c - integers
returns float solutions x of the following equation: a x ** 2 + b x + c == 0
In case of two diffrent solution returns tuple / list (x1, x2)
In case of one solution returns one float
In case of no float solutions return None
In case of infinity number of solutions returns 'inf' | 625941e992d797404e304643 |
def setcfFrameDisplay(self, v): <NEW_LINE> <INDENT> self.setcfValue(FRAME_DISPLAY, v) | Sets config value for frame display on/off
:param k:
:return: | 625941e91f037a2d8b9466b4 |
def __iter__(self): <NEW_LINE> <INDENT> return self.iter() | Default iterator over the leaf sequences.
Iteration happens in deapth-first order. A customizable iterator
is available through the :py:meth:`iter` method. | 625941e98e05c05ec3eea82f |
def test_feed_using_get3(self): <NEW_LINE> <INDENT> pass | Test case for feed_using_get3
Get certificate feeds # noqa: E501 | 625941e9bd1bec0571d90ae6 |
def load(self, index=None): <NEW_LINE> <INDENT> if not index: <NEW_LINE> <INDENT> pg = self._get_page('index') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pg = index <NEW_LINE> <DEDENT> self.data = [] <NEW_LINE> pages = len(self._xpath('pages', pg)) <NEW_LINE> self.pages = pages - 1 <NEW_LINE> if self.pages <= 0: <NE... | Loads the shop inventory for the :class:`User` instance of this class
Arguments:
**index**: Optional :class:`Page` instance with the user's shop
index page loaded | 625941e9b5575c28eb68e4bb |
def parse_html(self, page_html): <NEW_LINE> <INDENT> if ".html" not in page_html: <NEW_LINE> <INDENT> page_html += ".html" <NEW_LINE> <DEDENT> with open(page_html, 'r') as schedule: <NEW_LINE> <INDENT> soup = BeautifulSoup(schedule) <NEW_LINE> flag = False <NEW_LINE> count = 0 <NEW_LINE> details = 0 <NEW_LINE> for span... | Parse the html file passed into the function
It should be the HTML file from the view schedule page of Access Plus | 625941e9f548e778e58cda37 |
def predict_proba(self, x): <NEW_LINE> <INDENT> self.propabilityLVQ() <NEW_LINE> return np.array([ np.array([self.propa[i, self.find_closest(test_vector)[0]] for i in range(len(self.propa))]) for test_vector in x]) | Predict label's propability for a given input
Parameters
-------
test_vector: input vector | 625941e916aa5153ce36292f |
def send(self, current_strip): <NEW_LINE> <INDENT> data = bytearray(3*current_strip.length) <NEW_LINE> for i in reversed(range(current_strip.length)): <NEW_LINE> <INDENT> c = current_strip.get(current_strip.length - i) <NEW_LINE> data[3*i+0] = int( c[0] * self.fade ) <NEW_LINE> data[3*i+1] = int( c[1] * self.fade ) <NE... | Send the data of a strip | 625941e9460517430c39462f |
def get_candidates(itemSet, length): <NEW_LINE> <INDENT> return [list(x) for x in set(frozenset(i).union(frozenset(j)) for i in itemSet for j in itemSet if len(set(i).union(set(j))) == length)] | Join a set with itself and returns the n-element itemsets. | 625941e92eb69b55b151cd6d |
def test_exit_status_warning(self): <NEW_LINE> <INDENT> self._run(['/bin/echo', 'test'], ok = 'exit_status=1', warn = 'exit_status=0') <NEW_LINE> self.assertFalse(self.job.is_ok()) <NEW_LINE> self.assertTrue(self.job.is_warning()) | Test exit status matching WARN criteria | 625941e915baa723493c4430 |
def _gen_prefixes_with_length(self, index, rack_ls, row_valid_letters, placed): <NEW_LINE> <INDENT> if not row_valid_letters: <NEW_LINE> <INDENT> yield '', rack_ls <NEW_LINE> return <NEW_LINE> <DEDENT> if placed[0]: <NEW_LINE> <INDENT> assert(len(row_valid_letters[0]) == 1) <NEW_LINE> letters, = _encode(row_valid_lette... | Generate all prefixes with the given letters and valid placements
of length len(valid_letters), starting with index. | 625941e907f4c71912b1193c |
def write_csv(data, filename, header_row): <NEW_LINE> <INDENT> kwargs = {'newline': ''} <NEW_LINE> mode = 'w' <NEW_LINE> if sys.version_info < (3, 0): <NEW_LINE> <INDENT> kwargs.pop('newline', None) <NEW_LINE> mode = 'wb' <NEW_LINE> <DEDENT> with open(filename, mode, **kwargs) as fp: <NEW_LINE> <INDENT> writer = csv.wr... | Write CSV data for both Python2 and Python3 | 625941e930bbd722463cc280 |
@migration.command() <NEW_LINE> @click.argument("log_file", type=click.File("r"), nargs=1) <NEW_LINE> @click.argument("recid_list_file", type=click.File("r"), nargs=1) <NEW_LINE> def items_report(log_file, recid_list_file): <NEW_LINE> <INDENT> items_migration_report(log_file, recid_list_file) | Provide item migration summary. | 625941e9a17c0f6771cbe506 |
def _set_annotation_radio_button(idx, params): <NEW_LINE> <INDENT> radio = params['fig_annotation'].radio <NEW_LINE> for circle in radio.circles: <NEW_LINE> <INDENT> circle.set_facecolor('white') <NEW_LINE> <DEDENT> radio.circles[idx].set_facecolor('#cccccc') <NEW_LINE> _annotation_radio_clicked('', radio, params['ax']... | Set active button. | 625941e950812a4eaa59c7d4 |
def water_plant(self, plant_pot, liquid): <NEW_LINE> <INDENT> if liquid == self.water_id: <NEW_LINE> <INDENT> plant_pot.plant.grow() | Water (or sherry) a plant. If the liquid is water, the plant will
start growing.
:param plant_pot: The plant pot hit by the water or sherry.
:param liquid: The type of liquid. | 625941e96e29344779a62ac7 |
def constant_fold(expression): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Constant(value(expression)) <NEW_LINE> <DEDENT> except NotConstant: <NEW_LINE> <INDENT> return expression | Replace an expression with a constant if possible | 625941e9b545ff76a89142cc |
def gcta_grm_filter(in_file, out_file, grm_cutoff=0.025, gcta='gcta', per_chr=False, chr_list=None, ncpus=1, other_gcta_par=None, srun=False): <NEW_LINE> <INDENT> if chr_list is None: <NEW_LINE> <INDENT> chr_list = list(range(1, 23)) <NEW_LINE> <DEDENT> if other_gcta_par is None: <NEW_LINE> <INDENT> other_gcta_par = []... | Use GCTA to compute genetic relationship matrix (GRM):
From a GRM file, filter individuals to keep only a subset with no pair of individuals having
a relatedness over the value of grm_cutoff.
Writes three output files
test.grm.bin (it is a binary file which contains the lower triangle elements of the GRM).
test.g... | 625941e9b830903b967e9dbd |
def import_systems(self, db_client): <NEW_LINE> <INDENT> systems = set() <NEW_LINE> return systems | Add keras frcnns from a folder of pre-trained models.
:param db_client: The database client used to do the importing
:return: A collection of the database ids of the imported image sources | 625941e9711fe17d82542818 |
@blog.route("/") <NEW_LINE> def index(): <NEW_LINE> <INDENT> db = get_db() <NEW_LINE> posts = db.execute( "SELECT p.id, title, body, created, author_id, username" " FROM post p JOIN user u ON p.author_id = u.id" " ORDER BY created DESC" ).fetchall() <NEW_LINE> return render_template("blog/index.html", posts=posts) | Show all the posts, most recent first. | 625941e9004d5f362079a7e7 |
def get_closest(ra, dec, table, ra_key, dec_key): <NEW_LINE> <INDENT> d2t = get_distances(ra, dec, table, ra_key, dec_key) <NEW_LINE> match_id = argmin(d2t) <NEW_LINE> return table[match_id], d2t[match_id] | given an astropy Table containing sources with position keys ra[dec]_key,
return the entry closest to the target.
Parameters:
-----------
ra/dec: `float`
sky coordinates (J2000, in degrees) of the target direction.
table: `astropy.table.Table`
table with the sources among which the c... | 625941e9a4f1c619b28b04e5 |
def family_comma_given(self): <NEW_LINE> <INDENT> return self.formatted("%(family_name)s, %(given_name)s") | Return name as 'Family-name, Given-name' | 625941e94e696a04525c9905 |
def listen(self, _): <NEW_LINE> <INDENT> pass | Don't actually listen for pubsub events | 625941e97047854f462a18bb |
def onOpen(self, ws): <NEW_LINE> <INDENT> print(u'vnokex.onOpen') | 接口打开事件
:param ws:
:return: | 625941e9f7d966606f6aa4c1 |
def positive_roots(self): <NEW_LINE> <INDENT> return self.roots()[:self.number_of_reflections()] | Return the positive roots of ``self``.
EXAMPLES::
sage: W = ReflectionGroup(['A',3], ['B',2]) # optional - gap3
sage: W.positive_roots() # optional - gap3
[(1, 0, 0, 0, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 0),
(0, 0, 0, 1, 0),
(0, 0, 0, 0... | 625941e95166f23b2e1a5610 |
def on_batch_end(self, last_input, last_output, **kwargs): <NEW_LINE> <INDENT> self.G_A.zero_grad(); self.G_B.zero_grad() <NEW_LINE> fake_A, fake_B = last_output[0].detach(), last_output[1].detach() <NEW_LINE> real_A, real_B = last_input <NEW_LINE> self._set_trainable(D_A=True) <NEW_LINE> self.D_A.zero_grad() <NEW_LINE... | Steps through the generators then each of the discriminators. | 625941e929b78933be1e5b5d |
def _set_load_status(self, val): <NEW_LINE> <INDENT> if not isinstance(val, usertypes.LoadStatus): <NEW_LINE> <INDENT> raise TypeError("Type {} is no LoadStatus member!".format(val)) <NEW_LINE> <DEDENT> log.webview.debug("load status for {}: {}".format(repr(self), val)) <NEW_LINE> self._load_status = val <NEW_LINE> sel... | Setter for load_status. | 625941e99b70327d1c4e128f |
def GetAllQAs(qtotal=100): <NEW_LINE> <INDENT> page = 1 <NEW_LINE> next = '/api/v0/qa/all?page=' + str(page) <NEW_LINE> qas = [] <NEW_LINE> image_map = {} <NEW_LINE> while True: <NEW_LINE> <INDENT> data = utils.RetrieveData(next) <NEW_LINE> for d in data['results']: <NEW_LINE> <INDENT> if d['image'] not in image_map: <... | Gets all the QA from the dataset.
qtotal int total number of QAs to return. Set to None if all QAs should be returned | 625941e9925a0f43d254a333 |
def count_lines(self): <NEW_LINE> <INDENT> with open(self.curr_file) as open_file: <NEW_LINE> <INDENT> contents = open_file.readlines() <NEW_LINE> <DEDENT> return len(contents) | returns the number of lines in the current file | 625941e9d8ef3951e32439f5 |
def remove_node(node): <NEW_LINE> <INDENT> node.data = node.next.data <NEW_LINE> node.next = node.next.next | Given a node in a linked list, remove it.
Remove this node from a linked list. Note that we do not have access to
any other nodes of the linked list, like the head or the tail.
Does not return anything; changes list in place.
>>> four_node = Node(4)
>>> three_node = Node(3, four_node)
>>> two_node = Node(2, three_no... | 625941e95fc7496912cc3e35 |
def render(self): <NEW_LINE> <INDENT> self.send(((self.messagePrefix,self.sliderPos),), "outbox") <NEW_LINE> box = pygame.Rect(self.sliderPos, 0, 5, self.size[1]) <NEW_LINE> pygame.draw.rect(self.display, (0,0,0), box, 0) <NEW_LINE> self.send({"REDRAW":True, "surface":self.display}, "display_signal") | Draw the border and puck onto the surface | 625941e9baa26c4b54cb15d2 |
def test_create_parser_choices_init(self): <NEW_LINE> <INDENT> with self.assertRaises(SystemExit) as cm: <NEW_LINE> <INDENT> self.parser.parse_args(['init', '-h']) <NEW_LINE> <DEDENT> self.assertEqual(cm.exception.code, 0) | init -h | 625941e9507cdc57c630719e |
def __init__(self): <NEW_LINE> <INDENT> self.__nxt_width = 15 <NEW_LINE> self.__nxt_height = 20 <NEW_LINE> self.__max_distance = 5 <NEW_LINE> self.__nxt_speed = 5 <NEW_LINE> self.__points = [] <NEW_LINE> self.__points_max = 5 <NEW_LINE> self.__filled = [] <NEW_LINE> self.__filled_max = int(self.__nxt_width * self.__nxt... | Initialises an object to fill a map with points, passed by an NXT
Each object must be used for exact one NXT | 625941e9377c676e9127265e |
def run_training(self): <NEW_LINE> <INDENT> self.board = Board() <NEW_LINE> [player.reset() for player in self.players] <NEW_LINE> player_index = 0 <NEW_LINE> while not self.is_over(): <NEW_LINE> <INDENT> player = self.players[player_index] <NEW_LINE> position = player.get_next_move(self.board) <NEW_LINE> self.board.pl... | runs a single game and returns the winner, i.e. 0 (stale), 1, or 2
returns the winner | 625941e9bde94217f36832a4 |
def _set_arp_responder(self, action, lvid, mac_str, ip_str): <NEW_LINE> <INDENT> if not self.arp_responder_enabled: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mac = netaddr.EUI(mac_str, dialect=netaddr.mac_unix) <NEW_LINE> ip = netaddr.IPAddress(ip_str) <NEW_LINE> if action == 'add': <NEW_LINE> <INDENT> actions = (... | Set the ARP respond entry.
When the l2 population mechanism driver and OVS supports to edit ARP
fields, a table (ARP_RESPONDER) to resolve ARP locally is added to the
tunnel bridge.
:param action: add or remove ARP entry.
:param lvid: local VLAN map of network's ARP entry.
:param mac_str: MAC string value.
:param ip_... | 625941e9ab23a570cc25063e |
def makeTableList(url, caseSensitive = False, wildCards = True): <NEW_LINE> <INDENT> charList = [] <NEW_LINE> for ch in lower: <NEW_LINE> <INDENT> if(characterInTableName(ch, url)): <NEW_LINE> <INDENT> charList.append(ch) <NEW_LINE> <DEDENT> <DEDENT> for ch in numbers: <NEW_LINE> <INDENT> ch = str(ch) <NEW_LINE> if(cha... | List of characters in table names
Args:
url: String
form url
caseSensitive: Boolean
default False
true if case sentitivity matters
wildCards: Boolean
default True
true if wildcards should be placed where no other characters match
Returns:
lst: List
list of characters in... | 625941e94428ac0f6e5bacae |
def _unbind_observers(self): <NEW_LINE> <INDENT> self.instr_man_state.unobserve('all_profiles', self._update_profiles) <NEW_LINE> self.task.unobserve('selected_driver', self._update_profiles) <NEW_LINE> if isinstance(self.task, InterfaceableTaskMixin): <NEW_LINE> <INDENT> self.task.unobserve('selected_driver', self._up... | Unbind the observers at widget destruction.
| 625941e9b7558d58953c53c2 |
def main(): <NEW_LINE> <INDENT> opt_parser = RoseOptionParser() <NEW_LINE> opt_parser.add_my_options("case_mode", "lower", "output_file", "upper") <NEW_LINE> opts, args = opt_parser.parse_args() <NEW_LINE> return namelist_dump(args, opts.output_file, opts.case_mode) | CLI for "rose namelist-dump". | 625941e95e10d32532c5f3dd |
def received_scope(self, token, default=""): <NEW_LINE> <INDENT> received = getattr(token, "scope", None) <NEW_LINE> if received is None: <NEW_LINE> <INDENT> received = token.get('scope', default) <NEW_LINE> <DEDENT> requested_list = self.requested_scope() <NEW_LINE> requested_set = set(requested_list) <NEW_LINE> recei... | Extract scope granted by the provider from the token. The RFC isn't
strict about the scope, so aren't we.
Reference:
> The authorization server MAY fully or partially ignore the scope
> requested by the client, based on the authorization server policy or
> the resource owner's instructions. If the issued ... | 625941e9adb09d7d5db6cc44 |
def create_user_external(self, user_data, dato): <NEW_LINE> <INDENT> with transaction.atomic(): <NEW_LINE> <INDENT> user_data['email'] = dato[1] if dato[1] != 'null' else self.get_user_email(user_data['rut']) <NEW_LINE> if user_data['email'] == 'null': <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> user = self.cre... | Create the user given the user data.
If the email exists, get new email address. | 625941e92c8b7c6e89b35c75 |
def find_meta(meta): <NEW_LINE> <INDENT> meta_match = re.search( r'^__{meta}__ = ["\']([^"\']*)["\']'.format(meta=meta), META_FILE, re.M ) <NEW_LINE> if meta_match: <NEW_LINE> <INDENT> return meta_match.group(1) <NEW_LINE> <DEDENT> raise RuntimeError('Unable to find __{meta}__ string'.format(meta=meta)) | Extract __*meta*__ from META_FILE. | 625941e921bff66bcd684e06 |
def do_GET(self): <NEW_LINE> <INDENT> self.send_response(http.HTTPStatus.OK) <NEW_LINE> self.send_header("Content-type", 'text/html') <NEW_LINE> self.end_headers() <NEW_LINE> html = boilerplate_prefix + "The URL requested was: " + self.path + boilerplate_suffix <NEW_LINE> self.wfile.write(html.encode('utf-8')) | Serve a GET request. | 625941e9ff9c53063f47c6a9 |
def updateSettingsAttributes2(self, reqSeq, attributesToUpdate, settings): <NEW_LINE> <INDENT> pass | Parameters:
- reqSeq
- attributesToUpdate
- settings | 625941e976d4e153a657efea |
def __init__(self, func, xlim, ylim, time, fps=30, res=1000, pre_calc=False): <NEW_LINE> <INDENT> if isinstance(func, collections.Iterable): <NEW_LINE> <INDENT> self.funcs = list(func) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.funcs = [func] <NEW_LINE> <DEDENT> Animation.__init__(self, time, fps, pre_calc) <NE... | Animates a function f: [a,b]x[t0,tf] -> [c,d]
func : callable or iterable of callables
Takes a numpy array for the x domain and a scalar for the time domain
Returns a numpy array for the y domain
xlim : a sequence of floats ex. [a,b] or (a,b)
ylim : a sequence of floats ex. [c,d] or (c,d)
time : a sequence of floats ... | 625941e97cff6e4e81117e3d |
def calc_q(pvals): <NEW_LINE> <INDENT> pv = np.array(pvals) <NEW_LINE> pv = pv[isfinite(pv)] <NEW_LINE> pi0_hat = min(1, np.sum(pv) * 2 / len(pv)) <NEW_LINE> ranking = pv.argsort().argsort() + 1 <NEW_LINE> qlist = pv * pi0_hat * len(pv) / ranking <NEW_LINE> for i, rank in enumerate(ranking): <NEW_LINE> <INDENT> qlist[i... | Calculate q-values based on a list of p-values, with a conservative estimate
of the proportion of true null hypotheses (pi0_hat) based on the given p-values. | 625941e9ac7a0e7691ed457b |
def test_hidden_logged_in_no_permission(self): <NEW_LINE> <INDENT> self.login(self.alice) <NEW_LINE> response = self.client.get('/competition/5/registration/') <NEW_LINE> self.assertEqual(response.status_code, 403) <NEW_LINE> self.logout() | If random user logged in, it shouldn't work. | 625941e92ae34c7f2600d5e8 |
def integrate(self, a_xg, b_yg=None, global_integral=True, hermitian=False, _transposed_result=None): <NEW_LINE> <INDENT> if b_yg is None: <NEW_LINE> <INDENT> assert self.dtype == float <NEW_LINE> return a_xg[..., 0].real * self.gd.dv <NEW_LINE> <DEDENT> A_xg = a_xg.reshape((-1, a_xg.shape[-1])) <NEW_LINE> B_yg = b_yg.... | Integrate function(s) over domain.
a_xg: ndarray
Function(s) to be integrated.
b_yg: ndarray
If present, integrate a_xg.conj() * b_yg.
global_integral: bool
If the array(s) are distributed over several domains, then the
total sum will be returned. To get the local contribution
only, use global_int... | 625941e956b00c62f0f14b14 |
def _free(self): <NEW_LINE> <INDENT> _lib.caca_free_font.argtypes = [_Font] <NEW_LINE> _lib.caca_free_font.restype = ctypes.c_int <NEW_LINE> return _lib.caca_free_font(self) | Free a libcaca font.
| 625941e97d847024c06be778 |
def pyramidTransition(self, bottom, allowed): <NEW_LINE> <INDENT> replace = defaultdict(set) <NEW_LINE> for s in allowed: <NEW_LINE> <INDENT> replace[(s[0], s[1])].add(s[2]) <NEW_LINE> <DEDENT> status = [ set([c]) for c in bottom] <NEW_LINE> def generateNextStatus(): <NEW_LINE> <INDENT> if len(status) <=1: <NEW_LINE> <... | :type bottom: str
:type allowed: List[str]
:rtype: bool | 625941e929b78933be1e5b5e |
def nn_accuracy(X, X_embedded, k=1): <NEW_LINE> <INDENT> knn = NearestNeighbors(n_neighbors=1, n_jobs=-1) <NEW_LINE> _, neighbors_X = knn.fit(X).kneighbors() <NEW_LINE> _, neighbors_X_embedded = knn.fit(X_embedded).kneighbors() <NEW_LINE> return np.mean(neighbors_X == neighbors_X_embedded) | Accuracy of the first nearest neighbor | 625941e907d97122c4178d4e |
def write_options(self, options: Options) -> None: <NEW_LINE> <INDENT> raise NotImplementedError | Write Options `options` | 625941e9377c676e9127265f |
def GenPfHKLs(nMax,SGData,A): <NEW_LINE> <INDENT> HKL = np.array(GenHLaue(1.0,SGData,A)).T[:3].T <NEW_LINE> N = min(nMax,len(HKL)) <NEW_LINE> return ['%d %d %d'%(h[0],h[1],h[2]) for h in HKL[:N]] | Generate the unique pole figure reflections for a lattice and Bravais type.
Min d-spacing=1.0A & no more than nMax returned
:param nMax: maximum number of hkls returned
:param SGData: space group dictionary with at least
* 'SGLaue': Laue group symbol: one of '-1','2/m','mmm','4/m','6/m','4/mmm','6/mmm', '3m1', '... | 625941e982261d6c526ab95f |
def create_wizard(mod): <NEW_LINE> <INDENT> wiz = WC.Wizard(qt.QApplication.translate("WizardLinearThermic", "Linear thermal analysis", None, qt.QApplication.UnicodeUTF8), mod) <NEW_LINE> WC.add_model_page(wiz, [ WC.Mode3D, WC.Plane, ]) <NEW_LINE> exp_store = WC.ExpStore() <NEW_LINE> exp_store.register(WC.ExpStore.smes... | Create the linear thermic wizard | 625941e96fece00bbac2dbfd |
def _translate_volume_words(self): <NEW_LINE> <INDENT> volume_words = self.translate_namedvalues('volume.words') <NEW_LINE> if volume_words: <NEW_LINE> <INDENT> new_volume_words = {} <NEW_LINE> for volume_words_key in self.VOLUME_WORDS: <NEW_LINE> <INDENT> if volume_words.get(volume_words_key): <NEW_LINE> <INDENT> new_... | Translate VOLUME_WORDS keys for non-english support.
Any words in volume.words.value must also be contained in Level.voc | 625941e916aa5153ce362930 |
def bbox_center_dist(bboxes1, bboxes2, mode='L1'): <NEW_LINE> <INDENT> assert mode in ['L1', 'L2'] <NEW_LINE> ctr1 = xyxy_to_xcycwh(bboxes1)[:, 0:2] <NEW_LINE> ctr2 = xyxy_to_xcycwh(bboxes2)[:, 0:2] <NEW_LINE> delta = ctr1.unsqueeze(1) - ctr2.unsqueeze(0) <NEW_LINE> if mode == 'L1': <NEW_LINE> <INDENT> dist = torch.abs... | Calculate center distance between two set of bboxes.
Args:
bboxes1 (Tensor): shape (m, 4)
bboxes2 (Tensor): shape (n, 4)
Returns:
dist(Tensor): shape (m, n) | 625941e932920d7e50b2868c |
def permute(self, nums): <NEW_LINE> <INDENT> length = len(nums) <NEW_LINE> if length < 2: <NEW_LINE> <INDENT> return [nums] <NEW_LINE> <DEDENT> result_list = [] <NEW_LINE> self._permutation(result_list, [], nums) <NEW_LINE> return result_list | Time: 106ms.
:type nums: List[int]
:rtype: List[List[int]] | 625941e901c39578d7e752f4 |
def is_deleted_event(self) -> bool: <NEW_LINE> <INDENT> return self.type == LazydogEvent.EVENT_TYPE_DELETED | Returns ``True`` if the event is a file or dir deletion. | 625941e90fa83653e4657470 |
def __init__(self, env_fns, env_names=None): <NEW_LINE> <INDENT> self.env_fns = env_fns <NEW_LINE> self.env_names = env_names <NEW_LINE> self.env = None <NEW_LINE> self.env_idx = 0 <NEW_LINE> env = env_fns[0]() <NEW_LINE> try: <NEW_LINE> <INDENT> self.action_space = env.action_space <NEW_LINE> self.observation_space = ... | Create a joint environment.
Args:
env_fns: a sequence of callables that construct
new environments. All environments must have
the same spaces.
env_names: if specified, a sequence of names for
the env_fns. The name is included in the info
dict under 'env_name'. | 625941e94e696a04525c9906 |
def validate_member_owner_or_admin_view( *, two_challenge_set, client: Client, **kwargs ): <NEW_LINE> <INDENT> assert_viewname_redirect( redirect_url=settings.LOGIN_URL, challenge=two_challenge_set.challenge_set_1.challenge, client=client, **kwargs, ) <NEW_LINE> tests = [ (403, two_challenge_set.challenge_set_1.non_par... | Assert that a view is only accessible to administrators or participants
of that particular challenge. | 625941e985dfad0860c3b314 |
def run_main(): <NEW_LINE> <INDENT> os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sampleapp.settings") <NEW_LINE> sys.path.append(os.path.join(get_basedir(), 'sampleapp')) <NEW_LINE> from django.core.management import execute_from_command_line <NEW_LINE> execute_from_command_line([sys.argv[0], 'runserver', '0.0.0.0:... | Main Command Line Entry Point | 625941e9287bf620b61d3f19 |
def run(self, verbose=None, timeout=None): <NEW_LINE> <INDENT> self.set_verbose(verbose) <NEW_LINE> if timeout is not None: <NEW_LINE> <INDENT> self.timeout = int(timeout) <NEW_LINE> <DEDENT> runtime = Runtime() <NEW_LINE> return runtime.execute(self) | Alternative main entry point that doesn't print output and exit.
Initializes the runtime environment and runs the check under control of
this runtime environment.
This method does neither print the output to stdout nor exit the
process. To get it all in one method, use :meth:`main` instead.
:param verbose: output ve... | 625941e9e5267d203edce14f |
def delete(self, slug): <NEW_LINE> <INDENT> global client <NEW_LINE> sql = "DELETE from blogs WHERE slug = (%s)" <NEW_LINE> all_objects = client.list_objects(Bucket='sam-app-bucket') <NEW_LINE> poss_img = [] <NEW_LINE> for item in all_objects["Contents"]: <NEW_LINE> <INDENT> poss_img.append(item["Key"]) <NEW_LINE> <DED... | deletes a single blog post | 625941e9be7bc26dc91cdaaf |
def test_nativestr_empty_payload(self): <NEW_LINE> <INDENT> payload = NativeStr('') <NEW_LINE> deserialized = self._pack_and_unpack(NativeStr, payload) <NEW_LINE> self.assertEqual(payload.a, '') <NEW_LINE> self.assertEqual(deserialized.a, '') | Check if unpacked NativeStr('') works correctly. | 625941e966673b3332b92549 |
def ocrItems(self, **ocrArgs): <NEW_LINE> <INDENT> foundItems = [] <NEW_LINE> if self._ocrEngine != None: <NEW_LINE> <INDENT> self._notifyOcrEngine() <NEW_LINE> for word, bbox in self._ocrEngine.dumpOcr(self, **ocrArgs): <NEW_LINE> <INDENT> foundItems.append((GUIItem(word, bbox, self.filename()))) <NEW_LINE> <DEDENT> <... | Return list of GUIItems, each of them corresponding to a word
recognized by OCR. OCR engine must support dumpOcr.
Parameters:
**ocrArgs (keyword parameters):
refer to ocrEngine() documentation. | 625941e98e71fb1e9831dc60 |
def save_img(filename, np_array): <NEW_LINE> <INDENT> mpimg.imsave("{}.jpg".format(filename), np_array, vmin=0, vmax=255, format='jpg') | Save an image
Args:
filename: the file name
np_array: the image to save | 625941e9596a897236089f72 |
def family(self): <NEW_LINE> <INDENT> return self._family | Returns a package family string if this rule only applies to a given
package family, otherwise None. | 625941e9dc8b845886cb59ef |
def cal_adj_rate(): <NEW_LINE> <INDENT> tmp_count = 0.0 <NEW_LINE> if len(self.pos_result) == 0: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> for pos in self.pos_result: <NEW_LINE> <INDENT> if pos[1] in ['a', 'ad', 'an', 'ag', 'al', 'JJ', 'JJR', 'JJS']: <NEW_LINE> <INDENT> tmp_count += 1.0 <NEW_LINE> <DEDENT> <DE... | 计算形容词所占的比例
:return: | 625941e9d6c5a10208144507 |
def commit_pending_bios_changes(self, reboot=False): <NEW_LINE> <INDENT> return self._job_mgmt.create_config_job( resource_uri=uris.DCIM_BIOSService, cim_creation_class_name='DCIM_BIOSService', cim_name='DCIM:BIOSService', target=self.BIOS_DEVICE_FQDD, reboot=reboot) | Applies all pending changes on the BIOS by creating a config job
:param reboot: indicates whether a RebootJob should also be
created or not
:returns: id of the created job
:raises: WSManRequestFailure on request failures
:raises: WSManInvalidResponse when receiving invalid response
:raises: DRACOperatio... | 625941e923e79379d52eea16 |
@module.register("size") <NEW_LINE> def size(env) -> "(path -- int)": <NEW_LINE> <INDENT> env.stack.push(Token("lit_int", os.path.getsize(env.stack.pop().val))) | Returns the size of the file given by path in bytes | 625941e9ad47b63b2c50a437 |
def to_svg(self, round): <NEW_LINE> <INDENT> from svgfig import SVG <NEW_LINE> path_str = "" <NEW_LINE> if round is False: fmt = '%f,%f' <NEW_LINE> else: <NEW_LINE> <INDENT> fmt = '%.'+str(round)+'f' <NEW_LINE> fmt = fmt+','+fmt <NEW_LINE> <DEDENT> for pts in self.contours: <NEW_LINE> <INDENT> cont_str = "" <NEW_LINE> ... | constructs a svg representation of this polygon | 625941e95f7d997b87174f55 |
def points(self, pt, colorname='blue'): <NEW_LINE> <INDENT> fo = open(self.filename, "w") <NEW_LINE> if type(pt) == list: <NEW_LINE> <INDENT> pt = np.array(pt).reshape(3, 1) <NEW_LINE> <DEDENT> if type(pt) == dict: <NEW_LINE> <INDENT> npt = len(pt.keys()) <NEW_LINE> <DEDENT> if type(pt) == np.ndarray: <NEW_LINE> <INDEN... | Geomview display a set of points with color
Parameters
----------
pt
sequence of points np.ndarray or dictionnary whose value is a tuple (x,y,z)
colorname
a colorname from coldict keys
Examples
--------
>>> import numpy as np
>>> from pylayers.util.geomutil import *
>>> import scipy as sp
>>> pt1 = sp.rand(3,... | 625941e95fdd1c0f98dc06ee |
def console(request): <NEW_LINE> <INDENT> if not request.user.is_authenticated(): <NEW_LINE> <INDENT> return HttpResponseRedirect(reverse('login')) <NEW_LINE> <DEDENT> if request.method == 'GET': <NEW_LINE> <INDENT> token = request.GET.get('token', '') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> temptoken = token.spli... | Console instance block | 625941e90a50d4780f66734f |
def html_brainfuck(image, file, alphabet, text, x, y, font_size, is_url, clear, text_file, css): <NEW_LINE> <INDENT> size = x, y <NEW_LINE> if text_file: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tfile = open(text_file) <NEW_LINE> text = tfile.read() <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> print("ERR... | Generate the image with the arguments given by argparse | 625941e91f037a2d8b9466b5 |
def helper_get_fan_statuses(self): <NEW_LINE> <INDENT> logging.debug('') <NEW_LINE> status = [] <NEW_LINE> reply = self.command_get_parameter(OPCODE_FAN__FAN_SELECT) <NEW_LINE> if reply.result == 0x00: <NEW_LINE> <INDENT> for x in range(0, reply.max_value): <NEW_LINE> <INDENT> self.command_set_parameter(OPCODE_FAN__FAN... | Gets the fan status for all available fans.
:return: a list of the text status of each available fan | 625941e9cc0a2c11143dd34a |
def species(self): <NEW_LINE> <INDENT> return list(self.reactants) | Return a list of all Species involved in self. | 625941e930dc7b7665901e1a |
@csrf_exempt <NEW_LINE> def load_list(request): <NEW_LINE> <INDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> themes = Theme.objects.filter(is_custom=0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> themes = Theme.objects.filter(is_custom=0) <NEW_LINE> <DEDENT> return HttpResponse(serialize("json", themes... | Load a list of themes. It also loads your custom themes | 625941e9d4950a0f3b08c801 |
@given( x_constraint=generate_axis_constraint(), y_constraint=generate_axis_constraint(), z_constraint=generate_axis_constraint(), a_constraint=generate_axis_constraint(), b_constraint=generate_axis_constraint(), c_constraint=generate_axis_constraint(), origin=generate_coordinates(), data=st.data(), ) <NEW_LINE> def te... | Test motion plan using Hypothesis. | 625941e94527f215b584c90b |
def load_logs(self): <NEW_LINE> <INDENT> with open(self.paramfile, 'r') as f: <NEW_LINE> <INDENT> loglines = f.read().splitlines() <NEW_LINE> <DEDENT> params_to_print = ['max_steps', 'num_episodes', 'c', 'num_atoms', 'tau', 'vmin', 'vmax', 'epsilon', 'epsilon_min', 'gamma', 'layer_sizes', 'actor_learn_rate', 'critic_le... | Loads data from on-disk log files, for later manipulation and plotting. | 625941e9627d3e7fe0d6930a |
def limit(self, value): <NEW_LINE> <INDENT> if self.norm() > value: <NEW_LINE> <INDENT> self.set_mag(value) | Limit vector's maximum magnitude to given value. | 625941e94d74a7450ccd467d |
def preprocess_record(self, params, record): <NEW_LINE> <INDENT> return self._map_to_queries('preprocess_record', params, record) | Implements `tensorflow_privacy.DPQuery.preprocess_record`. | 625941e94428ac0f6e5bacaf |
def login(self): <NEW_LINE> <INDENT> mac = Mobileclient.FROM_MAC_ADDRESS <NEW_LINE> credentials = json.load(open('data/unlocked/credentials.json', 'r')) <NEW_LINE> self.client.login(credentials['username'], credentials['password'], mac) | Use data/unlocked/credentials.json to log in | 625941e94c3428357757c7de |
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.text = self.text.strip() <NEW_LINE> if self.name == '' and self.author is not None: <NEW_LINE> <INDENT> self.name = self.author.username <NEW_LINE> <DEDENT> self.check_spam() <NEW_LINE> super(Message, self).save(*args, **kwargs) | Enregistrer le message dans la base de données | 625941e98e7ae83300e4b487 |
def set_file_found(self, directory, filename, hashval): <NEW_LINE> <INDENT> final_path = self._get_file_found_cache_path( directory, filename, hashval) <NEW_LINE> with open(final_path, 'a'): <NEW_LINE> <INDENT> os.utime(final_path, None) | Sets the file was found and its hash value.
Arguments:
directory - the directory where the file was found
filename - the file name to the file found
hashval - the md5 hash value of the file found | 625941e992d797404e304645 |
def make_kernel(a): <NEW_LINE> <INDENT> a = np.asarray(a) <NEW_LINE> a = a.reshape(list(a.shape) + [1,1]) <NEW_LINE> return tf.constant(a, dtype="complex64") | Transform a 3D array into a convolution kernel | 625941e9f548e778e58cda39 |
def name(self) -> str: <NEW_LINE> <INDENT> return self.label() | Canonical image name based on configured namespace and registry. | 625941e98e05c05ec3eea831 |
def draw_maze(): <NEW_LINE> <INDENT> clear_screen() <NEW_LINE> flash = game['complete'] <NEW_LINE> clear_flash = flash and time.get_ticks() % 500 < 250 <NEW_LINE> maze_rect = (SHEET_MAZE[0] + SHEET_MAZE[2] * game_settings['maze'], SHEET_MAZE[1] + SHEET_MAZE[3] * clear_flash, SHEET_MAZE[2], SHEET_MAZE[3]) <NEW_LINE> GAM... | Draw maze and pellets | 625941e994891a1f4081bf64 |
def install_pckg(dest, name): <NEW_LINE> <INDENT> usrhome = get_home() <NEW_LINE> src = usrhome+"/.repository.config" <NEW_LINE> with open(src, 'r') as f_obj: <NEW_LINE> <INDENT> packages = f_obj.readlines() <NEW_LINE> f_obj.close() <NEW_LINE> for package in packages: <NEW_LINE> <INDENT> if name in package: <NEW_LINE> ... | Function that will do a mock install of a package.
This will first query the internal.config to see if anything exists.
It will place all packages into an array to be compared to packages to be installed.
This function will also be used for testing updates as logic is same. | 625941e90fa83653e4657471 |
def _build_network(self): <NEW_LINE> <INDENT> x = tf.placeholder(tf.int32, [None, self.seq_length], name='input') <NEW_LINE> embeddings = tf.get_variable('embedding_matrix', [self.vocab_size, self.n_h_units]) <NEW_LINE> rnn_input = tf.nn.embedding_lookup(embeddings, x) <NEW_LINE> if self.cell_type == 'GRU': <NEW_LINE> ... | Input shape should be (batch_size, seq_length, 1). | 625941e9460517430c394631 |
def blocked_cross_prod( x: ArraySequence, z: ArraySequence, s: Float64Array ) -> Float64Array: <NEW_LINE> <INDENT> k = len(x) <NEW_LINE> xp = [] <NEW_LINE> for i in range(k): <NEW_LINE> <INDENT> row = [] <NEW_LINE> for j in range(k): <NEW_LINE> <INDENT> s_ij = s[i, j] <NEW_LINE> row.append(s_ij * (x[i].T @ z[j])) <NEW_... | Parameters
----------
x : list of ndarray
k-element list of arrays to use as the left side of the cross-product
z : list of ndarray
k-element list of arrays to use as the right side of the cross-product
s : ndarray
Weighting matrix (k by k)
Returns
-------
ndarray
Weighted cross product constructed fro... | 625941e93c8af77a43ae3c5f |
def test__api_normalizeurl_search_single_good_1_clause_2(self): <NEW_LINE> <INDENT> new_slugs = dict(self.default_url_slugs) <NEW_LINE> url = '/__normalizeurl.json?widgets=observationduration&observationduration1_2=10.' <NEW_LINE> new_slugs['observationduration1'] = '10' <NEW_LINE> new_slugs['unit-observationduration']... | [test_ui_api.py] /__normalizeurl: search single good 1 _2 | 625941e9cad5886f8bd27492 |
def get_form_field_dict(self, model_dict): <NEW_LINE> <INDENT> return_dict = {} <NEW_LINE> for field_key, field_dict in model_dict.iteritems(): <NEW_LINE> <INDENT> if not field_key.startswith("_"): <NEW_LINE> <INDENT> widget = field_dict.get('_widget', None) <NEW_LINE> if widget is None: <NEW_LINE> <INDENT> return_dict... | Takes a model dictionary representation and creates a dictionary
keyed by form field. Each value is a keyed 4 tuple of:
(widget, mode_field_instance, model_field_type, field_key) | 625941e994891a1f4081bf65 |
def showGrid(self): <NEW_LINE> <INDENT> if self.checkBox_showGrid.isChecked(): <NEW_LINE> <INDENT> self.plot.getPlotItem().getAxis('left').setGrid(255) <NEW_LINE> self.plot.getPlotItem().getAxis('bottom').setGrid(255) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.plot.getPlotItem().getAxis('left').setGrid(False) <... | Toggles the grid on or off. | 625941e9b830903b967e9dbf |
def export_csv (self, fn: str, enc: str): <NEW_LINE> <INDENT> with open(fn, 'w', encoding = enc) as f: <NEW_LINE> <INDENT> f_csv = csv.writer(f) <NEW_LINE> f_csv.writerow(self.table[0]) <NEW_LINE> f_csv.writerows(self.table[1]) | Export financial table | 625941e9004d5f362079a7e9 |
def assert_is_read(self): <NEW_LINE> <INDENT> current_index = self.tell() <NEW_LINE> bytes = self.getvalue() <NEW_LINE> maximum_index = len(bytes) <NEW_LINE> everything_is_read = current_index == maximum_index <NEW_LINE> message = "Expected the message {} to be read to the end, " "but the last {} bytes are n... | Make sure this message is read 100%. | 625941e956ac1b37e626467f |
@asyncio.coroutine <NEW_LINE> def response_factory(app, handler): <NEW_LINE> <INDENT> @asyncio.coroutine <NEW_LINE> def response(request): <NEW_LINE> <INDENT> logging.info('Response handler...') <NEW_LINE> r = yield from handler(request) <NEW_LINE> if isinstance(r, web.StreamResponse): <NEW_LINE> <INDENT> return r <NEW... | 主要是对返回数据的数据头进行处理。用yield from handler(request)隔开
:param app:
:param handler:
:return: | 625941e94f88993c3716c51c |
def get_name_symb(empty_value_flag): <NEW_LINE> <INDENT> all_currencies = requests.get(constants.currencies_list_addr).json() <NEW_LINE> for currency in all_currencies.values(): <NEW_LINE> <INDENT> if empty_value_flag: <NEW_LINE> <INDENT> return {currency_info['id']: currency_info.get('currencySymbol', "").lower() for ... | Create a dictionary with currencies names and currencies symbols
:param empty_value_flag: if a flag is set to true, currencies without currencies symbol will be added to result list
:return: dictionary with following structure [currency code]:[currency symbol] | 625941e9f9cc0f698b140ab0 |
def to_numeric_features(features, feature_cols=None): <NEW_LINE> <INDENT> for col in CATEGORICAL_COLS: <NEW_LINE> <INDENT> features = pd.concat( [features, pd.get_dummies(features[col[0]], drop_first=True)], axis=1) <NEW_LINE> features.drop(col[0], axis=1, inplace=True) <NEW_LINE> <DEDENT> for col in UNUSED_COLUMNS: <N... | Converts the pandas input features to numeric values.
Args:
features: Input features in the data age (continuous) workclass
(categorical) fnlwgt (continuous) education (categorical) education_num
(continuous) marital_status (categorical) occupation (categorical)
relationship (categorical) race (categoric... | 625941e94a966d76dd5514cd |
def execute(self, game, parent = None): <NEW_LINE> <INDENT> self.game = game <NEW_LINE> self.parent = parent <NEW_LINE> self.init() <NEW_LINE> while True: <NEW_LINE> <INDENT> self.update() <NEW_LINE> yield | Template, base all elements off this execute method. | 625941e9eab8aa0e5d26e013 |
def add_handler(self, handler): <NEW_LINE> <INDENT> self.handlers.append(handler) <NEW_LINE> return self | add new handler method | 625941e99b70327d1c4e1291 |
def has_valid_groups_or_roles(path: str, handler: Callable, user: User) -> Union[ValueError, None]: <NEW_LINE> <INDENT> roles = handler.login_roles <NEW_LINE> groups = handler.login_groups <NEW_LINE> if groups and not any(x.name in groups for x in user.groups): <NEW_LINE> <INDENT> raise ValueError("User '{}' is not in ... | Check if an user has permissions for access to the requested URL
:raise ValueError: Permissions are not correct | 625941e98c3a87329515887a |
def __init__(self, sock): <NEW_LINE> <INDENT> BaseSFTP.__init__(self) <NEW_LINE> self.sock = sock <NEW_LINE> self.ultra_debug = False <NEW_LINE> self.request_number = 1 <NEW_LINE> self._lock = threading.Lock() <NEW_LINE> self._cwd = None <NEW_LINE> self._expecting = weakref.WeakValueDictionary() <NEW_LINE> if type(sock... | Create an SFTP client from an existing `.Channel`. The channel
should already have requested the ``"sftp"`` subsystem.
An alternate way to create an SFTP client context is by using
`from_transport`.
:param .Channel sock: an open `.Channel` using the ``"sftp"`` subsystem
:raises:
`.SSHException` -- if there's an... | 625941e97047854f462a18be |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.