code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
def test_bst_delete_node_two_children(bst): <NEW_LINE> <INDENT> bst.insert(8) <NEW_LINE> bst.insert(6) <NEW_LINE> bst.insert(7) <NEW_LINE> bst.insert(5) <NEW_LINE> bst.delete(6) <NEW_LINE> assert bst.root.val == 8 <NEW_LINE> assert bst.root.left.val == 5 <NEW_LINE> assert bst.root.left.right.val == 7 <NEW_LINE> assert bst.root.left.right.parent.val == 5 <NEW_LINE> assert bst.root.left.parent.val == 8 <NEW_LINE> assert bst.search(6) is None
|
.
|
625941bd6e29344779a62501
|
def MLbinomOptim_while(k,n,pCurr=0.5,diff=0.1,thresh=0.001): <NEW_LINE> <INDENT> pCurrLike = binomPMF(k,n,pCurr) <NEW_LINE> pUpLike = binomPMF(k,n,(pCurr+diff)) <NEW_LINE> pDownLike = binomPMF(k,n,(pCurr-diff)) <NEW_LINE> while (diff > thresh): <NEW_LINE> <INDENT> while (pCurrLike < pUpLike) or (pCurrLike < pDownLike): <NEW_LINE> <INDENT> if pUpLike > pCurrLike: <NEW_LINE> <INDENT> pCurr = pCurr + diff <NEW_LINE> <DEDENT> elif pDownLike > pCurrLike: <NEW_LINE> <INDENT> pCurr = pCurr- diff <NEW_LINE> <DEDENT> pCurrLike = binomPMF(k,n,pCurr) <NEW_LINE> pUpLike = binomPMF(k,n,(pCurr+diff)) <NEW_LINE> pDownLike = binomPMF(k,n,(pCurr-diff)) <NEW_LINE> <DEDENT> diff *= 0.5 <NEW_LINE> pCurrLike = binomPMF(k,n,pCurr) <NEW_LINE> pUpLike = binomPMF(k,n,(pCurr+diff)) <NEW_LINE> pDownLike = binomPMF(k,n,(pCurr-diff)) <NEW_LINE> <DEDENT> return pCurr
|
This function optimizes the value of p for a binomial according to ML, based on
observed data (k successes in n trial). Uses while loops instead of recursion.
|
625941bd1f037a2d8b9460ec
|
def _pause_callback(self, event=None): <NEW_LINE> <INDENT> self.pause()
|
The method called when 'PAUSE' is clicked -- pauses the program
|
625941bd76e4537e8c351563
|
def t310002_x8(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> call = t310002_x6() <NEW_LINE> assert IsClientPlayer() == 1 <NEW_LINE> call = t310002_x7() <NEW_LINE> assert not IsClientPlayer() <NEW_LINE> <DEDENT> """Unused""" <NEW_LINE> return 0
|
State 0
|
625941bd76d4e153a657ea1d
|
def tail(f, window=20): <NEW_LINE> <INDENT> if window == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> BUFSIZ = 1024 <NEW_LINE> f.seek(0, 2) <NEW_LINE> bytes = f.tell() <NEW_LINE> size = window + 1 <NEW_LINE> block = -1 <NEW_LINE> data = [] <NEW_LINE> while size > 0 and bytes > 0: <NEW_LINE> <INDENT> if bytes - BUFSIZ > 0: <NEW_LINE> <INDENT> f.seek(block * BUFSIZ, 2) <NEW_LINE> data.insert(0, f.read(BUFSIZ)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f.seek(0, 0) <NEW_LINE> data.insert(0, f.read(bytes)) <NEW_LINE> <DEDENT> linesFound = data[0].count('\n') <NEW_LINE> size -= linesFound <NEW_LINE> bytes -= BUFSIZ <NEW_LINE> block -= 1 <NEW_LINE> <DEDENT> return ''.join(data).splitlines()[-window:]
|
Returns the last `window` lines of file `f` as a list.
|
625941bdb57a9660fec3376e
|
def AddValue(self, Value): <NEW_LINE> <INDENT> return super(IGPMultiValue, self).AddValue(Value)
|
Method IGPMultiValue.AddValue
INPUT
Value : IGPValue*
|
625941bda79ad161976cc032
|
def sync(self, registers): <NEW_LINE> <INDENT> return self.__client.sync(registers)
|
Sync the registers.
Args:
registers (dict): Registers
Returns:
bool: Status of sync.
|
625941bd38b623060ff0acdb
|
def _extract_pixel(self, char: str) -> list: <NEW_LINE> <INDENT> font = ImageFont.truetype( self.font_path, self.original_size*self.multipler) <NEW_LINE> tmp = Image.new('RGB', (1, 1), (0, 0, 0)) <NEW_LINE> tmp_d = ImageDraw.Draw(tmp) <NEW_LINE> width, height = tmp_d.textsize(char, font=font) <NEW_LINE> img = Image.new('RGB', (width, height), (0, 0, 0)) <NEW_LINE> img_d = ImageDraw.Draw(img) <NEW_LINE> img_d.text((0, 0), char, font=font) <NEW_LINE> img = img.convert(self.mode) <NEW_LINE> data = list(img.getdata()) <NEW_LINE> output_width = width//self.multipler <NEW_LINE> output_height = height//self.multipler <NEW_LINE> result = [[0]*(output_width) for _ in range(output_height)] <NEW_LINE> p_offset = self.multipler >> 1 <NEW_LINE> for i in range(output_height): <NEW_LINE> <INDENT> for j in range(output_width): <NEW_LINE> <INDENT> y = i*self.multipler <NEW_LINE> x = j*self.multipler <NEW_LINE> one_dim_idx = (y+p_offset)*width + x+p_offset <NEW_LINE> result[i][j] = data[one_dim_idx] <NEW_LINE> <DEDENT> <DEDENT> return result
|
Extract pixel information of the unicode charactor
Args:
char:
charactor you want to extract, length shoud be 1
Returns:
2 dim list of grayscale value
|
625941bd3617ad0b5ed67de5
|
def get_tag_names(self): <NEW_LINE> <INDENT> return self.get_sorted_ref_names('refs/tags')
|
Returns a sorted list of tag names.
|
625941bdcdde0d52a9e52f1d
|
def test_name_set_no_changes(self): <NEW_LINE> <INDENT> field1 = basic.numeric_float(4, 2, name='field1') <NEW_LINE> field2 = basic.numeric_float(4, 2, name='field2') <NEW_LINE> self.assertEqual('field1', field1.name) <NEW_LINE> self.assertEqual('field2', field2.name)
|
Tests that the field name does not change for creating a new one
|
625941bd45492302aab5e1ad
|
def insertNode(self,refNodeNum,newNodeNum,stop=False,after=True): <NEW_LINE> <INDENT> newNode = Node(newNodeNum) <NEW_LINE> if stop==True: newNode.setStop(True) <NEW_LINE> for nodeIdx in range(len(self.n)): <NEW_LINE> <INDENT> currentNodeNum = abs(int(self.n[nodeIdx].num)) <NEW_LINE> if currentNodeNum == abs(refNodeNum): <NEW_LINE> <INDENT> if after==True: <NEW_LINE> <INDENT> self.n.insert(nodeIdx+1,newNode) <NEW_LINE> WranglerLogger.debug("In line %s: inserted node %s after node %s" % (self.name,newNode.num,str(refNodeNum))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.n.insert(nodeIdx,newNode) <NEW_LINE> WranglerLogger.debug("In line %s: inserted node %s before node %s" % (self.name,newNode.num,str(refNodeNum)))
|
Inserts the given *newNodeNum* into this line, as a stop if *stop* is True.
The new node is inserted after *refNodeNum* if *after* is True, otherwise it is inserted
before *refNodeNum*.
*refNodeNum* and *newNodeNum* are ints.
|
625941bd2eb69b55b151c799
|
def newLap(self): <NEW_LINE> <INDENT> self.laps.append(time.time()) <NEW_LINE> return self.laps
|
Adds current time to laps list.
Returns
-------
laps: list
List of all the lap times.
|
625941bd32920d7e50b280ba
|
def delete(fqdn, rdtype=None, origin=None): <NEW_LINE> <INDENT> if rdtype is not None: <NEW_LINE> <INDENT> assert rdtype in ['A', 'AAAA', ] <NEW_LINE> rdtypes = [rdtype, ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rdtypes = ['A', 'AAAA'] <NEW_LINE> <DEDENT> for rdtype in rdtypes: <NEW_LINE> <INDENT> update_ns(fqdn, rdtype, action='del', origin=origin)
|
dns deleter
:param fqdn: fully qualified domain name (str)
:param rdtype: 'A', 'AAAA' or None (deletes 'A' and 'AAAA')
|
625941bdbe8e80087fb20b34
|
def get_match_info_from_link(page_link): <NEW_LINE> <INDENT> time.sleep(10) <NEW_LINE> response = futblot24.send_request(page_link) <NEW_LINE> page = scrapy.Selector(response) <NEW_LINE> actions = page.xpath(""".//tbody/tr""") <NEW_LINE> actions_list = [] <NEW_LINE> number_of_goals = {} <NEW_LINE> for _index in range(len(actions)): <NEW_LINE> <INDENT> minute = actions[_index].xpath(""".//td[@class='status']/text()""").extract_first() <NEW_LINE> score = actions[_index].xpath(""".//td[@class='result']/text()""").extract_first() <NEW_LINE> if _index > 0 and score == actions[_index - 1].xpath(""".//td[@class='result']/text()""").extract_first(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if score.strip() == '-': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> first_team_score = int(score.split('-')[0].strip()) <NEW_LINE> second_team_score = int(score.split('-')[1].strip()) <NEW_LINE> if '+' in minute: <NEW_LINE> <INDENT> minute = int(minute.split('+')[0]) <NEW_LINE> if number_of_goals.get(minute): <NEW_LINE> <INDENT> number_of_goals[minute] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> number_of_goals[minute] = 1 <NEW_LINE> <DEDENT> actions_list.append( {minute: {'home_team': first_team_score, 'guest_team': second_team_score, 'number_of_goals': number_of_goals}}) <NEW_LINE> continue <NEW_LINE> <DEDENT> elif minute.isdigit(): <NEW_LINE> <INDENT> minute = int(minute) <NEW_LINE> if minute > 90: <NEW_LINE> <INDENT> minute = 90 <NEW_LINE> if number_of_goals.get(minute): <NEW_LINE> <INDENT> number_of_goals[minute] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> number_of_goals[minute] = 1 <NEW_LINE> <DEDENT> actions_list.append( {minute: {'home_team': first_team_score, 'guest_team': second_team_score, 'number_of_goals': number_of_goals}}) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> number_of_goals[minute] = 1 <NEW_LINE> actions_list.append( {minute: {'home_team': first_team_score, 'guest_team': second_team_score, 'number_of_goals': 1}}) <NEW_LINE> <DEDENT> return sorted(actions_list, key=lambda x: list(x.keys())[0])
|
Get match details
:param page_link: string -- page url of match details
:return: list -- [{minute: {'home_team': home_team_score, 'guest_team': guest_team_score,
first_half': first_half, 'second_half': second_half}}]
|
625941bd442bda511e8be30a
|
def load_user_credentials(client_secrets, storage, flags): <NEW_LINE> <INDENT> flow = client.flow_from_clientsecrets( client_secrets, scope=API_SCOPES, message=tools.message_if_missing(client_secrets)) <NEW_LINE> credentials = storage.get() <NEW_LINE> if credentials is None or credentials.invalid: <NEW_LINE> <INDENT> credentials = tools.run_flow(flow, storage, flags) <NEW_LINE> <DEDENT> return credentials
|
Attempts to load user credentials from the provided client secrets file.
Args:
client_secrets: path to the file containing client secrets.
storage: the data store to use for caching credential information.
flags: command-line flags.
Returns:
A credential object initialized with user account credentials.
|
625941bdd164cc6175782c3b
|
def get_value(self, series, key): <NEW_LINE> <INDENT> s = com.values_from_object(series) <NEW_LINE> try: <NEW_LINE> <INDENT> value = super().get_value(s, key) <NEW_LINE> <DEDENT> except (KeyError, IndexError): <NEW_LINE> <INDENT> if isinstance(key, str): <NEW_LINE> <INDENT> asdt, parsed, reso = parse_time_string(key, self.freq) <NEW_LINE> grp = resolution.Resolution.get_freq_group(reso) <NEW_LINE> freqn = resolution.get_freq_group(self.freq) <NEW_LINE> vals = self._ndarray_values <NEW_LINE> if grp < freqn: <NEW_LINE> <INDENT> iv = Period(asdt, freq=(grp, 1)) <NEW_LINE> ord1 = iv.asfreq(self.freq, how="S").ordinal <NEW_LINE> ord2 = iv.asfreq(self.freq, how="E").ordinal <NEW_LINE> if ord2 < vals[0] or ord1 > vals[-1]: <NEW_LINE> <INDENT> raise KeyError(key) <NEW_LINE> <DEDENT> pos = np.searchsorted(self._ndarray_values, [ord1, ord2]) <NEW_LINE> key = slice(pos[0], pos[1] + 1) <NEW_LINE> return series[key] <NEW_LINE> <DEDENT> elif grp == freqn: <NEW_LINE> <INDENT> key = Period(asdt, freq=self.freq).ordinal <NEW_LINE> return com.maybe_box( self, self._int64index.get_value(s, key), series, key ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError(key) <NEW_LINE> <DEDENT> <DEDENT> period = Period(key, self.freq) <NEW_LINE> key = period.value if isna(period) else period.ordinal <NEW_LINE> return com.maybe_box(self, self._int64index.get_value(s, key), series, key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return com.maybe_box(self, value, series, key)
|
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
|
625941bd3c8af77a43ae368b
|
def testPlayWaitForPlayTimeout(self): <NEW_LINE> <INDENT> action = play.PlayAction(selector='#video_1', playing_event_timeout_in_seconds=0.1) <NEW_LINE> action.WillRunAction(self._tab) <NEW_LINE> self._tab.EvaluateJavaScript('document.getElementById("video_1").src = ""') <NEW_LINE> self.assertFalse(self._tab.EvaluateJavaScript(VIDEO_1_PLAYING_CHECK)) <NEW_LINE> self.assertRaises(util.TimeoutException, action.RunAction, self._tab)
|
Tests that wait_for_playing timeouts if video does not play.
|
625941bd004d5f362079a223
|
def withinit(init,n,sz=9): <NEW_LINE> <INDENT> if init=="": <NEW_LINE> <INDENT> return withdup(sz,n) <NEW_LINE> <DEDENT> matched = any([a==b for a,b in zip(init,init[1:])]) <NEW_LINE> l = init[-1] <NEW_LINE> available = sz+1-int(l) <NEW_LINE> lenleft = n-len(init) <NEW_LINE> if matched: <NEW_LINE> <INDENT> return ci(available,lenleft) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (ci(available,lenleft - 1)+ withdup(available - 1,lenleft) )
|
How many length `n` sequences are there beginning with `init` (part 1 conditions)
|
625941bd63d6d428bbe443dd
|
def test_delete_media(self): <NEW_LINE> <INDENT> pass
|
Test case for delete_media
|
625941bd5510c4643540f2d9
|
def test_ask_for_nothing(self, req, includes): <NEW_LINE> <INDENT> cookiejar = RequestsCookieJar() <NEW_LINE> cookiejar.set("a", 2) <NEW_LINE> mock_session = Mock(spec=requests.Session, cookies=cookiejar) <NEW_LINE> req["cookies"] = [] <NEW_LINE> assert _read_expected_cookies(mock_session, req, includes) == {}
|
explicitly ask fo rno cookies
|
625941bd460517430c39407a
|
def normalize_title(title): <NEW_LINE> <INDENT> title = title.replace(' ', '_').strip('_') <NEW_LINE> if not is_valid_title(title): <NEW_LINE> <INDENT> return title <NEW_LINE> <DEDENT> title = urllib.unquote(title).replace(' ','_').strip('_') <NEW_LINE> title = clean_anchors(title) <NEW_LINE> if not title: <NEW_LINE> <INDENT> return title <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> title = title.decode('utf8') <NEW_LINE> <DEDENT> except UnicodeError: <NEW_LINE> <INDENT> title = title.decode('latin-1') <NEW_LINE> <DEDENT> title = unicodedata.normalize("NFC", title) <NEW_LINE> title = title[0].upper() + title[1:] <NEW_LINE> title = title.encode('utf8') <NEW_LINE> title = urllib.quote(title, safe="%") <NEW_LINE> if not redirects: <NEW_LINE> <INDENT> return title <NEW_LINE> <DEDENT> flag = {} <NEW_LINE> while title in redirects: <NEW_LINE> <INDENT> title = redirects[title] <NEW_LINE> if title in flag: <NEW_LINE> <INDENT> return title <NEW_LINE> <DEDENT> flag[title] = True <NEW_LINE> <DEDENT> return title
|
Get a title and return its normalized form
|
625941bd0383005118ecf4d2
|
def _getpricestring(amount, denom): <NEW_LINE> <INDENT> return '{:g} {}'.format( amount, denom + 's' if denom in ('Key', 'Weapon') and amount != 1 else denom)
|
Return a human-readable price string
|
625941bda05bb46b383ec712
|
def _setup(self, config): <NEW_LINE> <INDENT> self.model_setup(config)
|
Custom initialization.
Args:
config (dict): Hyperparameters and other configs given.
Copy of `self.config`.
|
625941bd711fe17d8254225e
|
@pytest.fixture(scope="session") <NEW_LINE> def bolt_app(): <NEW_LINE> <INDENT> _app = Flask(__name__) <NEW_LINE> with _app.app_context(): <NEW_LINE> <INDENT> yield _app
|
Setup the test app context
:return: Flask app instance
|
625941bd15fb5d323cde09f9
|
def text(screen, health, len_zombies, fps, level, ammo, power_ups): <NEW_LINE> <INDENT> lifes_text_f = lifes_text.format(math.ceil(health)) <NEW_LINE> screen.blit(text_render(lifes_text_f), (0, 0)) <NEW_LINE> zombies_left_text_f = zombies_left_text.format(len_zombies) <NEW_LINE> screen.blit(text_render(zombies_left_text_f), (text_width * len(lifes_text_f) + Options.width // 25, 0)) <NEW_LINE> round_text_f = round_text.format(level) <NEW_LINE> screen.blit(text_render(round_text_f), (Options.width - text_width * len(round_text_f), 0)) <NEW_LINE> ammo_text_f = ammo_text.format(ammo) <NEW_LINE> screen.blit(text_render(ammo_text_f), ( Options.width - text_width * len(ammo_text_f), Options.height - text_height)) <NEW_LINE> fps_text_f = fps_text.format("{0:.2f}".format(fps)) <NEW_LINE> screen.blit(text_render(fps_text_f), (0, Options.height - text_height)) <NEW_LINE> power_up_text_f = power_up_text.format( [get_text("drops", d) for d in power_ups]) <NEW_LINE> screen.blit(text_render(power_up_text_f), (0, Options.height - text_height * 2))
|
Writes all the text during the standard game loop
|
625941bd92d797404e304077
|
def kit(): <NEW_LINE> <INDENT> if len(request.args) == 2: <NEW_LINE> <INDENT> s3db.configure("budget_kit", update_next=URL(f="kit_item", args=request.args[1])) <NEW_LINE> <DEDENT> return s3_rest_controller(rheader=s3db.budget_rheader, main="code")
|
REST controller for kits
|
625941bd6aa9bd52df036c90
|
def __init__(self, command): <NEW_LINE> <INDENT> self.command = command
|
Initialize the service.
|
625941bdbf627c535bc130bc
|
def compute_total_distance(road_map): <NEW_LINE> <INDENT> total_distance = 0 <NEW_LINE> for i in range(len(road_map)): <NEW_LINE> <INDENT> lat1degrees = float(road_map[i][2]) <NEW_LINE> long1degrees = float(road_map[i][3]) <NEW_LINE> lat2degrees = float(road_map[(i+1) % len(road_map)][2]) <NEW_LINE> long2degrees = float(road_map[(i+1) % len(road_map)][3]) <NEW_LINE> total_distance = total_distance + distance(lat1degrees, long1degrees, lat2degrees, long2degrees) <NEW_LINE> <DEDENT> return total_distance
|
Returns, as a floating point number, the sum of the distances of all
the connections in the road_map. Remember that it's a cycle, so that
(for example) in the initial road_map,Wyoming connects to Alabama..
|
625941bdb545ff76a8913d0b
|
def wait(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self._server is not None: <NEW_LINE> <INDENT> self._server.wait() <NEW_LINE> <DEDENT> <DEDENT> except greenlet.GreenletExit: <NEW_LINE> <INDENT> LOG.info("WSGI server has stopped.")
|
Block, until the server has stopped.
Waits on the server's eventlet to finish, then returns.
:returns: None
|
625941bdff9c53063f47c0e3
|
def run_forever(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.event_loop.run_forever() <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> print("Active OutputThings: %s" % ', '.join([('%s'%o) for o in self.active_schedules.keys()])) <NEW_LINE> raise <NEW_LINE> <DEDENT> if self.fatal_error is not None: <NEW_LINE> <INDENT> raise ScheduleError("Scheduler aborted due to fatal error") from self.fatal_error
|
Call the event loop's run_forever(). We don't really run forever:
the event loop is exited if we run out of scheduled events or if stop()
is called.
|
625941bd3539df3088e2e239
|
def __tidy_list(self): <NEW_LINE> <INDENT> self.word_list[:] = self.__remove_empty_strings(self.word_list) <NEW_LINE> self.word_list[:] = map(self.__clean_trailing_symbols, self.word_list) <NEW_LINE> self.word_list[:] = self.__remove_case_from_list(self.word_list)
|
This function removes trailing symbols and empty entries from the list
as well as forces lowercase to prepare for the word frequency count
|
625941bd099cdd3c635f0b4a
|
def test_get_globalconfig(self): <NEW_LINE> <INDENT> res = self.client().post('/globalconfig', headers={'Content-Type': 'application/json'}, data=json.dumps(self.globalconfig)) <NEW_LINE> json_data = json.loads(res.data) <NEW_LINE> self.assertEqual(res.status_code, 201) <NEW_LINE> res = self.client().get('/globalconfig', headers={'Content-Type': 'application/json'}) <NEW_LINE> self.assertEqual(res.status_code, 200)
|
test globalconfig getAll
|
625941bd596a8972360899b1
|
def calculate_availability(self, product): <NEW_LINE> <INDENT> logger.info('WeeklyMenu calculating availability') <NEW_LINE> required = {} <NEW_LINE> counter_list = [] <NEW_LINE> counter = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> serve = product.serve <NEW_LINE> ingredientslist = self.Ingredient.search(['dish', '=', product.id]) <NEW_LINE> for ingredient_obj in ingredientslist: <NEW_LINE> <INDENT> namekey = ingredient_obj.ingredient.template.name <NEW_LINE> new_uom, new_quantity = self.process.convert_uom_to_higher(ingredient_obj.quantity_uom, ingredient_obj.quantity) <NEW_LINE> required[namekey] = (new_uom, new_quantity) <NEW_LINE> <DEDENT> available = self.manage_inventory.get_stock() <NEW_LINE> for i, j in required.iteritems(): <NEW_LINE> <INDENT> if available.get(i): <NEW_LINE> <INDENT> counter_list.append(Decimal(available[i][1]) / j[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> counter = min(counter_list) if counter_list else Decimal(0) <NEW_LINE> return counter.quantize(Decimal('0')) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> if settings.level == 10: <NEW_LINE> <INDENT> logger.exception('raised exception') <NEW_LINE> <DEDENT> return False
|
calculate if the dish is available
|
625941bdf8510a7c17cf95e8
|
def __str__(self): <NEW_LINE> <INDENT> answer = [] <NEW_LINE> n = self.n <NEW_LINE> x = max(len(str(self.matrix[i,j])) for i in range(n) for j in range(n)) <NEW_LINE> for i in range(self.n): <NEW_LINE> <INDENT> answer.append(" ".join([str(self.matrix[i,j]).ljust(x) for j in range(n)]) + " %s" % self.captions[i]) <NEW_LINE> <DEDENT> return "\n".join(answer)
|
String representation of the matrix, used by the print command
|
625941bdbe383301e01b537a
|
def options(self): <NEW_LINE> <INDENT> return _gnsdk.GnVideo_options(self)
|
options(GnVideo self) -> GnVideoOptions
|
625941bd66656f66f7cbc098
|
def test_pecas_iguais_success(self): <NEW_LINE> <INDENT> for pieces in self.pieces: <NEW_LINE> <INDENT> p1 = target.cria_peca(pieces) <NEW_LINE> p2 = target.cria_peca(pieces) <NEW_LINE> self.assertTrue(target.pecas_iguais(p1, p2))
|
Testa pecas_iguais para todas as peças válidas possíveis
|
625941bd99fddb7c1c9de280
|
def testBuildBotWithGoodChromeRootOption(self): <NEW_LINE> <INDENT> args = ['--local', '--buildroot=/tmp', '--chrome_root=.', self._X86_PREFLIGHT] <NEW_LINE> self.mox.ReplayAll() <NEW_LINE> (options, args) = cbuildbot._ParseCommandLine(self.parser, args) <NEW_LINE> self.mox.VerifyAll() <NEW_LINE> self.assertEquals(options.chrome_rev, constants.CHROME_REV_LOCAL) <NEW_LINE> self.assertNotEquals(options.chrome_root, None)
|
chrome_root can be set without chrome_rev.
|
625941bdde87d2750b85fc7d
|
@error_context.context_aware <NEW_LINE> def run(test, params, env): <NEW_LINE> <INDENT> vm = env.get_vm(params["main_vm"]) <NEW_LINE> session = vm.wait_for_login() <NEW_LINE> driver_name = params["driver_name"] <NEW_LINE> session = utils_test.qemu.windrv_check_running_verifier(session, vm, test, driver_name) <NEW_LINE> run_sigverif_cmd = utils_misc.set_winutils_letter( session, params["run_sigverif_cmd"]) <NEW_LINE> sigverif_log = params["sigverif_log"] <NEW_LINE> check_sigverif_cmd = params["check_sigverif_cmd"] % driver_name <NEW_LINE> clean_sigverif_cmd = params["clean_sigverif_cmd"] <NEW_LINE> error_context.context("Run sigverif in windows guest", logging.info) <NEW_LINE> session.cmd(clean_sigverif_cmd, ignore_all_errors=True) <NEW_LINE> vm.send_key('meta_l-d') <NEW_LINE> time.sleep(60) <NEW_LINE> status, output = session.cmd_status_output(run_sigverif_cmd) <NEW_LINE> if status != 0: <NEW_LINE> <INDENT> test.error(output) <NEW_LINE> <DEDENT> if not utils_misc.wait_for(lambda: system.file_exists(session, sigverif_log), 180, 0, 5): <NEW_LINE> <INDENT> test.error("sigverif logs are not created") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> error_context.context("Open sigverif logs and check driver signature" " status", logging.info) <NEW_LINE> output = session.cmd_output(check_sigverif_cmd) <NEW_LINE> pattern = r"%s.sys.*\s{2,}Signed" % driver_name <NEW_LINE> if not re.findall(pattern, output, re.M): <NEW_LINE> <INDENT> test.fail("%s driver is not digitally signed, details info is:\n %s" % (driver_name, output)) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> error_context.context("Clean sigverif logs", logging.info) <NEW_LINE> session.cmd(clean_sigverif_cmd, ignore_all_errors=True)
|
sigverif test:
1) Boot guest with related virtio devices
2) Run sigverif command(an autoit script) in guest
3) Open sigverif log and check whether driver is signed
:param test: QEMU test object
:param params: Dictionary with the test parameters
:param env: Dictionary with test environment
|
625941bdc432627299f04b31
|
def t_NUMBER(t): <NEW_LINE> <INDENT> t.value = float(t.value) <NEW_LINE> return t
|
[\d+][.][\d+]| \d+
|
625941bd498bea3a759b999e
|
def test_post_profile_error(self): <NEW_LINE> <INDENT> FacebookPost.query.delete() <NEW_LINE> FacebookInfo.query.delete() <NEW_LINE> db.session.commit() <NEW_LINE> result = self.client.get("/post_profile", follow_redirects=True) <NEW_LINE> self.assertIn("You need to log into Facebook first!", result.data)
|
Testing post_profile page error
|
625941bdc432627299f04b32
|
@csrf_protect <NEW_LINE> @require_POST <NEW_LINE> def post_comment_ajax(request, using=None): <NEW_LINE> <INDENT> if not request.is_ajax(): <NEW_LINE> <INDENT> return HttpResponseBadRequest("Expecting Ajax call") <NEW_LINE> <DEDENT> data = request.POST.copy() <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> if not data.get('name', ''): <NEW_LINE> <INDENT> data["name"] = request.user.get_full_name() or request.user.username <NEW_LINE> <DEDENT> if not data.get('email', ''): <NEW_LINE> <INDENT> data["email"] = request.user.email <NEW_LINE> <DEDENT> <DEDENT> ctype = data.get("content_type") <NEW_LINE> object_pk = data.get("object_pk") <NEW_LINE> if ctype is None or object_pk is None: <NEW_LINE> <INDENT> return CommentPostBadRequest("Missing content_type or object_pk field.") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> model = get_django_model(*ctype.split(".", 1)) <NEW_LINE> target = model._default_manager.using(using).get(pk=object_pk) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return CommentPostBadRequest("Invalid object_pk value: {0}".format(escape(object_pk))) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return CommentPostBadRequest("Invalid content_type value: {0}".format(escape(ctype))) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return CommentPostBadRequest("The given content-type {0} does not resolve to a valid model.".format(escape(ctype))) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return CommentPostBadRequest("No object matching content-type {0} and object PK {1} exists.".format(escape(ctype), escape(object_pk))) <NEW_LINE> <DEDENT> except (ValueError, ValidationError) as e: <NEW_LINE> <INDENT> return CommentPostBadRequest("Attempting go get content-type {0!r} and object PK {1!r} exists raised {2}".format(escape(ctype), escape(object_pk), e.__class__.__name__)) <NEW_LINE> <DEDENT> preview = "preview" in data <NEW_LINE> form = get_comments_form()(target, data=data) <NEW_LINE> if form.security_errors(): <NEW_LINE> <INDENT> return CommentPostBadRequest("The comment form failed security verification: {0}".format(form.security_errors())) <NEW_LINE> <DEDENT> if preview: <NEW_LINE> <INDENT> comment = form.get_comment_object() if not form.errors else None <NEW_LINE> return _ajax_result(request, form, "preview", comment, object_id=object_pk) <NEW_LINE> <DEDENT> if form.errors: <NEW_LINE> <INDENT> return _ajax_result(request, form, "post", object_id=object_pk) <NEW_LINE> <DEDENT> comment = form.get_comment_object() <NEW_LINE> comment.ip_address = request.META.get("REMOTE_ADDR", None) <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> comment.user = request.user <NEW_LINE> <DEDENT> responses = signals.comment_will_be_posted.send( sender = comment.__class__, comment = comment, request = request ) <NEW_LINE> for (receiver, response) in responses: <NEW_LINE> <INDENT> if response is False: <NEW_LINE> <INDENT> return CommentPostBadRequest("comment_will_be_posted receiver {0} killed the comment".format(receiver.__name__)) <NEW_LINE> <DEDENT> <DEDENT> comment.save() <NEW_LINE> signals.comment_was_posted.send( sender = comment.__class__, comment = comment, request = request ) <NEW_LINE> return _ajax_result(request, form, "post", comment, object_id=object_pk)
|
Post a comment, via an Ajax call.
|
625941bda8370b771705278e
|
def recurse(subreddit, after={}): <NEW_LINE> <INDENT> listings = [] <NEW_LINE> url = "https://www.reddit.com/r/{}.json".format(subreddit) <NEW_LINE> headers = {"User-agent": 'Shoji'} <NEW_LINE> params = {"after": after} <NEW_LINE> response = requests.get(url, headers=headers, params=params, allow_redirects=False) <NEW_LINE> if response.status_code != 200: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if after is None: <NEW_LINE> <INDENT> return listings <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> parent = response.json() <NEW_LINE> children = parent['data']['children'] <NEW_LINE> for child in children: <NEW_LINE> <INDENT> listings.append(child['data']['title']) <NEW_LINE> <DEDENT> after = parent['data']['after'] <NEW_LINE> ret = recurse(subreddit, after) <NEW_LINE> if listings: <NEW_LINE> <INDENT> ret.extend(listings) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return None
|
Returns a list of titles
|
625941bd462c4b4f79d1d5be
|
def monitorHUDManagement(func): <NEW_LINE> <INDENT> metaHUD = None <NEW_LINE> currentHUDs = getMetaNodes(mTypes=MetaHUDNode, mAttrs='mNodeID=CBMonitorHUD') <NEW_LINE> if currentHUDs: <NEW_LINE> <INDENT> metaHUD = currentHUDs[0] <NEW_LINE> <DEDENT> if func == 'delete': <NEW_LINE> <INDENT> if metaHUD: <NEW_LINE> <INDENT> metaHUD.delete() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> HUDS = cmds.headsUpDisplay(lh=True) <NEW_LINE> for hud in HUDS: <NEW_LINE> <INDENT> if 'MetaHUDConnector' in hud: <NEW_LINE> <INDENT> print('killing HUD : ', hud) <NEW_LINE> cmds.headsUpDisplay(hud, remove=True) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if func == 'refreshHeadsUp': <NEW_LINE> <INDENT> metaHUD.headsUpOnly = True <NEW_LINE> metaHUD.refreshHud() <NEW_LINE> <DEDENT> if func == 'refreshSliders': <NEW_LINE> <INDENT> metaHUD.headsUpOnly = False <NEW_LINE> metaHUD.refreshHud() <NEW_LINE> <DEDENT> if func == 'kill': <NEW_LINE> <INDENT> metaHUD.killHud()
|
ChannelBox wrappers for the HUD : kill any current MetaHUD headsUpDisplay blocks
|
625941bdcc0a2c11143dcd7e
|
def strip_sep(path: str) -> str: <NEW_LINE> <INDENT> retval = path.replace(os.sep, "") <NEW_LINE> if ON_WINDOWS: <NEW_LINE> <INDENT> retval = retval.replace(os.altsep, "") <NEW_LINE> <DEDENT> return retval
|
remove all path separators from argument
|
625941bd26238365f5f0ed58
|
def getLows(self, start_time = 0, end_time = 0, window_size = 50): <NEW_LINE> <INDENT> if start_time == 0: <NEW_LINE> <INDENT> start_time = self.start_time <NEW_LINE> <DEDENT> if end_time == 0: <NEW_LINE> <INDENT> end_time = self.end_time <NEW_LINE> <DEDENT> times, tides = self.getTidesBasedOnPeriod(start_time, end_time) <NEW_LINE> mean_tide = np.nanmean(tides) <NEW_LINE> one_hour = datetime(2000,1,1,2)-datetime(2000,1,1,1) <NEW_LINE> Lows_tides = [] <NEW_LINE> Lows_times = [] <NEW_LINE> for i in range(window_size, len(tides) - window_size): <NEW_LINE> <INDENT> middle = tides[i] <NEW_LINE> if middle < mean_tide: <NEW_LINE> <INDENT> left = np.nanmin(tides[i - window_size:i]) <NEW_LINE> right = np.nanmin(tides[i + 1:i + window_size + 1]) <NEW_LINE> if middle <= left and middle <= right: <NEW_LINE> <INDENT> if len(Lows_times) > 0: <NEW_LINE> <INDENT> if times[i]-Lows_times[-1] > one_hour: <NEW_LINE> <INDENT> Lows_tides.append(middle) <NEW_LINE> Lows_times.append(times[i]) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> Lows_tides.append(middle) <NEW_LINE> Lows_times.append(times[i]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return Lows_times, Lows_tides
|
Method to retrieve low water (both times and water levels)
:param start_time: datetime object of start of the requested period
:param end_time: datetime object of end of the requested period
:param window_size: parameter to define peaks
:return: times and tides series with the times and water levels of the requested lows
|
625941bdcc40096d61595840
|
def change_size(self, percent): <NEW_LINE> <INDENT> self.radius *= (percent / 100.0)
|
Change the size of the circle in percent.
Operation does not change the anchor.
Args:
percent (float): the percentage by which we change the size.
|
625941bd8e7ae83300e4aeba
|
def test_address(test): <NEW_LINE> <INDENT> if hasattr(test, "address"): <NEW_LINE> <INDENT> return test.address() <NEW_LINE> <DEDENT> t = type(test) <NEW_LINE> file = module = call = None <NEW_LINE> if t == types.ModuleType: <NEW_LINE> <INDENT> file = getattr(test, '__file__', None) <NEW_LINE> module = getattr(test, '__name__', None) <NEW_LINE> return (src(file), module, call) <NEW_LINE> <DEDENT> if t == types.FunctionType or issubclass(t, type) or t == types.ClassType: <NEW_LINE> <INDENT> module = getattr(test, '__module__', None) <NEW_LINE> if module is not None: <NEW_LINE> <INDENT> m = sys.modules[module] <NEW_LINE> file = getattr(m, '__file__', None) <NEW_LINE> if file is not None: <NEW_LINE> <INDENT> file = os.path.abspath(file) <NEW_LINE> <DEDENT> <DEDENT> call = getattr(test, '__name__', None) <NEW_LINE> return (src(file), module, call) <NEW_LINE> <DEDENT> if t == types.InstanceType: <NEW_LINE> <INDENT> return test_address(test.__class__) <NEW_LINE> <DEDENT> if t == types.MethodType: <NEW_LINE> <INDENT> cls_adr = test_address(test.im_class) <NEW_LINE> return (src(cls_adr[0]), cls_adr[1], "%s.%s" % (cls_adr[2], test.__name__)) <NEW_LINE> <DEDENT> if isinstance(test, unittest.TestCase): <NEW_LINE> <INDENT> if (hasattr(test, '_FunctionTestCase__testFunc') or hasattr(test, '_testFunc')): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return test_address(test._FunctionTestCase__testFunc) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return test_address(test._testFunc) <NEW_LINE> <DEDENT> <DEDENT> cls_adr = test_address(test.__class__) <NEW_LINE> try: <NEW_LINE> <INDENT> method_name = test._TestCase__testMethodName <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> method_name = test._testMethodName <NEW_LINE> <DEDENT> return (src(cls_adr[0]), cls_adr[1], "%s.%s" % (cls_adr[2], method_name)) <NEW_LINE> <DEDENT> raise TypeError("I don't know what %s is (%s)" % (test, t))
|
Find the test address for a test, which may be a module, filename,
class, method or function.
|
625941bd85dfad0860c3ad47
|
def setattr(self, attr_name, *, mc_overwrite_property=False, mc_set_unknown=False, mc_force=False, mc_error_info_up_level=2, **env_values): <NEW_LINE> <INDENT> if attr_name[0] == '_': <NEW_LINE> <INDENT> msg = "Trying to set attribute '{}' on a config item. ".format(attr_name) <NEW_LINE> msg += ("Atributes starting with '_mc' are reserved for multiconf internal usage." if attr_name.startswith('_mc') else "Atributes starting with '_' cannot be set using item.setattr. Use assignment instead.") <NEW_LINE> self._mc_print_error_caller(msg, mc_error_info_up_level) <NEW_LINE> return <NEW_LINE> <DEDENT> cr = self._mc_root <NEW_LINE> env_factory = cr.env_factory <NEW_LINE> if cr._mc_check_unknown: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> env_factory.validate_env_group_names(env_values) <NEW_LINE> <DEDENT> except EnvException as ex: <NEW_LINE> <INDENT> self._mc_print_error_caller(str(ex), mc_error_info_up_level) <NEW_LINE> <DEDENT> <DEDENT> current_env = thread_local.env <NEW_LINE> try: <NEW_LINE> <INDENT> value, eg = env_factory._mc_resolve_env_group_value(current_env, env_values) <NEW_LINE> if eg is not None: <NEW_LINE> <INDENT> self._mc_setattr( current_env, attr_name, value, eg, mc_overwrite_property, mc_set_unknown, mc_force, mc_error_info_up_level + 1) <NEW_LINE> return <NEW_LINE> <DEDENT> if not env_values: <NEW_LINE> <INDENT> msg = "No Env or EnvGroup names specified." <NEW_LINE> self._mc_print_error_caller(msg, mc_error_info_up_level) <NEW_LINE> return <NEW_LINE> <DEDENT> self._mc_setattr( current_env, attr_name, MC_NO_VALUE, env_factory.eg_none, mc_overwrite_property, mc_set_unknown, False, mc_error_info_up_level + 1) <NEW_LINE> return <NEW_LINE> <DEDENT> except AmbiguousEnvException as ex: <NEW_LINE> <INDENT> msg = "Value for {env} is specified more than once, with no single most specific group or direct env:".format(env=current_env) <NEW_LINE> for eg in ex.ambiguous: <NEW_LINE> <INDENT> value = env_values[eg.name] <NEW_LINE> msg += "\nvalue: " + repr(value) + ", from: " + repr(eg) <NEW_LINE> <DEDENT> self._mc_print_error_caller(msg, mc_error_info_up_level)
|
Set env specific values for an attribute.
Arguments:
attr_name (str): The name of the attribute to set.
mc_overwrite_property (bool=False): Setting this to True allows overwriting a @property method with env specific values.
Any env for which the @property is not overridden will still get the value of the @property method.
mc_set_unknown (bool=False): This allows setting a property which was not defined in the __init__ method.
mc_force (bool=False): Force the value of the property regardless of the normal multiconf rules for assigning values.
This should be used with care, as normal validation is disabled. Using this could be a sign of bad configuration/modelling.
mc_error_info_up_level (int): Only for use if a class overrides setattr. You must add 1 each time it is overridden.
This is used for calculating the file:line info in case of errors.
**env_values (dict[env-name]->value): The env specific values to assign. Arg names must be valid env names from the EnvFactory used to
create the configuration.
|
625941bda17c0f6771cbdf41
|
def trajectoryDistances(self, poses): <NEW_LINE> <INDENT> dist = [0] <NEW_LINE> sort_frame_idx = sorted(poses.keys()) <NEW_LINE> for i in range(len(sort_frame_idx)-1): <NEW_LINE> <INDENT> cur_frame_idx = sort_frame_idx[i] <NEW_LINE> next_frame_idx = sort_frame_idx[i+1] <NEW_LINE> P1 = poses[cur_frame_idx] <NEW_LINE> P2 = poses[next_frame_idx] <NEW_LINE> dx = P1[0,3] - P2[0,3] <NEW_LINE> dy = P1[1,3] - P2[1,3] <NEW_LINE> dz = P1[2,3] - P2[2,3] <NEW_LINE> dist.append(dist[i]+np.sqrt(dx**2+dy**2+dz**2)) <NEW_LINE> <DEDENT> self.distance = dist[-1] <NEW_LINE> return dist
|
Compute the length of the trajectory
poses dictionary: [frame_idx: pose]
|
625941bd63b5f9789fde6fd3
|
def get_irow(self, i, *field_names): <NEW_LINE> <INDENT> res = [] <NEW_LINE> if not field_names: <NEW_LINE> <INDENT> field_names = self.value.keys() <NEW_LINE> <DEDENT> for field_name in field_names: <NEW_LINE> <INDENT> res.append(self.value[field_name][i]) <NEW_LINE> <DEDENT> return res
|
返回第i行字段名为field_names的数据,i从0开始算起
|
625941bd3d592f4c4ed1cf64
|
def export_model(model, export_model_dir, model_version ): <NEW_LINE> <INDENT> with tf.get_default_graph().as_default(): <NEW_LINE> <INDENT> last_conv_layer = model.get_layer('mixed10') <NEW_LINE> pool = model.get_layer('global_average_pooling2d_1') <NEW_LINE> tensor_info_input = tf.saved_model.utils.build_tensor_info(model.input) <NEW_LINE> tensor_info_output = tf.saved_model.utils.build_tensor_info(model.output) <NEW_LINE> tensor_pool_grads = tf.saved_model.utils.build_tensor_info(pool.output) <NEW_LINE> tensor_last_conv_layer = tf.saved_model.utils.build_tensor_info(last_conv_layer.output) <NEW_LINE> prediction_signature = ( tf.saved_model.signature_def_utils.build_signature_def( inputs={'se': tensor_info_input}, outputs={'pooled': tensor_pool_grads,'result':tensor_info_output,'conv': tensor_last_conv_layer}, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME ) ) <NEW_LINE> print('step1 => prediction_signature created successfully') <NEW_LINE> export_path_base = export_model_dir <NEW_LINE> export_path = os.path.join( tf.compat.as_bytes(export_path_base), tf.compat.as_bytes(str(model_version)) ) <NEW_LINE> builder = tf.saved_model.builder.SavedModelBuilder(export_path) <NEW_LINE> builder.add_meta_graph_and_variables( sess=K.get_session(), tags=[tf.saved_model.tag_constants.SERVING], signature_def_map={'prediction_signature': prediction_signature,}, ) <NEW_LINE> print('step2 => Export path(%s) ready to export trained model' % export_path, '\n starting to export model...') <NEW_LINE> builder.save(as_text=True) <NEW_LINE> print('Done exporting!')
|
:param export_model_dir: type string, save dir for exported model
:param model_version: type int best
:return:no return
|
625941bd293b9510aa2c3187
|
def test_client_can_obtain_production_url_as_base_url(): <NEW_LINE> <INDENT> client = AvataxClient('test app', 'ver 0.0', 'test machine') <NEW_LINE> assert client.base_url == 'https://rest.avatax.com'
|
Test the default option for base url is production url.
|
625941bdd10714528d5ffbcf
|
def _init_inverse_lookup(self): <NEW_LINE> <INDENT> logging.debug("First request of a reverse lookup. Building the " "inverse lookup dictionary.") <NEW_LINE> self._invlookup={} <NEW_LINE> for k, items in self._tree.iteritems(): <NEW_LINE> <INDENT> for item in items.position: <NEW_LINE> <INDENT> self._invlookup[item]=k <NEW_LINE> <DEDENT> <DEDENT> logging.log(ULTRADEBUG, "Done building inverse lookup dictionary.") <NEW_LINE> return
|
Sets up the internal data store to perform reverse lookups.
|
625941bd23849d37ff7b2f7f
|
def _on_cells_selection(self, added, removed): <NEW_LINE> <INDENT> items = list(self.items()) <NEW_LINE> indexes = self.table_view.selectionModel().selectedIndexes() <NEW_LINE> selected = [] <NEW_LINE> for index in indexes: <NEW_LINE> <INDENT> index = self.model.mapToSource(index) <NEW_LINE> obj = items[index.row()] <NEW_LINE> column_name = self.columns[index.column()].name <NEW_LINE> selected.append((obj, column_name)) <NEW_LINE> <DEDENT> self.setx(selected=selected) <NEW_LINE> self.ui.evaluate(self.factory.on_select, self.selected)
|
Handle the cells selection being changed.
|
625941bd796e427e537b04b1
|
def hasCycle(self, head): <NEW_LINE> <INDENT> if not head: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> slow, fast = head, head <NEW_LINE> while fast.next and fast.next.next: <NEW_LINE> <INDENT> slow , fast = slow.next, fast.next.next <NEW_LINE> if slow == fast: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
|
:type head: ListNode
:rtype: bool
|
625941bd66673b3332b91f7f
|
def translate(self, to_cipher=True): <NEW_LINE> <INDENT> if to_cipher: <NEW_LINE> <INDENT> return self.cipher.cipher() <NEW_LINE> <DEDENT> return self.cipher.decipher()
|
Ciphers or deciphers the currently loaded
cipher and returns the result.
|
625941bd1d351010ab855a0b
|
def VSIFCloseL(*args): <NEW_LINE> <INDENT> return _gdal.VSIFCloseL(*args)
|
VSIFCloseL(VSILFILE * arg1)
|
625941bd5fcc89381b1e15ab
|
def __init__(self, index, change): <NEW_LINE> <INDENT> self.index = index <NEW_LINE> self.change = change
|
Initialises Insert object.
Parameters
----------
index : int
Index of the node
change : ast
AST of inserted code
|
625941bdbaa26c4b54cb1011
|
def test_smoothing(self): <NEW_LINE> <INDENT> N = 500 <NEW_LINE> D = 2 <NEW_LINE> A0 = np.array([[.9, -.4], [.4, .9]]) <NEW_LINE> A1 = np.array([[.98, -.1], [.1, .98]]) <NEW_LINE> l = np.linspace(0, 1, N-1).reshape((-1,1,1)) <NEW_LINE> A = (1-l)*A0 + l*A1 <NEW_LINE> v = np.random.rand(D) <NEW_LINE> V = np.diag(v) <NEW_LINE> C = np.identity(D) <NEW_LINE> X = np.empty((N,D)) <NEW_LINE> Y = np.empty((N,D)) <NEW_LINE> x = np.array([0.5, -0.5]) <NEW_LINE> X[0,:] = x <NEW_LINE> Y[0,:] = x + np.random.multivariate_normal(np.zeros(D), C) <NEW_LINE> for n in range(N-1): <NEW_LINE> <INDENT> x = np.dot(A[n,:,:],x) + np.random.multivariate_normal(np.zeros(D), V) <NEW_LINE> X[n+1,:] = x <NEW_LINE> Y[n+1,:] = x + np.random.multivariate_normal(np.zeros(D), C) <NEW_LINE> <DEDENT> Xh = GaussianMarkovChain(np.zeros(D), np.identity(D), A, 1/v, n=N) <NEW_LINE> Yh = Gaussian(Xh, np.identity(D), plates=(N,)) <NEW_LINE> Yh.observe(Y) <NEW_LINE> Xh.update() <NEW_LINE> Xh_vb = Xh.u[0] <NEW_LINE> CovXh_vb = Xh.u[1] - Xh_vb[...,np.newaxis,:] * Xh_vb[...,:,np.newaxis] <NEW_LINE> V = N*(V,) <NEW_LINE> UY = Y <NEW_LINE> U = N*(C,) <NEW_LINE> (Xh, CovXh) = utils.kalman_filter(UY, U, A, V, np.zeros(D), np.identity(D)) <NEW_LINE> (Xh, CovXh) = utils.rts_smoother(Xh, CovXh, A, V) <NEW_LINE> self.assertTrue(np.allclose(Xh_vb, Xh)) <NEW_LINE> self.assertTrue(np.allclose(CovXh_vb, CovXh))
|
Test the posterior estimation of GaussianMarkovChain.
Create time-variant dynamics and compare the results of BayesPy VB
inference and standard Kalman filtering & smoothing.
This is not that useful anymore, because the moments are checked much
better in another test method.
|
625941bd26238365f5f0ed59
|
def set_pocket(self, card1, card2): <NEW_LINE> <INDENT> self.pocket = [card1, card2]
|
Bot.set_pocket(cards) -> None
Dealer provides bot with cards
|
625941bd4f88993c3716bf5a
|
def exception_to_validation_msg(e): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> error = json.loads(str(e)) <NEW_LINE> return error['error'].get('message', None) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> validation_patterns = [ "Remote error: \w* {'Error': '(.*?)'}", 'Remote error: \w* (.*?) \[', '400 Bad Request\n\nThe server could not comply with the request ' 'since it is either malformed or otherwise incorrect.\n\n (.*)', '(ParserError: .*)' ] <NEW_LINE> for pattern in validation_patterns: <NEW_LINE> <INDENT> match = re.search(pattern, str(e)) <NEW_LINE> if match: <NEW_LINE> <INDENT> return match.group(1)
|
Extracts a validation message to display to the user.
|
625941bd4c3428357757c218
|
def print(self, *msg): <NEW_LINE> <INDENT> for m in msg: <NEW_LINE> <INDENT> if self._current_train_progress is None: <NEW_LINE> <INDENT> print(m) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._current_train_progress.write(m) <NEW_LINE> <DEDENT> self.log_file.write(f'{m}\n') <NEW_LINE> <DEDENT> return self
|
Print log message without interfering the current `tqdm`
progress bar
|
625941bd8a43f66fc4b53f57
|
def teardown_zookeeper(self): <NEW_LINE> <INDENT> if not self.cluster[0].running: <NEW_LINE> <INDENT> self.cluster.start() <NEW_LINE> <DEDENT> tries = 0 <NEW_LINE> if self.client and self.client.connected: <NEW_LINE> <INDENT> while tries < 3: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.client.retry(self.client.delete, '/', recursive=True) <NEW_LINE> break <NEW_LINE> <DEDENT> except NotEmptyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> tries += 1 <NEW_LINE> <DEDENT> self.client.stop() <NEW_LINE> self.client.close() <NEW_LINE> del self.client <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> client = self._get_client() <NEW_LINE> client.start() <NEW_LINE> client.retry(client.delete, '/', recursive=True) <NEW_LINE> client.stop() <NEW_LINE> client.close() <NEW_LINE> del client <NEW_LINE> <DEDENT> for client in self._clients: <NEW_LINE> <INDENT> client.stop() <NEW_LINE> del client <NEW_LINE> <DEDENT> self._clients = None
|
Clean up any ZNodes created during the test
|
625941bdbde94217f3682ce3
|
def urldata_init(self, ud, d): <NEW_LINE> <INDENT> ud.proto = ud.parm.get('protocol', 'git') <NEW_LINE> ud.branch = ud.parm.get('branch', 'master') <NEW_LINE> ud.manifest = ud.parm.get('manifest', 'default.xml') <NEW_LINE> if not ud.manifest.endswith('.xml'): <NEW_LINE> <INDENT> ud.manifest += '.xml' <NEW_LINE> <DEDENT> ud.localfile = d.expand("repo_%s%s_%s_%s.tar.gz" % (ud.host, ud.path.replace("/", "."), ud.manifest, ud.branch))
|
We don"t care about the git rev of the manifests repository, but
we do care about the manifest to use. The default is "default".
We also care about the branch or tag to be used. The default is
"master".
|
625941bd7d847024c06be1a7
|
def backchain_to_goal_tree(rules, hypothesis): <NEW_LINE> <INDENT> raise NotImplementedError
|
Takes a hypothesis (string) and a list of rules (list
of IF objects), returning an AND/OR tree representing the
backchain of possible statements we may need to test
to determine if this hypothesis is reachable or not.
This method should return an AND/OR tree, that is, an
AND or OR object, whose constituents are the subgoals that
need to be tested. The leaves of this tree should be strings
(possibly with unbound variables), *not* AND or OR objects.
Make sure to use simplify(...) to flatten trees where appropriate.
|
625941bddc8b845886cb5422
|
def plugin_loaded(): <NEW_LINE> <INDENT> start_kernel()
|
The ST3 entry point for plugins.
|
625941bd21a7993f00bc7bda
|
def ck_add_s(x,str_add): <NEW_LINE> <INDENT> if x != 1: <NEW_LINE> <INDENT> return str(x) + ' ' + str_add + 's' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(x) + ' ' + str_add
|
add x infront of the str_add and
add 's' to the str_add if x ~! 1
|
625941bdd486a94d0b98e034
|
def delete_credentials(self): <NEW_LINE> <INDENT> Credentials.list_of_credentials.remove(self)
|
function that deletes credentials
|
625941bd23e79379d52ee455
|
def compose_left_right(left, right): <NEW_LINE> <INDENT> return lambda x: left(right(x))
|
Compose a pair of functions
|
625941bda934411ee3751586
|
def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False): <NEW_LINE> <INDENT> problem_ids = super(pxgo_account_chart_checker_problem, self).search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count) <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if arg[0] == 'wizard_id' and arg[1] == '=': <NEW_LINE> <INDENT> wizard_id = arg[2] <NEW_LINE> problems = self.browse(cr, uid, problem_ids, context=context) <NEW_LINE> problem_ids = [problem.id for problem in problems if problem.wizard_id.id == wizard_id] <NEW_LINE> <DEDENT> <DEDENT> return problem_ids
|
Redefinition of the search method (as osv_memory wizards currently don't
support domain filters by themselves.
|
625941bdd6c5a10208143f37
|
def on_idle(self, event): <NEW_LINE> <INDENT> state = self.state <NEW_LINE> if state.close_window.acquire(False): <NEW_LINE> <INDENT> self.state.app.ExitMainLoop() <NEW_LINE> <DEDENT> obj = None <NEW_LINE> while not state.object_queue.empty(): <NEW_LINE> <INDENT> obj = state.object_queue.get() <NEW_LINE> if isinstance(obj, SlipObject): <NEW_LINE> <INDENT> self.add_object(obj) <NEW_LINE> <DEDENT> if isinstance(obj, SlipPosition): <NEW_LINE> <INDENT> object = self.find_object(obj.key, obj.layer) <NEW_LINE> if object is not None: <NEW_LINE> <INDENT> object.update_position(obj) <NEW_LINE> if getattr(object, 'follow', False): <NEW_LINE> <INDENT> self.follow(object) <NEW_LINE> <DEDENT> state.need_redraw = True <NEW_LINE> <DEDENT> <DEDENT> if isinstance(obj, SlipDefaultPopup): <NEW_LINE> <INDENT> state.default_popup = obj <NEW_LINE> <DEDENT> if isinstance(obj, SlipInformation): <NEW_LINE> <INDENT> if obj.key in state.info: <NEW_LINE> <INDENT> state.info[obj.key].update(obj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> state.info[obj.key] = obj <NEW_LINE> <DEDENT> state.need_redraw = True <NEW_LINE> <DEDENT> if isinstance(obj, SlipCenter): <NEW_LINE> <INDENT> (lat,lon) = obj.latlon <NEW_LINE> state.panel.re_center(state.width/2, state.height/2, lat, lon) <NEW_LINE> state.need_redraw = True <NEW_LINE> <DEDENT> if isinstance(obj, SlipBrightness): <NEW_LINE> <INDENT> state.brightness = obj.brightness <NEW_LINE> state.need_redraw = True <NEW_LINE> <DEDENT> if isinstance(obj, SlipClearLayer): <NEW_LINE> <INDENT> if obj.layer in state.layers: <NEW_LINE> <INDENT> state.layers.pop(obj.layer) <NEW_LINE> <DEDENT> state.need_redraw = True <NEW_LINE> <DEDENT> if isinstance(obj, SlipRemoveObject): <NEW_LINE> <INDENT> for layer in state.layers: <NEW_LINE> <INDENT> if obj.key in state.layers[layer]: <NEW_LINE> <INDENT> state.layers[layer].pop(obj.key) <NEW_LINE> <DEDENT> <DEDENT> state.need_redraw = True <NEW_LINE> <DEDENT> if isinstance(obj, SlipHideObject): <NEW_LINE> <INDENT> for layer in state.layers: <NEW_LINE> <INDENT> if obj.key in state.layers[layer]: <NEW_LINE> <INDENT> state.layers[layer][obj.key].set_hidden(obj.hide) <NEW_LINE> <DEDENT> <DEDENT> state.need_redraw = True <NEW_LINE> <DEDENT> <DEDENT> if obj is None: <NEW_LINE> <INDENT> time.sleep(0.05)
|
prevent the main loop spinning too fast
|
625941bd379a373c97cfaa35
|
def get_rate_limit(): <NEW_LINE> <INDENT> method = 'GET' <NEW_LINE> path = '/open/api/v2/common/rate_limit' <NEW_LINE> url = '{}{}'.format(ROOT_URL, path) <NEW_LINE> params = {'api_key': API_KEY} <NEW_LINE> response = requests.request(method, url, params=params) <NEW_LINE> return response.json()
|
rate limit
|
625941bd5166f23b2e1a5048
|
def synchronize(self, timeout=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.queue.get(timeout=timeout) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None
|
Wait for receiving message with a common queue
Args:
timeout (int): timeout for waiting a message in seconds
Returns:
dict: a received message
|
625941bd8c0ade5d55d3e8ae
|
def clear(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> self._flag = False
|
Clear the internal flag.
|
625941bdb57a9660fec33770
|
@pytest.mark.parametrize( "wmts_capabilities, expected", [ ("simple", {"OSM": {"http://tile.openstreetmap.org/{zoom}/{x}/{y}.png"}}), ], indirect=["wmts_capabilities"], ) <NEW_LINE> def test_generate_tms_url(wmts_capabilities: wmtshelper.WMTSCapabilities, expected: Dict[str, str]): <NEW_LINE> <INDENT> for layer, expected_tms_url in expected.items(): <NEW_LINE> <INDENT> assert wmts_capabilities.get_tms_compatible_urls(layer) == expected_tms_url
|
Test generation of tms url for simpleProfileTile compatible layers
|
625941bd3eb6a72ae02ec3c4
|
def main(): <NEW_LINE> <INDENT> num = input() <NEW_LINE> print(fact(int(num)))
|
factorial of a number
|
625941bddc8b845886cb5423
|
def get_candlestick_24h(self): <NEW_LINE> <INDENT> return self.candlestick_24h
|
:return: 24h candlestick
|
625941bdd7e4931a7ee9de0b
|
def test_0010_single_payment_CASE2(self): <NEW_LINE> <INDENT> with Transaction().start(DB_NAME, USER, context=CONTEXT): <NEW_LINE> <INDENT> self.setup_defaults() <NEW_LINE> sale = self._create_sale( payment_authorize_on='manual', payment_capture_on='sale_confirm', ) <NEW_LINE> self.assertEqual(sale.total_amount, Decimal('200')) <NEW_LINE> self.assertEqual(sale.payment_total, Decimal('0')) <NEW_LINE> self.assertEqual(sale.payment_collected, Decimal('0')) <NEW_LINE> self.assertEqual(sale.payment_captured, Decimal('0')) <NEW_LINE> self.assertEqual(sale.payment_available, Decimal('0')) <NEW_LINE> self.assertEqual(sale.payment_authorized, Decimal('0')) <NEW_LINE> payment, = self.SalePayment.create([{ 'sale': sale.id, 'amount': Decimal('200'), 'gateway': self.dummy_gateway, 'payment_profile': self.dummy_cc_payment_profile.id, 'credit_account': self.party.account_receivable.id, }]) <NEW_LINE> self.assertEqual(sale.payment_total, Decimal('200')) <NEW_LINE> self.assertEqual(sale.payment_available, Decimal('200')) <NEW_LINE> self.assertEqual(sale.payment_collected, Decimal('0')) <NEW_LINE> self.assertEqual(sale.payment_captured, Decimal('0')) <NEW_LINE> self.assertEqual(sale.payment_authorized, Decimal('0')) <NEW_LINE> with Transaction().set_context(company=self.company.id): <NEW_LINE> <INDENT> self.Sale.quote([sale]) <NEW_LINE> self._confirm_sale_by_completing_payments([sale]) <NEW_LINE> <DEDENT> self.assertEqual(sale.payment_total, Decimal('200')) <NEW_LINE> self.assertEqual(sale.payment_available, Decimal('0')) <NEW_LINE> self.assertEqual(sale.payment_collected, Decimal('200')) <NEW_LINE> self.assertEqual(sale.payment_captured, Decimal('200')) <NEW_LINE> self.assertEqual(sale.payment_authorized, Decimal('0')) <NEW_LINE> with Transaction().set_context(company=self.company.id): <NEW_LINE> <INDENT> self._process_sale_by_completing_payments([sale]) <NEW_LINE> <DEDENT> self.assertEqual(sale.payment_total, Decimal('200')) <NEW_LINE> self.assertEqual(sale.payment_available, Decimal('0')) <NEW_LINE> self.assertEqual(sale.payment_collected, Decimal('200')) <NEW_LINE> self.assertEqual(sale.payment_captured, Decimal('200')) <NEW_LINE> self.assertEqual(sale.payment_authorized, Decimal('0'))
|
===================================
Total Sale Amount | $200
Payment Authorize On: | 'manual'
Payment Capture On: | 'sale_confirm'
===================================
Total Payment Lines | 1
Payment 1 | $200
===================================
|
625941bd442bda511e8be30b
|
def test_yy_no_visual_command(vim_bot): <NEW_LINE> <INDENT> main, editor_stack, editor, vim, qtbot = vim_bot <NEW_LINE> editor.stdkey_backspace() <NEW_LINE> editor.go_to_line(3) <NEW_LINE> editor.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) <NEW_LINE> cmd_line = vim.get_focus_widget() <NEW_LINE> qtbot.keyClicks(cmd_line, 'yy') <NEW_LINE> clipboard = QApplication.clipboard().text() <NEW_LINE> assert clipboard[:-1] == 'line 2'
|
Copy current line.
|
625941bd67a9b606de4a7dab
|
def begin_site(self): <NEW_LINE> <INDENT> for resource in self.site.content.walk_resources(): <NEW_LINE> <INDENT> if resource.source_file.kind == 'styl': <NEW_LINE> <INDENT> new_name = resource.source_file.name_without_extension + ".css" <NEW_LINE> target_folder = File(resource.relative_deploy_path).parent <NEW_LINE> resource.relative_deploy_path = target_folder.child(new_name)
|
Find all the styl files and set their relative deploy path.
|
625941bde8904600ed9f1e18
|
def serialize(self, root): <NEW_LINE> <INDENT> res = [] <NEW_LINE> stack = [] <NEW_LINE> stack.append(root) <NEW_LINE> while stack: <NEW_LINE> <INDENT> curr = stack.pop() <NEW_LINE> if curr: <NEW_LINE> <INDENT> res.append(curr.val) <NEW_LINE> if curr.right: <NEW_LINE> <INDENT> stack.append(curr.right) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stack.append(None) <NEW_LINE> res.append(None) <NEW_LINE> <DEDENT> if curr.left: <NEW_LINE> <INDENT> stack.append(curr.left) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stack.append(None) <NEW_LINE> res.append(None) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if len(stack) == 0: <NEW_LINE> <INDENT> return res
|
Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
|
625941bd63d6d428bbe443de
|
def age_dia_model(m, x): <NEW_LINE> <INDENT> return (x * 0.0) + m
|
given (intercept,slope), calculates predicted hgt assuming hgt=m[1]*x+m[0]
|
625941bdb5575c28eb68deed
|
def cli_host_uuid_error(): <NEW_LINE> <INDENT> cli_error('You must pass at least the host UUID to this command.')
|
This function is not exported, but used only inside this module.
|
625941bdcdde0d52a9e52f1f
|
def __wNoise_Power__(self,SC_Bandwidth): <NEW_LINE> <INDENT> wNoise_Power = (pow(10,(-70+10 * math.log10(SC_Bandwidth * 10e6))/10))/1000 <NEW_LINE> return wNoise_Power
|
求噪声功率
:param SC_Bandwidth: 子信道的带宽 MHZ
:return: 噪声功率 单位:w
|
625941bda219f33f3462885c
|
def test_031_item_insert(self): <NEW_LINE> <INDENT> self.cahandler.xdb_file = self.dir_path + '/ca/acme2certifier.xdb' <NEW_LINE> self.cahandler.issuing_ca_name = 'sub-ca' <NEW_LINE> item_dic = {'name': 'name', 'type': 2, 'source': 0, 'comment': 'comment'} <NEW_LINE> self.assertFalse(self.cahandler._item_insert(item_dic))
|
CAhandler._item_insert no date
|
625941bd57b8e32f52483389
|
def numberOfMatches(self, n: int) -> int: <NEW_LINE> <INDENT> dp=[0]*(n+1) <NEW_LINE> for i in range(1,n+1): <NEW_LINE> <INDENT> if i%2==0: <NEW_LINE> <INDENT> dp[i]=dp[i//2]+i//2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dp[i]=dp[(i-1)//2+1]+(i-1)//2 <NEW_LINE> <DEDENT> <DEDENT> return dp[n]
|
dp[i]表示n=i时,需要匹配的次数,则有
dp[1]=1
dp[2]=1
dp[i]=dp[i/2]+i/2 i为偶数
dp[i]=dp[(i-1/2)+1]+(i-1)/2 i为奇数
:param n:
:return:
|
625941bda05bb46b383ec713
|
def insert_new(self, record): <NEW_LINE> <INDENT> self.storage.append(record) <NEW_LINE> index = len(self.storage) <NEW_LINE> self.emit(SIGNAL('rowsInserted(QModelIndex, int, int)'), QModelIndex(), index, index) <NEW_LINE> return True
|
Метод для вставки новой записи в модель.
@type record: dict
@param record: Словарь с данными.
@rtype: boolean
@return: Результат выполнения операции.
|
625941bd099cdd3c635f0b4b
|
def ComputeMetrics(prob, batch_labels, p1, p2, rgb=None, save_path=None, ind=0): <NEW_LINE> <INDENT> GT = label(batch_labels.copy()) <NEW_LINE> PRED = PostProcess(prob, p1, p2) <NEW_LINE> lbl = GT.copy() <NEW_LINE> pred = PRED.copy() <NEW_LINE> aji = AJI_fast(lbl, pred) <NEW_LINE> lbl[lbl > 0] = 1 <NEW_LINE> pred[pred > 0] = 1 <NEW_LINE> l, p = lbl.flatten(), pred.flatten() <NEW_LINE> acc = accuracy_score(l, p) <NEW_LINE> roc = roc_auc_score(l, p) <NEW_LINE> jac = jaccard_similarity_score(l, p) <NEW_LINE> f1 = f1_score(l, p) <NEW_LINE> recall = recall_score(l, p) <NEW_LINE> precision = precision_score(l, p) <NEW_LINE> if rgb is not None: <NEW_LINE> <INDENT> xval_n = join(save_path, "xval_{}.png").format(ind) <NEW_LINE> yval_n = join(save_path, "yval_{}.png").format(ind) <NEW_LINE> prob_n = join(save_path, "prob_{}.png").format(ind) <NEW_LINE> pred_n = join(save_path, "pred_{}.png").format(ind) <NEW_LINE> c_gt_n = join(save_path, "C_gt_{}.png").format(ind) <NEW_LINE> c_pr_n = join(save_path, "C_pr_{}.png").format(ind) <NEW_LINE> imsave(xval_n, rgb) <NEW_LINE> imsave(yval_n, color_bin(GT)) <NEW_LINE> imsave(prob_n, prob) <NEW_LINE> imsave(pred_n, color_bin(PRED)) <NEW_LINE> imsave(c_gt_n, add_contours(rgb, GT)) <NEW_LINE> imsave(c_pr_n, add_contours(rgb, PRED)) <NEW_LINE> <DEDENT> return acc, roc, jac, recall, precision, f1, aji
|
Computes all metrics between probability map and corresponding label.
If you give also an rgb image it will save many extra meta data image.
|
625941bd9f2886367277a77f
|
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, StorageExistResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
|
Returns true if both objects are equal
|
625941bd91af0d3eaac9b905
|
def __init__(self, **kwargs): <NEW_LINE> <INDENT> param_defaults = { 'Status': None, 'Message': None, 'Reason': None, 'Details': None, 'Code': None} <NEW_LINE> for (param, default) in param_defaults.iteritems(): <NEW_LINE> <INDENT> setattr(self, param, kwargs.get(param, default)) <NEW_LINE> <DEDENT> super(Status, self).__init__(**kwargs)
|
An object to hold a Kubernete Status.
Arg:
Status:
One of: "Success", "Failure", "Working" (for operations not yet completed)
Message:
A human-readable description of the status of this operation.
Reason:
A machine-readable description of why this operation is in the
"Failure" or "Working" status. If this value is empty there
is no information available. A Reason clarifies an HTTP status
code but does not override it.
Details:
Extended data associated with the reason. Each reason may define its
own extended details. This field is optional and the data returned
is not guaranteed to conform to any schema except that defined by
the reason type.
Code:
Suggested HTTP return code for this status, 0 if not set.
|
625941bd8e71fb1e9831d69a
|
def testCopyNodeFailure(self): <NEW_LINE> <INDENT> self._task.set_default("stderr", False) <NEW_LINE> dest = make_temp_filename(suffix='LocalhostCopyF') <NEW_LINE> worker = self._task.copy("/etc/hosts", dest, nodes='unlikely-node,localhost') <NEW_LINE> self.assert_(worker != None) <NEW_LINE> self._task.resume() <NEW_LINE> self.assert_(worker.node_error_buffer("unlikely-node") is None) <NEW_LINE> self.assert_(len(worker.node_buffer("unlikely-node")) > 2) <NEW_LINE> os.unlink(dest) <NEW_LINE> self._task.set_default("stderr", True) <NEW_LINE> try: <NEW_LINE> <INDENT> dest = make_temp_filename(suffix='LocalhostCopyF2') <NEW_LINE> worker = self._task.copy("/etc/hosts", dest, nodes='unlikely-node,localhost') <NEW_LINE> self.assert_(worker != None) <NEW_LINE> self._task.resume() <NEW_LINE> self.assert_(worker.node_buffer("unlikely-node") is None) <NEW_LINE> self.assert_(len(worker.node_error_buffer("unlikely-node")) > 2) <NEW_LINE> os.unlink(dest) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._task.set_default("stderr", False)
|
test node failure error handling on simple copy
|
625941bd442bda511e8be30c
|
def feed_data(self, data_point): <NEW_LINE> <INDENT> self._cur_timestamp = data_point['EventTimestamp(ns)'] <NEW_LINE> acc_x = data_point['AccelX'] <NEW_LINE> acc_y = data_point['AccelY'] <NEW_LINE> acc_z = data_point['AccelZ'] <NEW_LINE> activity_type = data_point['Activity'] <NEW_LINE> updated = self._model.process_data(acc_x, acc_y, acc_z) <NEW_LINE> if updated > 0: <NEW_LINE> <INDENT> self._probs = self._model.get_probs() <NEW_LINE> self._model_predict = np.argmax(self._probs) <NEW_LINE> self._predcit_activity = self._model.get_type() <NEW_LINE> self._res = { 'EventTimestamp(ns)': self._cur_timestamp, 'Activity': activity_type, 'Prob0': self._probs[0], 'Prob1': self._probs[1], 'Prob2': self._probs[2], 'Prob3': self._probs[3], 'Prob4': self._probs[4], 'Prob5': self._probs[5], 'Predict': self._model_predict, 'PredictActivity': self._predcit_activity } <NEW_LINE> <DEDENT> return (updated > 0)
|
main function processes data and count steps
|
625941bd30c21e258bdfa38a
|
def __repr__(self): <NEW_LINE> <INDENT> return "{}({}, {})".format(self.__class__.__name__, self.__x, self.__y)
|
Returns the representational form of an object
|
625941bd07f4c71912b11376
|
def test_clone_alert(self): <NEW_LINE> <INDENT> pass
|
Test case for clone_alert
Clones the specified alert # noqa: E501
|
625941bd097d151d1a222d4b
|
def createSelectBox(self, buttonText, labelText): <NEW_LINE> <INDENT> button1 = QPushButton(buttonText) <NEW_LINE> button1.setMinimumWidth(220) <NEW_LINE> button1.setMaximumWidth(220) <NEW_LINE> button2 = QPushButton("Edit") <NEW_LINE> button2.setMinimumWidth(100) <NEW_LINE> button2.setMaximumWidth(100) <NEW_LINE> label = QLabel(labelText) <NEW_LINE> box = QHBoxLayout() <NEW_LINE> box.addWidget(button1) <NEW_LINE> box.addWidget(button2) <NEW_LINE> box.addStretch(1) <NEW_LINE> box.addWidget(label) <NEW_LINE> return (box, button1, button2, label)
|
Creates a Layout containing 2 buttons and a Label
The first button allows the user to "Select" from file
The second button allows the user to "Edit" currently selected file
@param buttonText The text on the first button
@param labelText The text on the label
@return (layout, button1, button2, label) as a tuple
|
625941bd63d6d428bbe443df
|
def create_smooth(fwhm=6, name='smooth'): <NEW_LINE> <INDENT> smooth = pe.Node(interface=spm.Smooth(), name=name) <NEW_LINE> smooth.inputs.fwhm = fwhm <NEW_LINE> return smooth
|
Smooth the functional data using
:class:`nipype.interfaces.spm.Smooth`.
|
625941bd8e7ae83300e4aebb
|
def forward(self, src, src_key_padding_mask=None): <NEW_LINE> <INDENT> output = super().forward(src, src_key_padding_mask=src_key_padding_mask) <NEW_LINE> return output
|
Arguments:
----------
- `src` of shape (B, T, E)
- `src_key_padding_mask` of shape (B, T)
Outputs:
--------
- output of shape (B, T, E)
|
625941bd8da39b475bd64e60
|
def validate_params(r_param_valid_list, g_params): <NEW_LINE> <INDENT> import re <NEW_LINE> if not r_param_valid_list: <NEW_LINE> <INDENT> return Ret() <NEW_LINE> <DEDENT> for r_param_valid in r_param_valid_list: <NEW_LINE> <INDENT> valid_method = None <NEW_LINE> process = None <NEW_LINE> if isinstance(r_param_valid, str): <NEW_LINE> <INDENT> r_param = r_param_valid <NEW_LINE> <DEDENT> elif isinstance(r_param_valid, tuple): <NEW_LINE> <INDENT> if not r_param_valid: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> r_param = r_param_valid[0] <NEW_LINE> if len(r_param_valid) > 1: <NEW_LINE> <INDENT> valid_method = r_param_valid[1] <NEW_LINE> if len(r_param_valid) > 2: <NEW_LINE> <INDENT> g_params.setdefault(r_param, r_param_valid[2]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif isinstance(r_param_valid, dict): <NEW_LINE> <INDENT> r_param = r_param_valid.get('value', None) <NEW_LINE> if r_param is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> valid_method = r_param_valid.get('func', None) <NEW_LINE> default = r_param_valid.get('default', False) <NEW_LINE> default_value = r_param_valid.get('default_value', None) <NEW_LINE> if default: <NEW_LINE> <INDENT> g_params.setdefault(r_param, default_value) <NEW_LINE> <DEDENT> process = r_param_valid.get('process', None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if r_param not in g_params: <NEW_LINE> <INDENT> return Ret(Error.REQUIRE_PARAM, append_msg=r_param) <NEW_LINE> <DEDENT> req_value = g_params[r_param] <NEW_LINE> if isinstance(valid_method, str): <NEW_LINE> <INDENT> if re.match(valid_method, req_value) is None: <NEW_LINE> <INDENT> return Ret(Error.ERROR_PARAM_FORMAT, append_msg=r_param) <NEW_LINE> <DEDENT> <DEDENT> elif callable(valid_method): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret = valid_method(req_value) <NEW_LINE> if ret.error is not Error.OK: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> deprint(str(err)) <NEW_LINE> return Ret(Error.ERROR_VALIDATION_FUNC) <NEW_LINE> <DEDENT> <DEDENT> if process is not None and callable(process): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> g_params[r_param] = process(req_value) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> deprint(str(err)) <NEW_LINE> return Ret(Error.ERROR_PROCESS_FUNC) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return Ret(Error.OK, g_params)
|
验证参数
[
('a', '[a-z]+'),
'b',
('c', valid_c_func),
('d', valid_d_func, default_d_value)
{
"value": "e",
"func": valid_e_func,
"default": True,
"default_value": default_e_value,
"process": process_e_value (str to int)
}
]
|
625941bd9b70327d1c4e0cc3
|
def _set_state(self, brightness=None, powered=None): <NEW_LINE> <INDENT> new_state = {} <NEW_LINE> if brightness is not None: <NEW_LINE> <INDENT> new_state['brightness'] = brightness <NEW_LINE> <DEDENT> if powered is not None: <NEW_LINE> <INDENT> new_state['powered'] = powered <NEW_LINE> <DEDENT> self.update(dict(desired_state=new_state))
|
Change the devices state
|
625941bd8c3a8732951582a7
|
def get_game_root(): <NEW_LINE> <INDENT> path = os.getcwd().replace("\\", "/") <NEW_LINE> if "floobits" in path or "PycharmProjects" in path: <NEW_LINE> <INDENT> path_parts = path.split("/") <NEW_LINE> path = path_parts[0] + "/" + path_parts[1] + "/" + path_parts[ 2] + "/Desktop/Auden Pres" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = path[:path.rfind("/")] <NEW_LINE> <DEDENT> return path + "/"
|
Gets the path to the root folder of the game
|
625941bd4e4d5625662d42cb
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.