code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def save_book_to_database(self, session=None, tables=None, initializers=None, mapdicts=None, auto_commit=True, **keywords): <NEW_LINE> <INDENT> params = self.get_params(**keywords) <NEW_LINE> params['dest_session'] = session <NEW_LINE> params['dest_tables'] = tables <NEW_LINE> params['dest_initializers'] = initializers <NEW_LINE> params['dest_mapdicts'] = mapdicts <NEW_LINE> params['dest_auto_commit'] = auto_commit <NEW_LINE> pe.save_book_as(**params)
Save a book into database :param session: a SQLAlchemy session :param tables: a list of database tables :param initializers: a list of model initialization functions. :param mapdicts: a list of explicit table column names if your excel data sheets do not have the exact column names :param keywords: additional keywords to :meth:`pyexcel.Book.save_to_database`
625941bf9c8ee82313fbb6ba
def get_gam_teams(self): <NEW_LINE> <INDENT> endpoint = GAMEndpoint.TEAM.value <NEW_LINE> return self._get(url=self._build_url(endpoint))
GET /central/gam/team :return: Response object :rtype: requests.Response
625941bf0c0af96317bb812e
def voigt(x, x0, sigma, gamma): <NEW_LINE> <INDENT> return np.real(wofz(((x - x0) + 1j*gamma) / sigma / np.sqrt(2)))
Voigt function as model for the peaks. Calculated numerically with the complex errorfunction wofz (https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.special.wofz.html)
625941bf283ffb24f3c55849
def get(self, index: int) -> int: <NEW_LINE> <INDENT> node = self.get_node(index) <NEW_LINE> if node: <NEW_LINE> <INDENT> return node.val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -1
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
625941bf0fa83653e4656f02
def got_raw(self, port_agent_packet): <NEW_LINE> <INDENT> self.publish_raw(port_agent_packet)
Called by the port agent client when raw data is available, such as data sent by the driver to the instrument, the instrument responses,etc. :param port_agent_packet: raw data from instrument
625941bf30dc7b76659018af
def piston_speed(t): <NEW_LINE> <INDENT> return - stroke / 2 * 2 * np.pi * f * np.sin(crank_angle(t))
Approximate piston speed with sinusoidal velocity profile
625941bf50812a4eaa59c26a
def test_check_json_loading(self): <NEW_LINE> <INDENT> with open("file.json") as f: <NEW_LINE> <INDENT> dic = json.load(f) <NEW_LINE> self.assertEqual(isinstance(dic, dict), True)
Checks if FileStorage works.
625941bf9b70327d1c4e0d1a
def spectrum(N, flux): <NEW_LINE> <INDENT> spectra = pickle.load( open("E_spectra.p", "rb"), encoding='latin1') <NEW_LINE> es = linspace(12, 100, N + 1) <NEW_LINE> fs = interp(es, spectra[:, 0], spectra[:, 1]) <NEW_LINE> Es = [(x[0] + x[1]) / 2 for x in zip(es[:-1], es[1:])] <NEW_LINE> Fs = [(x[0] + x[1]) / 2 for x in zip(fs[:-1], fs[1:])] <NEW_LINE> ESminus = [x[1] - x[0] for x in zip(es[:-1], es[1:])] <NEW_LINE> Is = [x[0] * x[1] for x in zip(Fs, ESminus)] <NEW_LINE> Is = array(Is) <NEW_LINE> Is = Is / Is.sum() <NEW_LINE> Is = Is * flux <NEW_LINE> return Es, Is
create simulated spectrum at N points flux param can be thought of as number of emitted photons
625941bf4a966d76dd550f53
def test_iter_events(): <NEW_LINE> <INDENT> event1 = e.event(p.identifier('local', 'id1', 'event'), 'tyyppi1', '2012-12-12T12:12:12', 'detaili1') <NEW_LINE> event2 = e.event(p.identifier('local', 'id2', 'event'), 'tyyppi2', '2012-12-12T12:12:12', 'detaili2') <NEW_LINE> event3 = e.event(p.identifier('local', 'id3', 'event'), 'tyyppi3', '2012-12-12T12:12:12', 'detaili2') <NEW_LINE> premisroot = p.premis(child_elements=[event1, event2, event3]) <NEW_LINE> i = 0 <NEW_LINE> for event in e.iter_events(premisroot): <NEW_LINE> <INDENT> i = i + 1 <NEW_LINE> assert e.parse_event_type(event) == 'tyyppi' + six.text_type(i) <NEW_LINE> <DEDENT> assert i == 3
Test iter_events
625941bf3c8af77a43ae36e4
def enable_delivery_confirmations(self): <NEW_LINE> <INDENT> self.LOGGER.debug("Issuing Confirm.Select RPC command") <NEW_LINE> self._channel.confirm_delivery(self.on_delivery_confirmation)
Send the Confirm.Select RPC method to RabbitMQ to enable delivery confirmations on the channel. The only way to turn this off is to close the channel and create a new one. When the message is confirmed from RabbitMQ, the on_delivery_confirmation method will be invoked passing in a Basic.Ack or Basic.Nack method from RabbitMQ that will indicate which messages it is confirming or rejecting.
625941bf99cbb53fe6792b2d
def enable_search(self): <NEW_LINE> <INDENT> if self.search_edit.text(): <NEW_LINE> <INDENT> self.search_action.setEnabled(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.search_action.setEnabled(False)
Enable/disable the 'Search' action.
625941bf4f88993c3716bfb0
def terminado(juego): <NEW_LINE> <INDENT> if juego[0][0] == "T": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Devuelve True si el juego terminó, es decir no se pueden agregar nuevas piezas, o False si se puede seguir jugando.
625941bf099cdd3c635f0ba2
def del_tool(self): <NEW_LINE> <INDENT> select = self.list_b.curselection() <NEW_LINE> if not select: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> index = select[0] <NEW_LINE> item = self.list_b.get(index) <NEW_LINE> item_list = list(filter(is_not_null, item.split(" "))) <NEW_LINE> print("item_list=%s " % (str(item_list))) <NEW_LINE> msg = "型号:%s\n插件中心:%s\n插件名称:%s\n过期时间:%s\n" % (item_list[0], item_list[1], item_list[2], item_list[3]) <NEW_LINE> if not messagebox.askyesno("删除确认", "工具信息:\n" + msg + "\n" + "确定删除?", parent=self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> result = sign_tool.del_tool(item_list[0], item_list[1], item_list[2], item_list[3]) <NEW_LINE> if not result: <NEW_LINE> <INDENT> messagebox.showerror("删除失败", msg, parent=self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> messagebox.showinfo("删除成功", msg, parent=self) <NEW_LINE> self.flush_list_b() <NEW_LINE> <DEDENT> return True
"删除"签名工具 按钮执行函数
625941bf4527f215b584c3a0
def print_weighted_distance(graph_map, direct_distance_map, current_node, nodes_list): <NEW_LINE> <INDENT> if len(nodes_list) != 0: <NEW_LINE> <INDENT> shortest_node = nodes_list[0] <NEW_LINE> shortest_distance = graph_map[current_node][shortest_node] + direct_distance_map[shortest_node] <NEW_LINE> for n in nodes_list: <NEW_LINE> <INDENT> print(n, ": w(", current_node, ",", n, ") + dd(", n, ") = ", graph_map[current_node][n], "+", direct_distance_map[n], "=", graph_map[current_node][n] + direct_distance_map[n]) <NEW_LINE> if graph_map[current_node][n] + direct_distance_map[n] < shortest_distance: <NEW_LINE> <INDENT> shortest_distance = graph_map[current_node][n] + direct_distance_map[n] <NEW_LINE> shortest_node = n <NEW_LINE> <DEDENT> <DEDENT> return shortest_node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Print all adjacent nodes' direct distance, then return the shortest node.
625941bf10dbd63aa1bd2aec
def update(self): <NEW_LINE> <INDENT> date = datetime.date(year=2018, month=1, day=1) <NEW_LINE> out_str = self.text[0].text() <NEW_LINE> d_day = datetime.date.today() - date + datetime.timedelta(days=1) <NEW_LINE> date = date.strftime('%y%m%d') <NEW_LINE> d_day = d_day.days <NEW_LINE> out_str += '%s %s ' %(d_day, date) <NEW_LINE> if self.checker[1].isChecked(): <NEW_LINE> <INDENT> wdays = '월화수목금토일' <NEW_LINE> out_str += wdays[datetime.date.today().weekday()] <NEW_LINE> <DEDENT> out_str += '\n' <NEW_LINE> if self.checker[0].isChecked(): <NEW_LINE> <INDENT> out_str += '\n' <NEW_LINE> <DEDENT> out_str += '%s%s\n' %(self.text[1].text(), '건강한 삶') <NEW_LINE> if self.checker[0].isChecked(): <NEW_LINE> <INDENT> out_str += '\n' <NEW_LINE> <DEDENT> out_str += self.text[2].text() + '\n' <NEW_LINE> action_list = [['운동', 1, 7], ['식단기록', 0, 22]] <NEW_LINE> for action in action_list: <NEW_LINE> <INDENT> idx = action_list.index(action) <NEW_LINE> out_str += '%s%d / %d\n' %(action[0], action[1], action[2]) <NEW_LINE> <DEDENT> if self.checker[0].isChecked(): <NEW_LINE> <INDENT> out_str += '\n' <NEW_LINE> <DEDENT> out_str += self.text[3].text() <NEW_LINE> calory_list = [2200, 1900] <NEW_LINE> if self.checker[2].isChecked(): <NEW_LINE> <INDENT> out_str += '%dkcal (%s)' %(calory_list[0], calory_list[1] - calory_list[0]) <NEW_LINE> <DEDENT> out_str += '\n' <NEW_LINE> meal_list = [['아침', '스무디'], ['점심', '된장찌개정식'], ['저녁', '닭가슴살 샐러드']] <NEW_LINE> for meal in meal_list: <NEW_LINE> <INDENT> out_str += '- %s : %s\n' %(meal[0], meal[1]) <NEW_LINE> <DEDENT> if self.checker[0].isChecked(): <NEW_LINE> <INDENT> out_str += '\n' <NEW_LINE> <DEDENT> out_str += self.text[4].text() + '\n' <NEW_LINE> deed_list = [[16, '배가 고팠지만 간식을 잘 참았다.']] <NEW_LINE> for deed in deed_list: <NEW_LINE> <INDENT> out_str += '%d. %s\n' %(deed[0], deed[1]) <NEW_LINE> <DEDENT> self.preview_text.setText(out_str)
미리보기를 업데이트한다
625941bf851cf427c661a458
def delete_by_person_id(self,person_id): <NEW_LINE> <INDENT> for p in list(self.get_all())[:]: <NEW_LINE> <INDENT> if p.person_id==person_id: <NEW_LINE> <INDENT> self.__participation_repository.delete_by_id(p.entity_id)
Delete a participation by the person id.
625941bffb3f5b602dac35d7
def test_host_domain_invalid_host_should_return_none(self): <NEW_LINE> <INDENT> sf = SpiderFoot(self.default_options) <NEW_LINE> host_domain = sf.hostDomain(None, sf.opts.get('_internettlds')) <NEW_LINE> self.assertEqual(None, host_domain)
Test hostDomain(self, hostname, tldList)
625941bf627d3e7fe0d68d95
def test_parent_validity(self): <NEW_LINE> <INDENT> V = GaussianARD(1, 1) <NEW_LINE> X = Gaussian(np.ones(1), np.identity(1)) <NEW_LINE> Y = Gaussian(np.ones(3), np.identity(3)) <NEW_LINE> Z = Gaussian(np.ones(5), np.identity(5)) <NEW_LINE> A = SumMultiply(X, ['i']) <NEW_LINE> self.assertEqual(A.dims, ((), ())) <NEW_LINE> A = SumMultiply('i', X) <NEW_LINE> self.assertEqual(A.dims, ((), ())) <NEW_LINE> A = SumMultiply(X, ['i'], ['i']) <NEW_LINE> self.assertEqual(A.dims, ((1,), (1,1))) <NEW_LINE> A = SumMultiply('i->i', X) <NEW_LINE> self.assertEqual(A.dims, ((1,), (1,1))) <NEW_LINE> A = SumMultiply(X, ['i'], Y, ['j'], ['i','j']) <NEW_LINE> self.assertEqual(A.dims, ((1,3), (1,3,1,3))) <NEW_LINE> A = SumMultiply('i,j->ij', X, Y) <NEW_LINE> self.assertEqual(A.dims, ((1,3), (1,3,1,3))) <NEW_LINE> A = SumMultiply(V, [], X, ['i'], Y, ['i'], []) <NEW_LINE> self.assertEqual(A.dims, ((), ())) <NEW_LINE> A = SumMultiply(',i,i->', V, X, Y) <NEW_LINE> self.assertEqual(A.dims, ((), ())) <NEW_LINE> self.assertRaises(ValueError, SumMultiply) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, X) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, Y, ['i', 'j']) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, 'ij', Y) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, Y, ['i'], Z, ['i']) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, 'i,i', Y, Z) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, X, ['i'], ['j']) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, 'i->j', X) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, X, ['i','i']) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, 'ii', X) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, X, ['i'], ['i','i']) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, 'i->ii', X) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, 'i->i->i', X) <NEW_LINE> self.assertRaises(ValueError, SumMultiply, 'i,i->i', X)
Test that the parent nodes are validated properly in SumMultiply
625941bfb57a9660fec337c8
def testComputation_8(self): <NEW_LINE> <INDENT> (w,h) = self.im8_1.getSize() <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> xi = random.randint(1,w//2-1) <NEW_LINE> yi = random.randint(1,h//2-1) <NEW_LINE> wi = random.randint(0,255) <NEW_LINE> for vect in self.directions: <NEW_LINE> <INDENT> self.im8_1.fill(255) <NEW_LINE> self.im8_1.setPixel(wi, (w//2,h//2)) <NEW_LINE> self.im8_2.fill(255) <NEW_LINE> self.im8_2.setPixel(wi, (w//2,h//2)) <NEW_LINE> self.im8_2.setPixel(wi, (w//2+xi*vect[0],h//2+yi*vect[1])) <NEW_LINE> infVector(self.im8_1, self.im8_1, (xi*vect[0],yi*vect[1]), edge=FILLED) <NEW_LINE> (x,y) = compare(self.im8_2, self.im8_1, self.im8_3) <NEW_LINE> self.assertTrue(x<0)
Tests infimum by vector computations on greyscale images
625941bf94891a1f4081b9ee
def _get_signatures(self): <NEW_LINE> <INDENT> t_signatures = {i: {} for i in range(len(self.edges) - 1)} <NEW_LINE> w_signatures = {i: 0 for i in range(len(self.edges) - 1)} <NEW_LINE> for neigh, ts in self.times.items(): <NEW_LINE> <INDENT> sgn_ts = np.digitize(ts, self.edges, True) - 1 <NEW_LINE> for t, sgn in zip(ts, sgn_ts): <NEW_LINE> <INDENT> t_signatures[sgn].setdefault(neigh, []).append(t) <NEW_LINE> w_signatures[sgn] += 1 <NEW_LINE> <DEDENT> <DEDENT> self.total_letters = sum(w_signatures.values()) <NEW_LINE> w_signatures = {k: w/self.total_letters for k, w in w_signatures.items()} <NEW_LINE> t_signatures = {k: self._create_signature(v) for k, v in t_signatures.items()} <NEW_LINE> self.w_signatures = w_signatures <NEW_LINE> self.t_signatures = t_signatures
Calculate social signatures for each bin
625941bfa8ecb033257d3014
def test_get_changenum3(self): <NEW_LINE> <INDENT> s = "1, 2, 3" <NEW_LINE> result = poker.get_changenum(s) <NEW_LINE> self.assertEqual(set(result), {"1", "2", "3"})
ポーカーの交換カードの指定番号取得テスト3
625941bf462c4b4f79d1d616
def parse_product(soup): <NEW_LINE> <INDENT> result = dict() <NEW_LINE> product_name = soup.select_one('h1.desc_product_name').text <NEW_LINE> result['raw_name'] = product_name <NEW_LINE> result['supplier'], result['name'], result['weight'] = parse_name(product_name) <NEW_LINE> result['description'] = soup.select_one('p.desc_bt_txt').text if soup.select_one('p.desc_bt_txt') else '' <NEW_LINE> result['thumbnail_url1'] = soup.select_one('div.image_top > img').get('src') <NEW_LINE> for index, img in enumerate(soup.select('a.top_thumb > img'), start=2): <NEW_LINE> <INDENT> result[f'thumbnail_url{index}'] = img.get('src') <NEW_LINE> <DEDENT> origin_price = soup.select_one('del.origin-price') <NEW_LINE> sale_price = int(soup.select_one('strong.sale-price').text[:-1].replace(',', '')) <NEW_LINE> result['sale_price'] = sale_price <NEW_LINE> if origin_price is not None: <NEW_LINE> <INDENT> price = int(soup.select_one('del.origin-price').text[:-1].replace(',', '')) <NEW_LINE> result['price'] = price <NEW_LINE> result['discount_rate'] = round((1 - sale_price / price) * 100) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result['price'] = 0 <NEW_LINE> result['discount_rate'] = 0 <NEW_LINE> <DEDENT> details = soup.select('table.table_detail_info > tbody > tr') <NEW_LINE> for detail in details: <NEW_LINE> <INDENT> if detail.select_one('th').text == '식품의 유형': <NEW_LINE> <INDENT> result['type'] = detail.select_one('td').text <NEW_LINE> <DEDENT> elif detail.select_one('th').text == '원재료명 및 함량': <NEW_LINE> <INDENT> result['materials'] = detail.select_one('td').text <NEW_LINE> <DEDENT> elif detail.select_one('th').text == '알레르기 유발물질': <NEW_LINE> <INDENT> result['alert_allergy'] = detail.select_one('td').text <NEW_LINE> <DEDENT> <DEDENT> result['stock'] = 10 <NEW_LINE> result['available'] = True <NEW_LINE> details = soup.select('dl.desc_info > dt') <NEW_LINE> for i, detail in enumerate(details): <NEW_LINE> <INDENT> if detail.text == '적립금': <NEW_LINE> <INDENT> result['point_amount'] = soup.select_one(f'dl.desc_info > dd:nth-of-type({i+1})').text[:-1].replace(',', '') <NEW_LINE> <DEDENT> elif detail.text == '배송타입': <NEW_LINE> <INDENT> result['delivery_type'] = soup.select_one(f'dl.desc_info > dd:nth-of-type({i+1})').text.strip() <NEW_LINE> <DEDENT> elif detail.text == '수령요일': <NEW_LINE> <INDENT> result['delivery_days'] = soup.select_one('dl.desc_info > dd > strong').text <NEW_LINE> <DEDENT> <DEDENT> print(result) <NEW_LINE> return result
반찬 상세 페이지에서 Product 인스턴스를 만들기 위한 정보 크롤링 :param soup: 상세 페이지의 BeautifulSoup 인스턴스 :return result: 크롤링한 정보를 저장한 딕셔너리 인스턴스
625941bff7d966606f6a9f48
def teardown(self): <NEW_LINE> <INDENT> for dev in self.devices: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dev.ui.stop_workload() <NEW_LINE> <DEDENT> except (UICmdException, ToolException) as err: <NEW_LINE> <INDENT> self.class_logger.debug("Error on workload teardown" " on device {0}: {1}".format(dev.name, err)) <NEW_LINE> raise
Stop the workload.
625941bf63b5f9789fde702b
def getoutput(cmd): <NEW_LINE> <INDENT> with AvoidUNCPath() as path: <NEW_LINE> <INDENT> if path is not None: <NEW_LINE> <INDENT> cmd = '"pushd %s &&"%s' % (path, cmd) <NEW_LINE> <DEDENT> out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT) <NEW_LINE> <DEDENT> if out is None: <NEW_LINE> <INDENT> out = b'' <NEW_LINE> <DEDENT> return py3compat.bytes_to_str(out)
Return standard output of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- stdout : str
625941bf435de62698dfdb92
def gdxDataWriteRawStart(pgdx, SyId, ExplTxt, Dimen, Typ, UserInfo): <NEW_LINE> <INDENT> return _gdxcc.gdxDataWriteRawStart(pgdx, SyId, ExplTxt, Dimen, Typ, UserInfo)
gdxDataWriteRawStart(pgdx, SyId, ExplTxt, Dimen, Typ, UserInfo) -> int
625941bf30bbd722463cbd0a
def draw_rectangle(img, x, y, w, h): <NEW_LINE> <INDENT> cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
Draw a rectangle from (x,y) with width and height :param img: the base image :param x: start of rectangle :param y: start of rectangle :param w: width of rectangle :param h: height of rectangle
625941bf15baa723493c3eba
def get_spot_price(self,symbol): <NEW_LINE> <INDENT> stock1= Stock.fetch(self.client, symbol) <NEW_LINE> stock = StockMarketdata.quote_by_instrument(self.client,_id =stock1['id']) <NEW_LINE> return stock
Returns a dictionary of data about the spot price, which includes bid, ask, bid size, ask size, as well as some api identification
625941bf498bea3a759b99f6
def parseHead(self): <NEW_LINE> <INDENT> if self.headed: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.headers = lodict() <NEW_LINE> self.checkPersisted() <NEW_LINE> self.headed = True <NEW_LINE> yield True <NEW_LINE> return
Generator to parse headers in heading of .msg Yields None if more to parse Yields True if done parsing
625941bfadb09d7d5db6c6d7
def stream_notify(self, stream_buffer): <NEW_LINE> <INDENT> raise NotImplementedError()
Notify that new data is available from the Joulescope. :param stream_buffer: The :class:`StreamBuffer` instance which contains the new data from the Joulescope. :return: False to continue streaming. True to stop streaming. This method will be called from the USB thread. The processing duration must be very short to prevent dropping samples. You should post any significant processing to a separate thread.
625941bffbf16365ca6f6105
def setUpModule(): <NEW_LINE> <INDENT> LOG.info("Begin Power Thermal Tests") <NEW_LINE> PowerThermalTest.initialize_data(HOST_OVERRIDE, DATA_OVERRIDE, DEPTH_OVERRIDE)
Initialize data for all test cases using overrides
625941bf711fe17d825422b6
def get_obj_label(self) -> str: <NEW_LINE> <INDENT> style_label: str = self.style.get_obj_label() <NEW_LINE> if self.style == self.style_or_mdh: <NEW_LINE> <INDENT> min_count: int = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> min_count = self.style_or_mdh.min_count <NEW_LINE> <DEDENT> return f"{style_label}.legend.{min_count}"
Return the metadata path prefix for this object.
625941bf7c178a314d6ef3a2
def set_nodatavalue(self, nodata): <NEW_LINE> <INDENT> self.nodatavalue = nodata
set nodata value
625941bf99fddb7c1c9de2d8
def find_next_stop_point(route,P,M,S,k,X,D,opts,weighted): <NEW_LINE> <INDENT> nsets_of_points = opts['nsets_of_points'] <NEW_LINE> stop_point_samples = [] <NEW_LINE> for i in range(nsets_of_points): <NEW_LINE> <INDENT> new_sample_distances, new_sample_positions = sample_set_of_stop_points(route,P,M,S,k,X,D,opts,weighted) <NEW_LINE> stop_point_samples.append(min(new_sample_distances)) <NEW_LINE> <DEDENT> next_point_dist = np.mean(np.array(stop_point_samples)) <NEW_LINE> remaining_dist = next_point_dist <NEW_LINE> current_point = route[0,:] <NEW_LINE> i = 0 <NEW_LINE> while remaining_dist>0: <NEW_LINE> <INDENT> delta = route[i,:] - route[i+1,:] <NEW_LINE> dist_to_next_point = np.sqrt(np.dot(delta,delta)) <NEW_LINE> if dist_to_next_point < remaining_dist: <NEW_LINE> <INDENT> remaining_dist -= dist_to_next_point <NEW_LINE> current_point = route[i+1,:] <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v = route[i+1,:] - route[i,:] <NEW_LINE> v = v/np.sqrt(np.dot(v,v)) <NEW_LINE> current_point = route[i,:] + remaining_dist*v <NEW_LINE> remaining_dist = 0 <NEW_LINE> <DEDENT> <DEDENT> remaining_route = np.vstack((current_point,route[i+1:,:])) <NEW_LINE> return current_point, remaining_route
Find the next point by sampling a number of sets of points, then taking the mean of the closest point. ARGUMENTS route: list of vertices on the route, from current position to destination M: mean of GP posterior S: variance of GP posterior k: number of stops still to be made RETURN x, 2d position vector remaining_route
625941bfcc40096d61595898
def get_method(self, action, method): <NEW_LINE> <INDENT> if action not in self.actions: <NEW_LINE> <INDENT> raise KeyError("Invalid action: {}".format(action)) <NEW_LINE> <DEDENT> key = _mk_cb_key(action, method) <NEW_LINE> if key not in self.actions[action]: <NEW_LINE> <INDENT> raise KeyError("No such method in '{}': '{}'".format(action, method)) <NEW_LINE> <DEDENT> return self.actions[action][key]
Returns a method's settings
625941bfd164cc6175782c94
def __len__(self) -> int: <NEW_LINE> <INDENT> ...
:return: the number of nodes in the tree
625941bf23e79379d52ee4ac
def __init__(self): <NEW_LINE> <INDENT> self.redmine = Redmine('http://localhost:81/redmine', username='ishikawa', password='yuto1004')
Constructor
625941bf45492302aab5e207
def plot_gdf(gdf,fig = False,filename='Test',column_plot = False, label = False, labelsize=4,**kwargs): <NEW_LINE> <INDENT> if fig == False: <NEW_LINE> <INDENT> fig = plt.figure(figsize=(16.53,11)) <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ax = fig.get_axes()[0] <NEW_LINE> <DEDENT> ax.set_aspect('equal') <NEW_LINE> ax.set_xlabel('Easting') <NEW_LINE> ax.set_ylabel('Northing') <NEW_LINE> if column_plot != False: <NEW_LINE> <INDENT> vmin = gdf[column_plot].min() <NEW_LINE> vmax = gdf[column_plot].max() <NEW_LINE> cax = fig.add_axes([0.9,0.1,0.03,0.8]) <NEW_LINE> sm = plt.cm.ScalarMappable(cmap ='gnuplot2_r',norm=plt.Normalize(vmin=vmin,vmax=vmax)) <NEW_LINE> sm._A=[] <NEW_LINE> cbar = fig.colorbar(sm,cax=cax) <NEW_LINE> time_delta = np.timedelta64(1,'D')*30.5/np.timedelta64(1,'s')*3 <NEW_LINE> i, ticks = 1,[cbar.vmin] <NEW_LINE> while ticks[-1] <cbar.vmax: <NEW_LINE> <INDENT> ticks.append(cbar.vmin+time_delta*i) <NEW_LINE> i = i+1 <NEW_LINE> <DEDENT> cbar.set_ticks(ticks) <NEW_LINE> cbar.set_ticklabels([datetime.datetime.fromtimestamp(t).strftime('%d-%b-%Y') for t in ticks]) <NEW_LINE> print(cbar.vmin) <NEW_LINE> gdf.plot(ax=ax,column=column_plot,**kwargs) <NEW_LINE> fig.suptitle(filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> gdf.plot(**kwargs,ax=ax) <NEW_LINE> <DEDENT> if label!=False: <NEW_LINE> <INDENT> gdf['coords'] = gdf.centroid <NEW_LINE> for index,row in gdf.iterrows(): <NEW_LINE> <INDENT> ax.annotate(s=str(row[label]),xy=(row['coords'].x, row['coords'].y) ,horizontalalignment='center', size=labelsize) <NEW_LINE> <DEDENT> <DEDENT> return fig, ax
This function is an extension of the geopandas's plot function and could plot labels and works on dates Parameters: gdf: - a geopandas object that holds the data fig: - pass the pointer to the figure object filename - name of the file to be ouput column_plot - the columns to be plotted label - label of the mnarker labelsize Return: tuple (fig, ax)
625941bfdd821e528d63b0f1
@lD.log(logBase + ".main") <NEW_LINE> def main(logger, resultsDict): <NEW_LINE> <INDENT> print("=" * 30) <NEW_LINE> print("Main function of splitFullMask module.") <NEW_LINE> print("=" * 30) <NEW_LINE> print("We get a copy of the result dictionary over here ...") <NEW_LINE> pprint.pprint(resultsDict) <NEW_LINE> top = Path(config_splitFullMask["top"]) <NEW_LINE> FULL_or_MASK = config_splitFullMask["FULL_or_MASK"] <NEW_LINE> extension = config_splitFullMask["extension"] <NEW_LINE> copy_to = Path(config_splitFullMask["copy_to"]) <NEW_LINE> files_moved = splitFullMask( top=top, FULL_or_MASK=FULL_or_MASK, extension=extension, copy_to=copy_to ) <NEW_LINE> print(f"Number of files with '{FULL_or_MASK}' moved: {files_moved}") <NEW_LINE> print() <NEW_LINE> print("Getting out of countFileType.") <NEW_LINE> print("-" * 30) <NEW_LINE> print() <NEW_LINE> return
main function for countDicom module. This function recursively counts the number of .dcm files in the given directory (i.e. includes all its subdirectories). Parameters ---------- logger : {logging.Logger} The logger used for logging error information resultsDict: {dict} A dictionary containing information about the command line arguments. These can be used for overwriting command line arguments as needed.
625941bf56ac1b37e626411a
def getFeatureClasses(): <NEW_LINE> <INDENT> global _featureClasses <NEW_LINE> if _featureClasses is None: <NEW_LINE> <INDENT> _featureClasses = {} <NEW_LINE> for _, mod, _ in pkgutil.iter_modules([os.path.dirname(__file__)]): <NEW_LINE> <INDENT> if str(mod).startswith('_'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> __import__('radiomics.' + mod) <NEW_LINE> module = sys.modules['radiomics.' + mod] <NEW_LINE> attributes = inspect.getmembers(module, inspect.isclass) <NEW_LINE> for a in attributes: <NEW_LINE> <INDENT> if a[0].startswith('Radiomics'): <NEW_LINE> <INDENT> for parentClass in inspect.getmro(a[1])[1:]: <NEW_LINE> <INDENT> if parentClass.__name__ == 'RadiomicsFeaturesBase': <NEW_LINE> <INDENT> _featureClasses[mod] = a[1] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return _featureClasses
Iterates over all modules of the radiomics package using pkgutil and subsequently imports those modules. Return a dictionary of all modules containing featureClasses, with modulename as key, abstract class object of the featureClass as value. Assumes only one featureClass per module This is achieved by inspect.getmembers. Modules are added if it contains a member that is a class, with name starting with 'Radiomics' and is inherited from :py:class:`radiomics.base.RadiomicsFeaturesBase`. This iteration only runs once (at initialization of toolbox), subsequent calls return the dictionary created by the first call.
625941bf5e10d32532c5ee6e
def ebSentMessage(err): <NEW_LINE> <INDENT> log.info("Error sending message "+str(err))
Called if the message cannot be sent. Report the failure to the user and then stop the reactor.
625941bf9c8ee82313fbb6bb
def __setitem__(self, key, value): <NEW_LINE> <INDENT> checkIndex(key) <NEW_LINE> self.changed[key] = value
Change an item in the arithmetic sequence.
625941bfb545ff76a8913d5d
def _delete_transmissions(self, content_metadata_item_ids): <NEW_LINE> <INDENT> ContentMetadataItemTransmission = apps.get_model( 'integrated_channel', 'ContentMetadataItemTransmission' ) <NEW_LINE> ContentMetadataItemTransmission.objects.filter( enterprise_customer=self.enterprise_configuration.enterprise_customer, integrated_channel_code=self.enterprise_configuration.channel_code(), content_id__in=content_metadata_item_ids ).delete()
Delete ContentMetadataItemTransmision models associated with the given content metadata items.
625941bfec188e330fd5a6ea
def appendLogger(loggername, loggerlevel='DEBUG', loggerclass='logging.handlers.RotatingFileHandler'): <NEW_LINE> <INDENT> global LOGGING, LOG_SIZE, LOG_ROOT <NEW_LINE> handler = 'logfile-' + str(loggername) <NEW_LINE> filename = LOG_ROOT + '/logfile.' + str(loggername) <NEW_LINE> LOGGING['handlers'][handler] = { 'level':loggerlevel, 'class':loggerclass, 'filename': filename, 'maxBytes': LOG_SIZE, 'backupCount': 2, 'formatter': 'verbose', } <NEW_LINE> LOGGING['loggers'][loggername] = { 'handlers': [handler], 'level': loggerlevel, }
appendLogger - append new logger properties :param loggername: name of the logger, e.g. 'bigpandamon' :type loggername: string
625941bf23e79379d52ee4ad
def test_ping_with_key(self): <NEW_LINE> <INDENT> ping_id = 42 <NEW_LINE> message = struct.pack('!IHHQHHI', server.MAGIC, 0, server.TYPE_PING, 123456, ping_id, 0, 0) <NEW_LINE> message = set_crc(message) <NEW_LINE> def check_pong(data, host_port): <NEW_LINE> <INDENT> assert host_port == self.HOST_PORT <NEW_LINE> assert len(data) >= 16 <NEW_LINE> header = struct.unpack('!IHHQ', data[:16]) <NEW_LINE> assert header[0] == server.MAGIC <NEW_LINE> assert check_crc(data) <NEW_LINE> assert header[2] == server.TYPE_ACK <NEW_LINE> ping_id2, _, flags = struct.unpack('!HHI', data[16:]) <NEW_LINE> assert ping_id2 == ping_id <NEW_LINE> assert not (flags & server.FLAG_ACK_BAD_KEY) <NEW_LINE> <DEDENT> self.server.socket = Mock() <NEW_LINE> self.server.socket.sendto = Mock(side_effect=check_pong) <NEW_LINE> self.server.handle(message, self.HOST_PORT) <NEW_LINE> assert self.server.socket.sendto.called
Tracking server can query by tracking key
625941bf8e7ae83300e4af13
def _find_references(self, items, depth=0): <NEW_LINE> <INDENT> reference_map = {} <NEW_LINE> if not items or depth >= self.max_depth: <NEW_LINE> <INDENT> return reference_map <NEW_LINE> <DEDENT> if isinstance(items, dict): <NEW_LINE> <INDENT> iterator = list(items.values()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iterator = items <NEW_LINE> <DEDENT> depth += 1 <NEW_LINE> for item in iterator: <NEW_LINE> <INDENT> if isinstance(item, (Document, EmbeddedDocument)): <NEW_LINE> <INDENT> for field_name, field in item._fields.items(): <NEW_LINE> <INDENT> v = item._data.get(field_name, None) <NEW_LINE> if isinstance(v, LazyReference): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif isinstance(v, DBRef): <NEW_LINE> <INDENT> reference_map.setdefault(field.document_type, set()).add(v.id) <NEW_LINE> <DEDENT> elif isinstance(v, (dict, SON)) and '_ref' in v: <NEW_LINE> <INDENT> reference_map.setdefault(get_document(v['_cls']), set()).add(v['_ref'].id) <NEW_LINE> <DEDENT> elif isinstance(v, (dict, list, tuple)) and depth <= self.max_depth: <NEW_LINE> <INDENT> field_cls = getattr(getattr(field, 'field', None), 'document_type', None) <NEW_LINE> references = self._find_references(v, depth) <NEW_LINE> for key, refs in references.items(): <NEW_LINE> <INDENT> if isinstance(field_cls, (Document, TopLevelDocumentMetaclass)): <NEW_LINE> <INDENT> key = field_cls <NEW_LINE> <DEDENT> reference_map.setdefault(key, set()).update(refs) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> elif isinstance(item, LazyReference): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif isinstance(item, DBRef): <NEW_LINE> <INDENT> reference_map.setdefault(item.collection, set()).add(item.id) <NEW_LINE> <DEDENT> elif isinstance(item, (dict, SON)) and '_ref' in item: <NEW_LINE> <INDENT> reference_map.setdefault(get_document(item['_cls']), set()).add(item['_ref'].id) <NEW_LINE> <DEDENT> elif isinstance(item, (dict, list, tuple)) and depth - 1 <= self.max_depth: <NEW_LINE> <INDENT> references = self._find_references(item, depth - 1) <NEW_LINE> for key, refs in references.items(): <NEW_LINE> <INDENT> reference_map.setdefault(key, set()).update(refs) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return reference_map
Recursively finds all db references to be dereferenced :param items: The iterable (dict, list, queryset) :param depth: The current depth of recursion
625941bf0fa83653e4656f03
def test_provider_get_connection(self, test_domain): <NEW_LINE> <INDENT> conn = test_domain.providers["default"].get_connection() <NEW_LINE> assert conn is not None <NEW_LINE> assert isinstance(conn, Session) <NEW_LINE> assert conn.is_active
Test ``get_connection`` method and check for connection details
625941bf1b99ca400220a9f7
@register.filter <NEW_LINE> def chunk(input_list, size): <NEW_LINE> <INDENT> return [input_list[i:i + size] for i in range(0, len(input_list), size)]
Split a list into a list-of-lists. If size = 2, [1, 2, 3, 4, 5, 6, 7] becomes [[1,2], [3,4], [5,6], [7]]
625941bf7cff6e4e811178cc
def create_user(self, user) -> int: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_id = self.db.incr('global:nextUserId') <NEW_LINE> p = self.db.pipeline() <NEW_LINE> self.db.set('phone:{phone}:id'.format(phone=user.get('phone')), user_id) <NEW_LINE> self.db.set('phone:password_hash:{id}'.format(id=user_id), user.get('password_hash')) <NEW_LINE> self.db.set('phone:create_date:{id}'.format(id=user_id), user.get('create_date')) <NEW_LINE> self.db.set('phone:is_active:{id}'.format(id=user_id), user.get('is_active')) <NEW_LINE> self.db.delete('{key}:{suffix}'.format(key=user.get('phone'), suffix='reg')) <NEW_LINE> self.db.sadd('global:users', user_id) <NEW_LINE> p.execute() <NEW_LINE> return user_id <NEW_LINE> <DEDENT> except RedisError as error: <NEW_LINE> <INDENT> raise RedisRepositoryError(error)
Create new user :param user: User schema :return: int
625941bf4e696a04525c9393
def pc_input_buffers_full(self, *args): <NEW_LINE> <INDENT> return _blocks_swig3.multiply_conjugate_cc_sptr_pc_input_buffers_full(self, *args)
pc_input_buffers_full(multiply_conjugate_cc_sptr self, int which) -> float pc_input_buffers_full(multiply_conjugate_cc_sptr self) -> pmt_vector_float
625941bf287bf620b61d39ac
def test(sess, model): <NEW_LINE> <INDENT> y_pred = model.prediction_soft <NEW_LINE> for idx in range(101, 151): <NEW_LINE> <INDENT> pt_number = str(idx).zfill(3) <NEW_LINE> print('Processing test volume: {0}'.format(pt_number)) <NEW_LINE> folder_name = 'patient{0}'.format(pt_number) <NEW_LINE> prefix = os.path.join(TEST_ROOT_DIR, folder_name) <NEW_LINE> ed, es = parse_info_cfg(os.path.join(prefix, 'Info.cfg')) <NEW_LINE> pt_full_path = os.path.join(prefix, 'patient' + pt_number + '_frame{0}.nii.gz'.format(str(ed).zfill(2))) <NEW_LINE> img_array, specs = get_processed_volumes(fname=pt_full_path) <NEW_LINE> prediction = sess.run(y_pred, feed_dict={model.acdc_sup_input_data: img_array, model.is_training: False}) <NEW_LINE> prediction = post_process_segmentation(prediction, specs) <NEW_LINE> out_name = os.path.join(OUT_DIR, 'patient' + pt_number + '_ED.nii.gz') <NEW_LINE> save_nifti_files(out_name, prediction, specs) <NEW_LINE> pt_full_path = os.path.join(prefix, 'patient' + pt_number + '_frame{0}.nii.gz'.format(str(es).zfill(2))) <NEW_LINE> img_array, specs = get_processed_volumes(fname=pt_full_path) <NEW_LINE> prediction = sess.run(y_pred, feed_dict={model.acdc_sup_input_data: img_array, model.is_training: False}) <NEW_LINE> prediction = post_process_segmentation(prediction, specs) <NEW_LINE> out_name = os.path.join(OUT_DIR, 'patient' + pt_number + '_ES.nii.gz') <NEW_LINE> save_nifti_files(out_name, prediction, specs)
Test the model on ACDC test data
625941bf379a373c97cfaa8a
def Hyperbolic(self, x): <NEW_LINE> <INDENT> a, b, c, result = 0, 0, 0, 0 <NEW_LINE> try: <NEW_LINE> <INDENT> a = self._parameters['a'] <NEW_LINE> b = self._parameters['b'] <NEW_LINE> c = self._parameters['c'] <NEW_LINE> if x <= c: <NEW_LINE> <INDENT> result = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = 1 / (1 + (a * (x - c)) ** b) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> result = 0 <NEW_LINE> FCLogger.error(traceback.format_exc()) <NEW_LINE> FCLogger.error('Hyperbolic membership function use real inputs x and parameters a, b, c.') <NEW_LINE> FCLogger.error('Your inputs: mju_hyperbolic({}, {}, {}, {})'.format(x, a, b, c)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return result
This is hyperbolic membership function with real inputs x and parameters a, b, c.
625941bff8510a7c17cf9642
def __div__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Symbol): <NEW_LINE> <INDENT> return __div_symbol__(self, other) <NEW_LINE> <DEDENT> if isinstance(other, _Number): <NEW_LINE> <INDENT> return __div_scalar__(self, scalar=other) <NEW_LINE> <DEDENT> raise TypeError('type %s not supported' % str(type(other)))
x.__div__(y) <=> x/y
625941bf6e29344779a6255b
def run(self, test): <NEW_LINE> <INDENT> result = self._makeResult() <NEW_LINE> registerResult(result) <NEW_LINE> result.failfast = self.failfast <NEW_LINE> result.buffer = self.buffer <NEW_LINE> startTime = time.time() <NEW_LINE> startTestRun = getattr(result, 'startTestRun', None) <NEW_LINE> if startTestRun is not None: <NEW_LINE> <INDENT> startTestRun() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> test(result) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> stopTestRun = getattr(result, 'stopTestRun', None) <NEW_LINE> if stopTestRun is not None: <NEW_LINE> <INDENT> stopTestRun() <NEW_LINE> <DEDENT> <DEDENT> stopTime = time.time() <NEW_LINE> timeTaken = stopTime - startTime <NEW_LINE> result.printErrors() <NEW_LINE> if hasattr(result, 'separator2'): <NEW_LINE> <INDENT> self.stream.writeln(result.separator2) <NEW_LINE> <DEDENT> run = result.testsRun <NEW_LINE> self.stream.writeln("Ran %d test%s in %.3fs" % (run, run != 1 and "s" or "", timeTaken)) <NEW_LINE> self.stream.writeln() <NEW_LINE> return result
Run the given test case or test suite.
625941bf3c8af77a43ae36e5
def printState(self): <NEW_LINE> <INDENT> if self.printStateFile is None: <NEW_LINE> <INDENT> for n in range(500): <NEW_LINE> <INDENT> self.printStateFile = "neb.EofS.%04d" % n <NEW_LINE> if not os.path.isfile(self.printStateFile): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> logger.info("NEB energies will be written to %s", self.printStateFile) <NEW_LINE> <DEDENT> with open(self.printStateFile, "a") as fout: <NEW_LINE> <INDENT> fout.write("\n\n") <NEW_LINE> fout.write("#neb step: %d\n" % self.getEnergyCount) <NEW_LINE> S = 0. <NEW_LINE> for i in range(self.nimages): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> dist = 0. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dist, t = self.distance(self.coords[i, :], self.coords[i - 1, :], grad=False) <NEW_LINE> <DEDENT> S += dist <NEW_LINE> fout.write("%f %g\n" % (S, self.energies[i]))
print the current state of the NEB. Useful for bug testing
625941bf2ae34c7f2600d078
def change_dir(path: typing.Union[str, pathlib.Path]): <NEW_LINE> <INDENT> nonlocal dir, foldermap <NEW_LINE> dir = pathlib.Path(path) <NEW_LINE> manager.dir = dir <NEW_LINE> asyncio.ensure_future(foldermap.destroy()) <NEW_LINE> foldermap = tk.AsyncFrame(manager) <NEW_LINE> foldermap.grid(row=1, column=0) <NEW_LINE> populate_folder(dir) <NEW_LINE> tk.AsyncButton( foldermap, text=self.cur_locale.menu.fileselect.button.cancel, callback=manager.destroy, ).pack(fill=tk.X)
Internal function to load a path into the file select menu.
625941bf4f6381625f114983
def __init__( self, input_key: str = "features", target_key: str = "target", loss_key: str = "loss", augemention_prefix: str = "augment", projection_prefix: str = "projection", embedding_prefix: str = "embedding", ): <NEW_LINE> <INDENT> IRunner.__init__(self) <NEW_LINE> self._target_key = target_key <NEW_LINE> self._loss_key = loss_key <NEW_LINE> self._projection_prefix = projection_prefix <NEW_LINE> self._augemention_prefix = augemention_prefix <NEW_LINE> self._embedding_prefix = embedding_prefix <NEW_LINE> self._input_key = input_key
Init.
625941bf8a349b6b435e80ba
def event_m50_36_38120(): <NEW_LINE> <INDENT> assert event_m50_36_x244(z59=38000, z60=536000042, z61=1) <NEW_LINE> EndMachine() <NEW_LINE> Quit()
Addition of destructive variable of sculpture statue_Boss room left_Back
625941bf187af65679ca5065
def modify_file(self, wdir_uuid, element, mod_style='override', **kwargs): <NEW_LINE> <INDENT> if mod_style == 'override': <NEW_LINE> <INDENT> self.override_file(wdir_uuid, element, **kwargs) <NEW_LINE> <DEDENT> elif mod_style == 'update-append': <NEW_LINE> <INDENT> self.update_append_file(wdir_uuid, element, **kwargs) <NEW_LINE> <DEDENT> elif callable(mod_style): <NEW_LINE> <INDENT> mod_style(wdir_uuid, element, callback_request=self.modify_request) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error('NOT VALID modify style passed.')
Modifies an existing file in Datary. =============== =============== ================================== Parameter Type Description =============== =============== ================================== wdir_uuid str working directory uuid element list [path, basename, data, sha1] mod_style str o callable 'override' by default, 'update-append' mod_style, 'update-row' mod_style, <callable> function to use. =============== =============== ==================================
625941bf3539df3088e2e292
def destroy_control(self): <NEW_LINE> <INDENT> if self.control is not None: <NEW_LINE> <INDENT> self.control.hide() <NEW_LINE> self.control.close() <NEW_LINE> self.control.deleteLater() <NEW_LINE> self.control = None <NEW_LINE> <DEDENT> return
Destroy the toolkit-specific control that represents the part.
625941bf66656f66f7cbc0f1
def __getitem__(self, key): <NEW_LINE> <INDENT> return self._userdata.get(key)
Return a single byte of the user data.
625941bf63d6d428bbe44436
def __init__( self, audiences: typing.List[str] = None, authenticated: bool = None, error: str = None, user: "UserInfo" = None, ): <NEW_LINE> <INDENT> super(TokenReviewStatus, self).__init__( api_version="authentication/v1beta1", kind="TokenReviewStatus" ) <NEW_LINE> self._properties = { "audiences": audiences if audiences is not None else [], "authenticated": authenticated if authenticated is not None else None, "error": error if error is not None else "", "user": user if user is not None else UserInfo(), } <NEW_LINE> self._types = { "audiences": (list, str), "authenticated": (bool, None), "error": (str, None), "user": (UserInfo, None), }
Create TokenReviewStatus instance.
625941bf55399d3f055885fa
def get_alerts(leader, key, start_time): <NEW_LINE> <INDENT> alerts = list() <NEW_LINE> (first_page, meta, links) = get_alerts_page(leader, key, start_time, 1) <NEW_LINE> alerts.extend(first_page) <NEW_LINE> last_page_number = get_page_from_link(links["last"]) <NEW_LINE> current_page_number = get_page_from_link(links["self"]) <NEW_LINE> while (current_page_number != last_page_number): <NEW_LINE> <INDENT> current_page_number = current_page_number + 1 <NEW_LINE> (current_page, meta, links) = get_alerts_page(leader, key, start_time, current_page_number) <NEW_LINE> alerts.extend(current_page) <NEW_LINE> <DEDENT> return alerts
Retrieve alerts from an SP leader. Args: leader (str): SP leader from which the alerts originated key (str): API key generated on the given SP leader start_time (obj): arrow time object to be used a start_time filter for alerts. Returns: list: Alerts from the SP leader.
625941bfa05bb46b383ec76b
def string_to_dict(var_string, allow_kv=True, require_dict=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return_dict = yaml.load(var_string, Loader=yaml.SafeLoader) <NEW_LINE> if require_dict: <NEW_LINE> <INDENT> assert type(return_dict) is dict <NEW_LINE> <DEDENT> <DEDENT> except (AttributeError, yaml.YAMLError, AssertionError): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert allow_kv <NEW_LINE> return_dict = parse_kv(var_string) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise exc.TowerCLIError( 'failed to parse some of the extra ' 'variables.\nvariables: \n%s' % var_string ) <NEW_LINE> <DEDENT> <DEDENT> return return_dict
Returns a dictionary given a string with yaml or json syntax. If data is not present in a key: value format, then it return an empty dictionary. Attempts processing string by 3 different methods in order: 1. as JSON 2. as YAML 3. as custom key=value syntax Throws an error if all of these fail in the standard ways.
625941bf090684286d50ec2a
def show_level(self): <NEW_LINE> <INDENT> self.write(f"level = {self.level}", align="Center", font=FONT)
Showing level on screen
625941bfdd821e528d63b0f2
def isValid(self, valid=None): <NEW_LINE> <INDENT> if valid is not None: <NEW_LINE> <INDENT> self._isValid = bool(valid) <NEW_LINE> <DEDENT> return self._isValid
Get or set the validity of this bridge request. If called without parameters, this method will return the current state, otherwise (if called with the **valid** parameter), it will set the current state of validity for this request. :param bool valid: If given, set the validity state of this request. Otherwise, get the current state.
625941bf44b2445a33931fde
def get_network_page_title(self): <NEW_LINE> <INDENT> self.wait().until(EC.visibility_of_element_located(self.default_tab_header_locator), 'default tab header not found before specified time') <NEW_LINE> return self.page_title()
Implementing get network page title functionality :return: network page title
625941bfd18da76e2353241a
def _set_loggers(verbosity: int = 0, api_verbosity: str = 'info') -> None: <NEW_LINE> <INDENT> logging.getLogger('requests').setLevel( logging.INFO if verbosity <= 1 else logging.DEBUG ) <NEW_LINE> logging.getLogger("urllib3").setLevel( logging.INFO if verbosity <= 1 else logging.DEBUG ) <NEW_LINE> logging.getLogger('ccxt.base.exchange').setLevel( logging.INFO if verbosity <= 2 else logging.DEBUG ) <NEW_LINE> logging.getLogger('telegram').setLevel(logging.INFO) <NEW_LINE> logging.getLogger('werkzeug').setLevel( logging.ERROR if api_verbosity == 'error' else logging.INFO )
Set the logging level for third party libraries :return: None
625941bfcb5e8a47e48b79f5
def generate_colors(): <NEW_LINE> <INDENT> rb_counts = [9, 8] <NEW_LINE> random.shuffle(rb_counts) <NEW_LINE> red_count, blue_count = rb_counts <NEW_LINE> grey_count, black_count = 7, 1 <NEW_LINE> counters = {'red': red_count, 'blue': blue_count, 'grey': grey_count, 'black': black_count} <NEW_LINE> colors = [] <NEW_LINE> while sum(counters.values()) > 0: <NEW_LINE> <INDENT> available_colors = {k: v for k, v in counters.items() if v > 0} <NEW_LINE> color = random.choice(list(available_colors.keys())) <NEW_LINE> counters[color] -= 1 <NEW_LINE> colors.append(color) <NEW_LINE> <DEDENT> return colors
Makes a random set of colors legal for a board Counts must be (9, 8, 7, 1) of (red/blue, blue/red, grey, black)
625941bf7d43ff24873a2be6
def Trifoliate(g, vid, turtle): <NEW_LINE> <INDENT> t = turtle <NEW_LINE> nid = g.node(vid) <NEW_LINE> order = nid.order <NEW_LINE> t.setColor(2+order) <NEW_LINE> t.setWidth(0.01) <NEW_LINE> len_petiole = 1. <NEW_LINE> len_internode = 0.1 <NEW_LINE> leaflet_length = 0.7/2. <NEW_LINE> leaflet_wdth = 0.3/2. <NEW_LINE> t.F(0.1) <NEW_LINE> t.push() <NEW_LINE> t.down(45.) <NEW_LINE> t.F(len_petiole) <NEW_LINE> if not WITHOUT_LEAF: <NEW_LINE> <INDENT> t.customGeometry(Trileaflet(leaflet_length, leaflet_wdth)) <NEW_LINE> <DEDENT> t.pop()
F: Petiol + 3 lobes. cylinder + 3 ellipse/surface
625941bfd4950a0f3b08c298
def test_get_meta_doc_handles_nested_oneof_property_types(self): <NEW_LINE> <INDENT> schema = { "properties": { "prop1": { "type": "array", "items": { "oneOf": [{"type": "string"}, {"type": "integer"}] }, } } } <NEW_LINE> self.assertIn( "**prop1:** (array of (string)/(integer))", get_meta_doc(self.meta, schema), )
get_meta_doc describes array items oneOf declarations in type.
625941bfff9c53063f47c13c
def GetPointer(self): <NEW_LINE> <INDENT> return _itkFlipImageFilterPython.itkFlipImageFilterID3_GetPointer(self)
GetPointer(self) -> itkFlipImageFilterID3
625941bf67a9b606de4a7e03
def TTF_Quit(): <NEW_LINE> <INDENT> return _funcs["TTF_Quit"]()
De-initializes the TTF engine. Once this has been called, other functions in the module should not be used until :func:`TTF_Init` is called to re-initialize the engine (except for :func:`TTF_WasInit`). .. note:: If :func:`TTF_Init` is called multiple times, this function should be called an equal number of times to properly de-initialize the library.
625941bf5fcc89381b1e1604
def readSetpoint(self, instance='01'): <NEW_LINE> <INDENT> return self.readParam(7001, float, instance='01')
Reads the current setpoint. This is a wrapper around `readParam()` and is equivalent to `readParam(7001, float, instance)`. Returns a dict containing the response data, parameter ID, and address. * **instance**: a two digit string corresponding to the channel to read (e.g. '01', '05')
625941bf3617ad0b5ed67e40
def bootstrap_c_source(output_dir, module_name=NATIVE_ENGINE_MODULE): <NEW_LINE> <INDENT> safe_mkdir(output_dir) <NEW_LINE> output_prefix = os.path.join(output_dir, module_name) <NEW_LINE> c_file = '{}.c'.format(output_prefix) <NEW_LINE> env_script = '{}.sh'.format(output_prefix) <NEW_LINE> ffibuilder = cffi.FFI() <NEW_LINE> ffibuilder.cdef(CFFI_TYPEDEFS) <NEW_LINE> ffibuilder.cdef(CFFI_HEADERS) <NEW_LINE> ffibuilder.cdef(CFFI_EXTERNS) <NEW_LINE> ffibuilder.set_source(module_name, CFFI_TYPEDEFS + CFFI_HEADERS) <NEW_LINE> ffibuilder.emit_c_code(six.binary_type(c_file)) <NEW_LINE> print('generating {}'.format(env_script)) <NEW_LINE> with open(env_script, 'wb') as f: <NEW_LINE> <INDENT> f.write('export CFLAGS="{}"\n'.format(get_build_cflags()))
Bootstrap an external CFFI C source file.
625941bf92d797404e3040d1
@tx.command() <NEW_LINE> @with_login <NEW_LINE> def send(session): <NEW_LINE> <INDENT> with Tx(allow_errors=False, recreate=False) as tx: <NEW_LINE> <INDENT> sent = gdk_resolve(gdk.send_transaction(session.session_obj, json.dumps(tx))) <NEW_LINE> tx.clear() <NEW_LINE> tx.update(sent) <NEW_LINE> click.echo(f"{tx['txhash']}")
Send/broadcast the current transaction.
625941bf5510c4643540f332
def stacked_prediction(stack_x, y): <NEW_LINE> <INDENT> y_hat = [] <NEW_LINE> for i in range(stack_x.shape[1]): <NEW_LINE> <INDENT> data = stack_x[:, i, :] <NEW_LINE> curr_labels = reverse_one_hot(data) <NEW_LINE> if np.sum(curr_labels) > 16.0: <NEW_LINE> <INDENT> y_hat.append(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y_hat.append(0) <NEW_LINE> <DEDENT> <DEDENT> return np.array(y_hat)
Function uses the output of the single models to determine it's final guess using majority rule in final output
625941bf3317a56b86939ba6
def label_accuracy_hist(label_trues, label_preds, n_class): <NEW_LINE> <INDENT> hist = np.zeros((n_class, n_class)) <NEW_LINE> for lt, lp in zip(label_trues, label_preds): <NEW_LINE> <INDENT> hist += _fast_hist(lt.flatten(), lp.flatten(), n_class) <NEW_LINE> <DEDENT> return hist
Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc
625941bfe64d504609d74787
def cast(*args): <NEW_LINE> <INDENT> return _itkIntensityWindowingImageFilterPython.itkIntensityWindowingImageFilterID2ID2_cast(*args)
cast(itkLightObject obj) -> itkIntensityWindowingImageFilterID2ID2
625941bf925a0f43d2549dbc
def get_meals(self): <NEW_LINE> <INDENT> return []
Returns list of menu objects of meuns that are available
625941bfcdde0d52a9e52f78
def resize(self, resolution): <NEW_LINE> <INDENT> mult = BoxComponent.resolution_map[resolution] <NEW_LINE> ac.setSize(self.__window_id, 512 * mult, 85 * mult) <NEW_LINE> for component in self.__components: <NEW_LINE> <INDENT> component.resize(resolution)
Resizes the window.
625941bf656771135c3eb7b4
def test_config_attr(self): <NEW_LINE> <INDENT> mongo = mongo_class.Rep(self.name, self.user, self.japd, self.host, self.port) <NEW_LINE> self.assertEqual(mongo.config, self.config2)
Function: test_config_attr Description: Test setting the config attribute. Arguments:
625941bfbde94217f3682d3b
def is_authenticated(view_func): <NEW_LINE> <INDENT> def _wrapped_view_func(request, *args, **kwargs): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> if not hasattr(user, 'wunderlist'): <NEW_LINE> <INDENT> return redirect('index') <NEW_LINE> <DEDENT> if not hasattr(user, 'habitica'): <NEW_LINE> <INDENT> return redirect('index') <NEW_LINE> <DEDENT> w_api = user.wunderlist.get_api() <NEW_LINE> h_api = user.habitica.get_api() <NEW_LINE> if not w_api.test_auth(): <NEW_LINE> <INDENT> user.wunderlist.delete() <NEW_LINE> messages.error(request, _('Could not connect to Wunderlist. Please re-connect')) <NEW_LINE> logout(request) <NEW_LINE> return redirect('index') <NEW_LINE> <DEDENT> if not h_api.get_status(): <NEW_LINE> <INDENT> messages.error(request, _('Habitica servers are currently not responding. Please try again later.')) <NEW_LINE> return redirect('dashboard') <NEW_LINE> <DEDENT> if not h_api.test_auth(): <NEW_LINE> <INDENT> user.habitica.delete() <NEW_LINE> messages.error(request, _('Could not connect to Habitica. Please re-connect.')) <NEW_LINE> return redirect('dashboard') <NEW_LINE> <DEDENT> return view_func(request, *args, **kwargs) <NEW_LINE> <DEDENT> return _wrapped_view_func
Checks if the current user is authenticated against Wunderlist and Habitica. If not, the user is redirected to the index page.
625941bff548e778e58cd4c4
def testEmptyStrings(self): <NEW_LINE> <INDENT> error = r"^Two sequences of zero length were passed\.$" <NEW_LINE> self.assertRaisesRegex(ValueError, error, dna2cigar, '', '')
If two empty strings are passed, a ValueError must be raised.
625941bf97e22403b379cee1
def wrap_response(self, response, model, flat=False): <NEW_LINE> <INDENT> if isinstance(response, SuccessResponse) and response.length > 0: <NEW_LINE> <INDENT> if issubclass(model, RestModel): <NEW_LINE> <INDENT> models = [model(self, i) for i in response.results()] <NEW_LINE> if flat and len(models) == 1: <NEW_LINE> <INDENT> return models[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return models <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return model <NEW_LINE> <DEDENT> <DEDENT> return None
Takes a SuccessResponse and returns the results as instances of the given model. Args: response (SuccessResponse): A SuccessResponse object containing the data to be wrapped. model (RestModel): A subclass of RestModel that should be used when creating instances for each result in the response. flat (bool, optional): Whether single-element lists should return just that element instead of the list itself. Returns: If ``response`` contains zero results, returns `None`. If ``response`` has one element and ``flat`` equals `True`, return the first element as an instance of type ``model``. In all other cases, return a list of instances of type ``model``.
625941bf57b8e32f524833e1
def getElementsAbove(nodes=None): <NEW_LINE> <INDENT> elements = [] <NEW_LINE> if not nodes: <NEW_LINE> <INDENT> nodes = mc.ls(sl=True) <NEW_LINE> <DEDENT> for each in nodes: <NEW_LINE> <INDENT> if getNodeType(each) in ['element','puppet']: <NEW_LINE> <INDENT> elements.append(each) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> elem = getNodeTypeAbove(each, 'element') <NEW_LINE> if elem: <NEW_LINE> <INDENT> elements.append(elem) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return list(set(elements))
Legacy, no longer used.
625941bf0fa83653e4656f04
def checkConns(self): <NEW_LINE> <INDENT> self.conns = self.nodestack.connecteds()
Evaluate the connected nodes
625941bf3346ee7daa2b2cb2
def cast(*args): <NEW_LINE> <INDENT> return _itkMaskNegatedImageFilterPython.itkMaskNegatedImageFilterID2IUL2ID2_cast(*args)
cast(itkLightObject obj) -> itkMaskNegatedImageFilterID2IUL2ID2
625941bf07f4c71912b113c8
def check_connection ( self ): <NEW_LINE> <INDENT> if self.controller.config.values["auto_connect"]: <NEW_LINE> <INDENT> self.open_connection() <NEW_LINE> <DEDENT> if self.connectivity_level != 2: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.telnet == None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not isinstance(self.telnet.get_socket(), socket.socket): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.ready = True <NEW_LINE> return True
Should return True if everything is fine with the connection. Do not rely on metadata for this; this function is supposed to be reliable, and the metadata set according to its results.
625941bfd8ef3951e3243485
def warp_homography(res, scale, shear, flip): <NEW_LINE> <INDENT> center_mat = np.eye(3) <NEW_LINE> center_mat[0, 2] = -res[0] / 2.0 <NEW_LINE> center_mat[1, 2] = -res[1] / 2.0 <NEW_LINE> cmat_inv = np.linalg.inv(center_mat) <NEW_LINE> flip_mat = np.eye(3) <NEW_LINE> if flip[0]: <NEW_LINE> <INDENT> flip_mat[0, 0] = -1 <NEW_LINE> <DEDENT> if flip[1]: <NEW_LINE> <INDENT> flip_mat[1, 1] = -1 <NEW_LINE> <DEDENT> shear_mat = np.eye(3) <NEW_LINE> shear_mat[0, 1] = math.tan(math.radians(shear[0])) <NEW_LINE> shear_mat[1, 0] = math.tan(math.radians(shear[1])) <NEW_LINE> scale_mat = np.eye(3) <NEW_LINE> scale_mat[0, 0] = scale[0] <NEW_LINE> scale_mat[1, 1] = scale[1] <NEW_LINE> return cmat_inv.dot(scale_mat.dot(shear_mat.dot(flip_mat.dot(center_mat))))
Returns a homography for image scaling, shear and flip. Args: res: resolution of the image, [x_res, y_res]. scale: scale factor [x_scale, y_scale]. shear: shear in [x_deg, y_deg]. flip: boolean [x_flip, y_flip].
625941bf9b70327d1c4e0d1c
def test_continues_if_jig_user_directory_created(self): <NEW_LINE> <INDENT> with patch('jig.gitutils.hooking.makedirs') as makedirs: <NEW_LINE> <INDENT> makedirs.side_effect = OSError(17, 'Directory exists') <NEW_LINE> <DEDENT> self.assertEqual( '{0}/.jig/git/templates'.format(self.user_home_directory), create_auto_init_templates(self.user_home_directory) )
An existing ~/.jig directory doesn't cause failure.
625941bf090684286d50ec2b
def ytdl_is_updateable(): <NEW_LINE> <INDENT> from zipimport import zipimporter <NEW_LINE> return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
Returns if ananse can be updated with -U
625941bf73bcbd0ca4b2bfbe
def computeSymbolicInputJacobian(self): <NEW_LINE> <INDENT> degree = self._params[2].size - 1 <NEW_LINE> x = self._stateSymb[0] <NEW_LINE> y = self._stateSymb[1] <NEW_LINE> z = self._stateSymb[2] <NEW_LINE> x_dot = self._stateSymb[3] <NEW_LINE> y_dot = self._stateSymb[4] <NEW_LINE> z_dot = self._stateSymb[5] <NEW_LINE> mu = sp.symbols('mu') <NEW_LINE> R_E = sp.symbols('R_E') <NEW_LINE> J = sp.symarray('J', degree + 1) <NEW_LINE> nmbrOfStates = self.getNmbrOfStates() <NEW_LINE> nmbrOfInputs = self.getNmbrInputs() <NEW_LINE> F = [0 for i in range(0, nmbrOfStates)] <NEW_LINE> dF = [[0 for i in range(0, nmbrOfInputs)] for i in range(0, nmbrOfStates)] <NEW_LINE> B_lambda = [[0 for i in range(0, nmbrOfInputs)] for i in range(0, nmbrOfStates)] <NEW_LINE> if self._usingDMC: <NEW_LINE> <INDENT> w_x = self._stateSymb[-3] <NEW_LINE> w_y = self._stateSymb[-2] <NEW_LINE> w_z = self._stateSymb[-1] <NEW_LINE> B = sp.symarray('B', 3) <NEW_LINE> for i in range(0, nmbrOfStates) : <NEW_LINE> <INDENT> F[i] = self._modelSymb[i] <NEW_LINE> for j in range(0, nmbrOfInputs) : <NEW_LINE> <INDENT> dF[i][j] = sp.diff(F[i], self._inputSymb[j]) <NEW_LINE> B_lambda[i][j] = sp.lambdify((x, y, z, x_dot, y_dot, z_dot, w_x, w_y, w_z, mu, R_E, [J], [B]), dF[i][j], "numpy") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(0, nmbrOfStates) : <NEW_LINE> <INDENT> F[i] = self._modelSymb[i] <NEW_LINE> for j in range(0, nmbrOfInputs) : <NEW_LINE> <INDENT> dF[i][j] = sp.diff(F[i], self._inputSymb[j]) <NEW_LINE> B_lambda[i][j] = sp.lambdify((x, y, z, x_dot, y_dot, z_dot, mu, R_E, [J]), dF[i][j], "numpy") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._jacobianInputSymb = dF <NEW_LINE> self._jacobianInputLambda = B_lambda <NEW_LINE> return self._jacobianInputSymb
Symbollically computes the Jacobian matrix of the model with respect to position and velocity and stores the models and lambda functions in the attributes _jacobian, _jacobianLambda. :return:
625941bf4527f215b584c3a2
def default(self): <NEW_LINE> <INDENT> def decorator(func): <NEW_LINE> <INDENT> self._default = func <NEW_LINE> return func <NEW_LINE> <DEDENT> return decorator
[Decorator] Set default handler method. :rtype: func :return: decorator
625941bfd4950a0f3b08c299
def get_stats(self): <NEW_LINE> <INDENT> ceph_cluster = "%s-%s" % (self.prefix, self.cluster) <NEW_LINE> data = { ceph_cluster: { 'pg': { } } } <NEW_LINE> output = self.exec_cmd('pg dump') <NEW_LINE> if output is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> json_data = json.loads(output) <NEW_LINE> pg_data = data[ceph_cluster]['pg'] <NEW_LINE> if 'pg_map' in json_data: <NEW_LINE> <INDENT> pg_stats = json_data['pg_map']['pg_stats'] <NEW_LINE> osd_stats = json_data['pg_map']['osd_stats'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pg_stats = json_data['pg_stats'] <NEW_LINE> osd_stats = json_data['osd_stats'] <NEW_LINE> <DEDENT> for pg in pg_stats: <NEW_LINE> <INDENT> for state in pg['state'].split('+'): <NEW_LINE> <INDENT> if not pg_data.has_key(state): <NEW_LINE> <INDENT> pg_data[state] = 0 <NEW_LINE> <DEDENT> pg_data[state] += 1 <NEW_LINE> <DEDENT> <DEDENT> for osd in osd_stats: <NEW_LINE> <INDENT> osd_id = "osd-%s" % osd['osd'] <NEW_LINE> data[ceph_cluster][osd_id] = {} <NEW_LINE> data[ceph_cluster][osd_id]['kb_used'] = osd['kb_used'] <NEW_LINE> data[ceph_cluster][osd_id]['kb_total'] = osd['kb'] <NEW_LINE> data[ceph_cluster][osd_id]['snap_trim_queue_len'] = osd['snap_trim_queue_len'] <NEW_LINE> data[ceph_cluster][osd_id]['num_snap_trimming'] = osd['num_snap_trimming'] <NEW_LINE> if 'fs_perf_stat' in osd: <NEW_LINE> <INDENT> perfname = 'fs_perf_stat' <NEW_LINE> <DEDENT> elif 'perf_stat' in osd: <NEW_LINE> <INDENT> perfname = 'perf_stat' <NEW_LINE> <DEDENT> data[ceph_cluster][osd_id]['apply_latency_ms'] = osd[perfname]['apply_latency_ms'] <NEW_LINE> data[ceph_cluster][osd_id]['commit_latency_ms'] = osd[perfname]['commit_latency_ms'] <NEW_LINE> <DEDENT> return data
Retrieves stats from ceph pgs
625941bf7d847024c06be201
def test_schema_related_serializers(): <NEW_LINE> <INDENT> generator = SchemaGenerator() <NEW_LINE> request = create_request("/") <NEW_LINE> schema = generator.get_schema(request=request) <NEW_LINE> assert "/authors/{id}/relationships/{related_field}" in schema["paths"] <NEW_LINE> assert "/authors/{id}/comments/" in schema["paths"] <NEW_LINE> assert "/authors/{id}/entries/" in schema["paths"] <NEW_LINE> assert "/authors/{id}/first_entry/" in schema["paths"] <NEW_LINE> first_get = schema["paths"]["/authors/{id}/first_entry/"]["get"]["responses"]["200"] <NEW_LINE> first_schema = first_get["content"]["application/vnd.api+json"]["schema"] <NEW_LINE> first_props = first_schema["properties"]["data"] <NEW_LINE> assert "$ref" in first_props <NEW_LINE> assert first_props["$ref"] == "#/components/schemas/Entry"
Confirm that paths are generated for related fields. For example: /authors/{pk}/{related_field>} /authors/{id}/comments/ /authors/{id}/entries/ /authors/{id}/first_entry/ and confirm that the schema for the related field is properly rendered
625941bf10dbd63aa1bd2aee
def _transpose_table(self, table): <NEW_LINE> <INDENT> transposed = [] <NEW_LINE> for item in table[0]: <NEW_LINE> <INDENT> transposed.append([]) <NEW_LINE> <DEDENT> for row in table: <NEW_LINE> <INDENT> for i in range(len(row)): <NEW_LINE> <INDENT> transposed[i].append(row[i]) <NEW_LINE> <DEDENT> <DEDENT> return transposed
Returns a list of columns in table formed by rows
625941bfd486a94d0b98e08d
def _assemble_msg(self, msg_tag, msg_body): <NEW_LINE> <INDENT> return '%s:%s' % (msg_tag, msg_body)
组织消息体 Args: msg_tag : 消息标识 msg_body :消息体
625941bf29b78933be1e55f8
def is_prime3(num): <NEW_LINE> <INDENT> if num == 2: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif num % 2 == 0 or num <= 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> root = _ceil(_sqrt(num)) <NEW_LINE> return _reduce(lambda acc, d: False if not acc or num % d == 0 else True, range(3, root+1, 2), True)
Tests if a given number is prime. Written with reduce.
625941bf5166f23b2e1a50a1
def extract_cell_mbexp(mbexp, cell_size, cell_buff, cell_ix, cell_iy): <NEW_LINE> <INDENT> import lsst.geom as geom <NEW_LINE> from metadetect.lsst.util import get_mbexp, copy_mbexp <NEW_LINE> start_x, start_y = get_cell_start( cell_size=cell_size, cell_buff=cell_buff, cell_ix=cell_ix, cell_iy=cell_iy, ) <NEW_LINE> bbox_begin = mbexp.getBBox().getBegin() <NEW_LINE> new_begin = geom.Point2I( x=bbox_begin.getX() + start_x, y=bbox_begin.getY() + start_y, ) <NEW_LINE> extent = geom.Extent2I(cell_size) <NEW_LINE> new_bbox = geom.Box2I( new_begin, extent, ) <NEW_LINE> subexps = [] <NEW_LINE> for band in mbexp.filters: <NEW_LINE> <INDENT> exp = mbexp[band] <NEW_LINE> subexp = exp[new_bbox] <NEW_LINE> assert np.all( exp.image.array[ start_y:start_y+cell_size, start_x:start_x+cell_size ] == subexp.image.array[:, :] ) <NEW_LINE> subexps.append(subexp) <NEW_LINE> <DEDENT> return copy_mbexp(get_mbexp(subexps))
extract a sub mbexp for the specified cell Parameters ---------- mbexp: lsst.afw.image.MultibandExposure The image data cell_size: int Size of the cell in pixels cell_buff: int Overlap buffer for cells cell_ix: int The index of the cell for x cell_iy: int The index of the cell for y Returns -------- mbexp: lsst.afw.image.MultibandExposure The sub-mbexp for the cell
625941bf442bda511e8be364
def test_category_delete_member(self): <NEW_LINE> <INDENT> self.client.force_login(self.team2_member) <NEW_LINE> response = self.client.post(path=self.delete_url) <NEW_LINE> self.assertEqual(response.status_code, 403)
Assert that regular teammembers can not delete Categories
625941bfbf627c535bc13116