Dataset Viewer
Auto-converted to Parquet
anchor
stringlengths
2
528
positive
stringlengths
4
6k
negative
stringlengths
6
6k
방학기간에 소외지역의 청소년을 대상으로 청춘누리 봉사단이 할 수 있는 캠프의 이름은 뭐야
주요 수상기관 교육기부프로그램 개요 4. 대학생 동아리 「청춘누리 봉사단」 □ 청춘누리축제 ◦ (참가대상) 전국 유치원, 초·중·고등학생 ◦ (활동내역) 대학생들이 운영하는 교육기부활동을 청소년들이 직접 체험해봄으로써 학생들이 사고력, 창의력 향상을 도모하고 자신의 꿈을 펼칠 수 있는 장 마련 ◦ (주요성과) 대학생들의 교육기부에 대한 전반적인 이해를 돕고 교육 기부 활동의 우수성 홍보 □ 청춘누리봉사단과 함께하는 교육기부(쏙쏙캠프, 함성소리) ◦ (참가대상) 전국의 초·중학생 ◦ (활동내역) - 쏙쏙캠프 : 방학을 이용하여 상대적으로 교육기부 혜택이 적은 소외 지역을 방문하여 창의력 체험, 진로체험 등을 제공, 배움의 기회 균등 및 꿈을 찾아주는 활동 전개 - 함성소리 : 학기중 토요일마다 수도권에 있는 청소년 대상으로 꿈을 설계하고 지원하는 활동 전개 ◦ (주요성과) 소외지역 청소년 대상 배움의 기회를 제공하고 대학생들의 봉사활동을 장려하여 많은 청소년 대상 멘토 활동 전개
개도국에 IT나눔을 실천한 청년들과 아름다운 동행 □ 미래창조과학부(장관 최문기)와 한국정보화진흥원(원장 장광수)은 12월 18일(수) 오후 2시 10분 과천과학관에서 「2013년도 월드프렌즈 IT봉사단 귀국보고대회」(이하, IT봉사단 귀국보고대회)를 개최하였다. o 정부는 2001년부터 현재까지 전 세계 70여개 개도국에 5,158명의 IT봉사단을 파견한 바 있으며, 「IT봉사단 귀국보고대회」는 매년 개도국에서 활동하고 온 봉사단원들이 서로의 경험을 공유하고 글로벌 역량을 배양하는 ‘소통'과 ‘협력‘의 장(場)으로 운영되고 있다. ※ 월드프렌즈(World Frends Korea, WFK) : 우리나라 해외봉사단사업 통합브랜드 □ 이번 「IT봉사단 귀국보고대회」에는 30개국에 파견되었던 552명의 봉사단원 중 약 300여명의 봉사단원이 참석했으며, 윤종록 제2차관과 주한 외교사절(인도네시아 대사, 코스타리카 대사, 네팔 대사 등)이 참석해 세계의 오지를 누비고 온 봉사단원들을 격려했다. o 윤종록 제2차관은 IT봉사단원들에게“귀한경험을 활용하여 대한민국의 이름을 빛내는 사람이 되기를 바란다”는 당부와 함께“정부는 여러분과 같은 젊은이들이 세계를 무대로 능력을 마음껏 발휘할 수 있는 글로벌 플랫폼을 구축하는데 노력할 계획”이라고 덧붙였다.
Loads sensor filters from an Excel file. Both new style XLSX and oldstyle XLS formats are supported.
def load_sensor_filters_excel(filename, normalise=False, sheet_names=None): sensor_filters = {} with pd.ExcelFile(filename) as excel_file: # default is all sheets if not sheet_names: sheet_names = excel_file.sheet_names for sheet in sheet_names: try: dataframe = excel_file.parse( sheet, index_col=0 ) # the sheet as a DataFrame # OK, we have the data frame. Let's process it... if not _validate_filter_dataframe(dataframe): continue if normalise: dataframe = _normalise_dataframe(dataframe) sensor_filters[sheet] = ( np.array(dataframe.index), dataframe.values.transpose(), ) except xlrd.biffh.XLRDError: continue # except xlrd.biffh.XLRDError as xlrd_error: # TODO: log warning about invalid sheet return sensor_filters
def convert_csv(fname): # Make sure this is an Excel file. if (not is_excel_file(fname)): # Not Excel, so no sheets. return [] # Run soffice in listening mode if it is not already running. run_soffice() # TODO: Make sure soffice is running in listening mode. # # Connect to the local LibreOffice server. context = connect(Socket(HOST, PORT)) # Load the Excel sheet. component = get_component(fname, context) # Iterate on all the sheets in the spreadsheet. controller = component.getCurrentController() sheets = component.getSheets() enumeration = sheets.createEnumeration() r = [] pos = 0 if sheets.getCount() > 0: while enumeration.hasMoreElements(): # Move to next sheet. sheet = enumeration.nextElement() name = sheet.getName() if (name.count(" ") > 10): name = name.replace(" ", "") name = fix_file_name(name) controller.setActiveSheet(sheet) # Set up the output URL. short_name = fname if (os.path.sep in short_name): short_name = short_name[short_name.rindex(os.path.sep) + 1:] short_name = fix_file_name(short_name) outfilename = "/tmp/sheet_%s-%s--%s.csv" % (short_name, str(pos), name.replace(' ', '_SPACE_')) pos += 1 r.append(outfilename) url = convert_path_to_url(outfilename) # Export the CSV. component.store_to_url(url,'FilterName','Text - txt - csv (StarCalc)') # Close the spreadsheet. component.close(True) # clean up os.kill(get_office_proc()["pid"], signal.SIGTERM) # Done. return r
Create an additional feature to metadata by counting number of occurrences in data, for a specific element_type
def create_count_features(metadata, element_type, data, grp_feat, res_feat, feature_suffix): feature_name = 'n_'+ element_type + '_modif' + feature_suffix newfeature = (data.groupby([grp_feat])[res_feat] .count() .reset_index() .fillna(0)) newfeature.columns = [grp_feat, feature_name] metadata = pd.merge(metadata, newfeature, on=grp_feat, how="outer").fillna(0) return metadata
def test(self): count = Counter() for example in self.testing_set: classification = self.classify(example.attributes) if example.CLASS and classification: count['TP'] += 1 elif not example.CLASS and classification: count['FP'] += 1 elif not example.CLASS and not classification: count['TN'] += 1 elif example.CLASS and not classification: count['FN'] += 1 return count
여야 3당 원내대표는 26일 교섭단체 3당 원내대표와 헌정특위(헌법개정 및 정치개혁 특별위원회) 간사들이 모여 무엇을 시작하기로 했어?
더불어민주당 우원식 원내대표와 자유한국당 김성태 대표는 이날 국회의장과 3당 원내대표 회동 직후 기자들과 만난 자리에서 27일부터 여야 교섭단체 대표들이 개헌 협상에 들어가겠다고 밝혔다.
김 원내대표는 이날 국회에서 열린 헌법개정정치개혁·사법개혁특별위원회 회의에서 “문 대통령이 개인적으로 대통령 4년 중임제가 가장 바람직하다고 말했다.
Check if two plane wave expansions are compatible in the sense that they can be added coefficientwise
def compatible(self, other): return (type(other).__name__=="PlaneWaveExpansion" and np.isclose(self.k, other.k) and all(np.isclose(self.k_parallel, other.k_parallel)) and all(np.isclose(self.azimuthal_angles, other.azimuthal_angles)) and self.kind == other.kind and self.reference_point == other.reference_point)
def wcompare( W1, W2, dj ): wavelet = pycwt.wavelet._check_parameter_wavelet('morlet') assert(W1.shape==W2.shape) sj = W1.columns.values dt = pd.Timedelta( W1.index[1] - W1.index[0] ) #dt = 1e5/dt.value #assert(dt==0.01) dt = dt.value / 1e9 data_len = W1.shape[0] scales = np.ones([1, data_len]) * sj[:, None] #print('%s' % (scales)) _W1 = W1.T.values _W2 = W2.T.values S1 = smooth(np.abs(_W1) ** 2 / scales, dt, dj, sj, wavelet.deltaj0) S2 = smooth(np.abs(_W2) ** 2 / scales, dt, dj, sj, wavelet.deltaj0) # cross-wavelet transform _W12 = _W1 * _W2.conj() #! Using a local adapted version of this to allow use with non-Morlet wavelets CHECK! S12 = smooth(_W12 / scales, dt, dj, sj, wavelet.deltaj0) _WCT = np.abs(S12) ** 2 / (S1 * S2) W12 = pd.DataFrame(data=_W12.T, columns=sj, index=W1.index) WCT = pd.DataFrame(data=_WCT.T, columns=sj, index=W1.index) return WCT, W12
Print a list of lines to a file. Note that each line should include the newline character
def print2file(lines, filename): try: outf = open(filename, "w") for l in lines: outf.write(l) outf.close() except Exception, e: sys.exit(str(e))
def list_to_file(l, fn): with open(fn, 'w') as f: for item in sorted(l): f.write('%s\n' % item)
create a shift object with default number of employees this object is the shift to be scheduled
def __init__(self, shift_id, date, start_hour, num_bartenders=1, num_waitresses=1, seniority=0): self.shift_id = shift_id self.date = date self.start_hour = start_hour self.num_bartenders = num_bartenders self.num_waitresses = num_waitresses self.bartenders = [] self.waitresses = [] self.seniority = seniority
def __init__(self, schedule_episodes, total_episodes, final_p, initial_p=1.0): if isinstance(schedule_episodes, float): self.schedule_episodes = int(schedule_episodes * total_episodes) else: self.schedule_episodes = schedule_episodes self.final_p = final_p self.initial_p = initial_p
치과비#돈#먹#쓰#내
먹고 노는 데 쓰는 돈으로 치과비를 내라고 한다.
고시공부는 내 돈 들여서 하는 보험 같은 것이라고 했다.
다름없다, 사람, 신선, 발, 땅, 있다, 마음
그 사람은 발은 땅에 있어도 마음은 언제나 신선이나 다름없다.
옛날 다과상 차림은 녹차, 무지개떡, 밤다식, 생란, 율란, 조란 등이다.
아내의 역할은 무엇인가?
아내의 역할. 1 기도: 간단하지만 강력한 행동. 2 경청: 사람들은 자신이 들리고 싶어 한다. 3 질문하기: 좋은 질문은 생산적인 대화를 촉진한다. 4 숙고하기: 천천히 그리고 성경적으로 생각하라. 5 격려하기: 비난하기보다는 격려하라.
이 기사의 목적은 지역 교회에서 목사의 아내의 역할을 정립하기 위한 성경적 기둥과 기준을 식별하는 것입니다. 이 기사의 주장은 성경이 목사의 아내의 역할을 정의하거나 규정하지 않으므로, 우리는 성경이 그녀의 정체성, 역할 및 여성, 아내, 신자로서의 목적에 대해 가르치는 것에서 목사의 아내로서의 사역의 틀을 유추해야 한다는 것입니다.
Update localization of the widget. This method will be called recursively on all widgets on language change.
def update_translation(self): pass
def set_localization(self, loc, val): self.locales[loc] = val
Use this API to login or register with a Onetime Password (OTP) sent via Email or SMS.
async def loginWithOTP(self, platform=None, body=""): payload = {} if platform: payload["platform"] = platform # Parameter validation schema = UserValidator.loginWithOTP() schema.dump(schema.load(payload)) # Body validation from .models import SendOtpRequestSchema schema = SendOtpRequestSchema() schema.dump(schema.load(body)) url_with_params = await create_url_with_params(api_url=self._urls["loginWithOTP"], proccessed_params="""{"required":[],"optional":[{"name":"platform","in":"query","description":"ID of the application","schema":{"type":"string","default":"Fynd"}}],"query":[{"name":"platform","in":"query","description":"ID of the application","schema":{"type":"string","default":"Fynd"}}],"headers":[],"path":[]}""", platform=platform) query_string = await create_query_string(platform=platform) headers = { "Authorization": "Bearer " + base64.b64encode("{}:{}".format(self._conf.applicationID, self._conf.applicationToken).encode()).decode() } if self._conf.locationDetails: headers["x-location-detail"] = ujson.dumps(self._conf.locationDetails) for h in self._conf.extraHeaders: headers.update(h) exclude_headers = [] for key, val in headers.items(): if not key.startswith("x-fp-"): exclude_headers.append(key) return await AiohttpHelper().aiohttp_request("POST", url_with_params, headers=get_headers_with_signature(urlparse(self._urls["loginWithOTP"]).netloc, "post", await create_url_without_domain("/service/application/user/authentication/v1.0/login/otp", platform=platform), query_string, headers, body, exclude_headers=exclude_headers), data=body, cookies=self._conf.cookies)
def register(): data = request.get_json() username = data['username'] email = data['email'] password = data['password'] confirm_password = data['repassword'] response = sign_up(username, email, password, confirm_password) return response
발목욕에 가장 적합한 물의 종류는 무엇인가?
이 제품은 물을 최대 115도까지 빠르게 가열할 수 있으며, 뜨거운 물을 계속 추가할 필요 없이 스파가 물의 온도를 유지하여 원하는 만큼 발을 스파에 담글 수 있습니다. 이 스파에는 분리 가능한 폼스톤도 함께 제공됩니다.
이온 웨이브 해독 발목욕 작동 원리 최적의 건강을 위해 인체는 80%의 음전하 전자 또는 이온(음이온)과 20%의 양전하 전자 또는 이온(양이온)으로 구성되어 있습니다. 이온 웨이브 발목욕 해독을 위한 권장 사항 해독 발목욕 시리즈를 진행하는 동안 어떤 형태의 해독 프로그램에 참여하는 것이 가장 좋습니다. 이는 정화 반응을 줄이기 위함입니다. 이러한 반응은 일반적으로 매우 경미하고 일시적이며 두통과 피로와 같은 증상을 포함할 수 있습니다.
Create file name for next log Assumes format 'Log_000.txt' Will incriment the number for the next file
def getFileName(self): import glob filename = '/home/pi/Data/Log_000.txt' files = glob.glob("/home/pi/Data/*.txt") if len(files) > 0: files.sort() last_file = files[-1] next_nbr = int(last_file.split('.')[0].split('_')[1]) next_nbr += 1 filename = "{}{}{}".format('/home/pi/Data/Log_', format(next_nbr, '0>3'), '.txt') print("Logging to:", filename) return filename
def create_filename(last_element): return last_element[:-4]
Return a new `~spectral_cube.lower_dimensional_structures.Projection` of the same class with the specified unit. See `astropy.units.Quantity.to` for further details.
def to(self, unit, equivalencies=[], freq=None): return super(Projection, self).to(unit, equivalencies, freq)
def to_unit(self, unit): unit = _find_unit(unit) self.value = _convert_value(self.value, self.unit, unit) self.unit = unit
run a given simulation for N_step iterations returns list of tissue objects at intervals given by skip
def run(tissue_original,simulation,N_step,skip): return [tissue_original.copy()]+[tissue.copy() for tissue in itertools.islice(simulation,skip-1,N_step,skip)]
def step(system, X0=None, T=None, N=None): if isinstance(system, lti): sys = system else: sys = lti(*system) if N is None: N = 100 if T is None: T = _default_response_times(sys.A, N) else: T = asarray(T) U = ones(T.shape, sys.A.dtype) vals = lsim(sys, U, T, X0=X0) return vals[0], vals[1]
Returns the next char from the receive buffer without removing it, or 1 if no data available.
def peek(self): if (self.peek_char): return self.peek_char if self.available(): self.peek_char = self.ser_port.read(1) return self.peek_char return -1
def readPendingChars(self, max=None): if (max is not None) and (max <= 0): return b'' # ===> if self.buf: if max and (len(self.buf) > max): got, self.buf = self.buf[0:max], self.buf[max:] else: got, self.buf = self.buf, b'' return got # ===> if self.eof: return b'' # ===> try: sel = select.select([self.fd], [], [self.fd], 0) except OSError: # select error occurs if self.fd been closed # treat like EOF self.eof = 1 return b'' # ===> if sel[0]: got = os.read(self.fd, self.chunkSize) if got: if max and (len(got) > max): self.buf = got[max:] return got[:max] # ===> else: return got # ===> else: self.eof = 1 return b'' # ===> else: return b'' # ===>
Return the Geometric Mean Longitude of the Sun in degrees julianCenturies number of Julian centuries since J2000.0
def getSunGeometricMeanLongitude(self, julianCenturies): longitude = 280.46646 + julianCenturies * (36000.76983 + 0.0003032 * julianCenturies) while (longitude > 360.0): longitude -= 360.0 while (longitude < 0.0): longitude += 360.0 return longitude # in degrees
def get_star_longitude(star, jd): from jyotisha.panchaanga.temporal import data import os swe.set_ephe_path(os.path.dirname(data.__file__)) (long, lat, _, _, _, _) = swe.fixstar_ut(star, jd)[0] return long
Test that the Unexpected API Error Exception is raised for an exception from Open Exchange Rates API
def test_exchange_rate_unexpected_api_error(self, mocked_request): mocked_request.return_value.status_code = 401 mocked_request.return_value.json.return_value = {"description": "Invalid App ID"} with self.assertRaises(UnexpectedAPIErrorException) as context: sync_currency_exchange_rates.apply(args=()).get() assert str(context.exception) == "Invalid App ID"
def test_security_error_case(self) -> None: with pytest.raises(ClientSecurityError): handle_response_errors( error_source=ErrorSource.SHIPENGINE.value, error_type=ErrorType.SECURITY.value, error_code=ErrorCode.UNAUTHORIZED.value, )
calibrateCameraAruco(corners, ids, counter, board, imageSize, cameraMatrix, distCoeffs[, rvecs[, tvecs[, flags[, criteria]]]]) > retval, cameraMatrix, distCoeffs, rvecs, tvecs
def calibrateCameraAruco(corners, ids, counter, board, imageSize, cameraMatrix, distCoeffs, rvecs=None, tvecs=None, flags=None, criteria=None): pass
def estimatePoseCharucoBoard(charucoCorners, charucoIds, board, cameraMatrix, distCoeffs, rvec=None, tvec=None): pass
Changes initial value of a constant in the equation according to new values of x0 and y0.
def change_initial_condition(self, x0: float = None, y0: float = None) -> None: if x0 is not None: self.x0 = x0 if y0 is not None: self.y0 = y0 self._const = (self.y0 + self.x0**2 + 1) * np.exp(-(self.x0**2))
def set_initial_conditions(self, initial): self.series[..., 0] = initial
인사 관리자는 얼마의 돈을 벌까요?
Payscale.com에 따르면 인사 관리자의 급여 범위는 $60,000에서 시작하여 지역 인사 관리자의 경우 Salary.com에 따르면 약 $147,484에 이릅니다. OOH에 따르면 인사 관리자의 하위 10%는 $59,020 미만을 벌었고, 상위 10%는 $173,140 이상을 벌었습니다.
인사 관리자 급여 인사 관리자의 연봉은 얼마인가요? 인사 관리자 급여, 인사 관리자 복리후생 패키지, 인사 관리자 보너스, 인사 관리자 직무 설명, 인사 관리자 통계 및 인사 관리자 채용 공고.
peruse의 정의는 무엇인가?
영어 학습자를 위한 peruse의 정의: 1. (무언가를) 비공식적이거나 편안한 방식으로 살펴보거나 읽다. 2. (무언가를) 매우 주의 깊게 조사하거나 읽다.
peruse의 전체 정의. peruse(동사) : 1. a : 주의 깊게 세밀하게 검토하거나 고려하다 : 연구하다. b : 대충 또는 간단히 훑어보다. 2. : 읽다; 특히 : 주의 깊거나 여유 있게 읽다. peruse는 browse와 매우 유사하다.
Assert that the elements of |l1| and |l2| are equal. Modifies |l1| and |l2| by sorting them.
def _assert_elements_equal(self, l1, l2): self.assertEqual(list(sorted(l1)), list(sorted(l2)))
def ana1(a, b): return sorted(a) == sorted(b)
Initialize XElemLib object. The initialization method is mainly used to initialize a dictionary which houses xelem objects.
def __init__(self): self.type='XElemLibrary' self.xelemDict = {}
def __init__(self): self.root = {}
디즈니랜드의 가장 한가한 시간은 언제인가요?
디즈니랜드에서 가장 한산한 시간대는 다음과 같습니다: 1. 12월의 첫 몇 주. 2. 9월의 첫 번째 화요일부터 11월 중순까지 (콜럼버스 데이의 3일 연휴, 즉 10월의 두 번째 월요일을 제외하고) 3. 1월의 첫 번째 전체 주부터 대통령의 날까지, 즉 2월의 세 번째 월요일을 포함한 3일 연휴.
디즈니랜드의 새로운 '스타워즈' 놀이기구 하이퍼스페이스 마운틴의 앞줄에 앉으세요. 디즈니랜드의 스페이스 마운틴은 스타워즈 포스의 시즌을 맞아 하이퍼스페이스 마운틴으로 변환되었습니다.
__init__(self, Window parent, int id=1, String title=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxDEFAULT_FRAME_STYLE|wxVSCROLL|wxHSCROLL, String name=FrameNameStr) > MDIParentFrame
def __init__(self, *args, **kwargs): newobj = _windows_.new_MDIParentFrame(*args, **kwargs) self.this = newobj.this self.thisown = 1 del newobj.thisown self._setOORInfo(self)
def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets()
최악, 위계질서, 군대
계급 간의 위계질서가 없는 군대는 최악이다.
건빵, 별 사탕, 위문편지 등은 가끔 군대의 추억을 떠올리게 한다.
Gets the dest part of the instruction. Returns 1 on failure or the dest string on success.
def getDest(self): end = self.data.find('=') if end == -1: return -1 return self.data[0:end]
def destination_path(self): if self._destination_path_present: return self._destination_path_value else: raise AttributeError("missing required field 'destination_path'")
목가극과 함께 연극사와 문학사상에까지 무시 못할 발자취를 남겨놓은 것은?
르네상스_연극 당시의 이탈리아에서는 세네카의 영향을 볼 수 있는 인문주의적 연극(특히 비극)이나 가톨릭교회, 특히 학교에서 라틴어 학습을 위해 보존되고 있던 로마 희극, 나아가서는 15세기 후반부터 시작되어 16세기 말에 대유행을 한 목가극 등의 장르도 존재했다. 특히 목가극은 이 시기에 창조된 장르로 베르길리우스의 <농경시>의 대화화에서 시작되었으며, 대개는 전원을 배경으로 하는 젊은 남녀 양치기들의 사랑과 시련을 소재로 했다. 줄거리는 황당무계하나 거기에는 어떤 종류의 심리적 상징주의를 볼 수 있으며, 꿈의 세계, 연애심리의 분석, 추상적이긴 하나 우아한 인간성을 묘사했다. 그리고 프랑스·영국을 비롯한 전 유럽에 파급되고 목가소설과 함께 연극사와 문학사상에까지 무시 못할 발자취를 남겨놓았다.
르네상스_연극 에스파냐 연극의 아버지로 불리는 환 델 엔시나(1469?-1529?)의 <에글로가스(牧歌)>는 드라마풍의 대화로 양치기와 천사가 주요인물이며 중세 성탄제극의 변형이라 하겠다. 그 후 미모스(momos), 즉 가면을 쓴 발레와 파스토라레스(목가극)가 행해졌으나 배우는 빈약한 장비로 도시나 지방을 순회했다. 바르톨로메 데 토르레스 나아로(1521년 사망)의 희곡집 <프로팔라디아>(1517)의 서문은 호라티우스를 따른 5막 형식 등의 연극론이나, 희극과 비극의 구별은 작품면에서 전혀 무시되고 있었다. <하인의 식당> <세라피나> <라 이메네아> 등의 작품이 있고, 특히 마지막 것은 후대의 에스파냐극에서 한 특색이 된 '외투와 칼의 희곡'의 효시라고 하겠다. 이러한 연극은 대도시의 건물 안뜰에서 거행되었으며 상연 때는 소란하기 짝이 없었다고 한다.
Build a WriteProperty request, wait for an answer, and return status [True if ok, False if not].
def write(self, args, vendor_id=0, timeout=10): if not self._started: raise ApplicationNotStarted("BACnet stack not running - use startApp()") args = args.split() self.log_title("Write property", args) try: # build a WriteProperty request iocb = IOCB(self.build_wp_request(args, vendor_id=vendor_id)) iocb.set_timeout(timeout) # pass to the BACnet stack deferred(self.this_application.request_io, iocb) self._log.debug("{:<20} {!r}".format("iocb", iocb)) except WritePropertyException as error: # construction error self._log.exception("exception: {!r}".format(error)) iocb.wait() # Wait for BACnet response if iocb.ioResponse: # successful response apdu = iocb.ioResponse if not isinstance(iocb.ioResponse, SimpleAckPDU): # expect an ACK self._log.warning("Not an ack, see debug for more infos.") self._log.debug( "Not an ack. | APDU : {} / {}".format((apdu, type(apdu))) ) return if iocb.ioError: # unsuccessful: error/reject/abort apdu = iocb.ioError reason = find_reason(apdu) raise NoResponseFromController("APDU Abort Reason : {}".format(reason))
def test_write(self): kwargs = dict() zkj = ZookeeperJournal('zookeeper://dev#foobar', kwargs, 'adminuser', 50) zkj.journal_zk_start() msg = {'user_id': 'user1', 'role': None, 'request_id': 'BAD268C6-AB14-11E6-A7C1-98638C7A8FAA', 'transaction_id': 'BAD268C6-AB14-11E6-A7C1-98638C7A8FAA', 'step': 'commit', 'resource': 'phonebook', 'cm': None} json_msg = json.dumps(msg) compressed_msg = zlib.compress(json_msg.encode()) zkj.write(msg['request_id'], 'commit', msg) kazoo.client.KazooClient.create.assert_called_with( '/BAD268C6-AB14-11E6-A7C1-98638C7A8FAA/commit', value=compressed_msg, makepath=True, acl=zkj.acl)
Prepare batch for BERT. Adds the special tokens to input, creates the token_type_ids and attention mask tensors.
def _prepare_BERT_batch(self, batch): input_ids = [] token_type_ids = [] for i in range(self.batch_size): seq_1 = batch.premise[i].tolist() seq_2 = batch.hypothesis[i].tolist() input_ids.append( self.tokenizer.build_inputs_with_special_tokens(seq_1, seq_2)) token_type_ids.append( self.tokenizer.create_token_type_ids_from_sequences(seq_1, seq_2)) input_ids = torch.LongTensor(input_ids) attention_mask = (input_ids != self.pad_id).long() token_type_ids = torch.LongTensor(token_type_ids) labels = batch.label - 1 return (input_ids, token_type_ids, attention_mask, labels)
def _model_context_input(self, batch) -> Dict[str, Any]: return {'ctxt_tokens': batch.text_vec, 'ctxt_image': batch.image}
Clear only parameter values, not the list of managed parameters. All parameters will be set to None.
def clear_parameter_values(self): for param_name in self.managed_parameters: self.managed_parameters[param_name] = None
def Destroy(self, *args): return _Interface.Interface_ParamSet_Destroy(self, *args)
Constructs a private and public raw RSA MKP using the private key in the raw RSA keyring.
def raw_rsa_mkps_from_keyring(keyring): # type: (RawRSAKeyring) -> (MasterKeyProvider, MasterKeyProvider) private_key = keyring._private_wrapping_key private_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), ) public_pem = private_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) private_key_mkp = RawMasterKey( provider_id=keyring.key_namespace, key_id=keyring.key_name, wrapping_key=WrappingKey( wrapping_algorithm=keyring._wrapping_algorithm, wrapping_key=private_pem, wrapping_key_type=EncryptionKeyType.PRIVATE, ), ) public_key_mkp = RawMasterKey( provider_id=keyring.key_namespace, key_id=keyring.key_name, wrapping_key=WrappingKey( wrapping_algorithm=keyring._wrapping_algorithm, wrapping_key=public_pem, wrapping_key_type=EncryptionKeyType.PUBLIC, ), ) return private_key_mkp, public_key_mkp
def vscf_rsa_import_public_key(self, ctx, raw_key, error): vscf_rsa_import_public_key = self._lib.vscf_rsa_import_public_key vscf_rsa_import_public_key.argtypes = [POINTER(vscf_rsa_t), POINTER(vscf_raw_public_key_t), POINTER(vscf_error_t)] vscf_rsa_import_public_key.restype = POINTER(vscf_impl_t) return vscf_rsa_import_public_key(ctx, raw_key, error)
미시시피의 날씨는 어떤가요?
미시시피의 날씨는 보통 해마다 꽤 신뢰할 수 있었습니다. 긴 여름 동안 높은 습도는 90-100도(화씨) 온도를 더욱 찌는 듯하게 만들었습니다. 공기가 당신을 짓누르는 듯한 진정한 여름입니다. 겨울에는 온도가 보통 온화하고 비가 내립니다. 그러나 최근 몇 년 동안 북부 미시시피는 깊은 한파와 강설을 경험했습니다. 겨울철에 온도가 급격히 떨어지는 날이 한두 번 있는 것은 드문 일이 아닙니다.
문장: '날씨 어때?' vs '날씨가 어떤가요?' 안녕하세요, 이 질문은 '날씨 어때?'와 '날씨가 어떤가요?'의 차이에 관한 것입니다. (저는 이 질문들에 대한 스레드를 읽었습니다.) 제가 접한 책에서는 '날씨가 어떤가요?'라는 질문에 다음과 같이 답변하고 있습니다: 맑아요/흐림/안개 낀/맑음/스모그/바람이 불어요/습해요/후덥지근해요/비가 와요/이슬비가 내려요/눈이 와요.
Create a new query by adding qr old query fpred failing predicate idxs list of failing predicate
def mkNewQuery(self, qr, fpred, t_flags, f_flags): self.log.info("Creating a new query ...") body = qr.body() pred = None for p in self.preds: if fpred.decl().eq(p.decl()): pred = p pred_vars = pred.children() false_vars = self.mkVars(f_flags, qr) true_vars = self.mkVars(t_flags, qr) not_vars = [z3.Not(ix) for ix in false_vars] exist_vars, body = stripQuantifierBlock(qr) true_false_vars = not_vars + true_vars + [qr.ctx] new_vars_conjunct = z3.Not(z3.And(*true_false_vars)) if len(not_vars + true_vars) >= 2 else z3.Not(*true_false_vars) and_predicate = z3.And(*[body,new_vars_conjunct,qr.ctx]) if debug_cex: print "New Conjunct:", and_predicate new_exist_vars = self.existVars(exist_vars, true_false_vars) new_query = z3.Exists(new_exist_vars,and_predicate) if debug_cex: print "NEW Query:\n", new_query #print "NEW Query:\n", new_query return new_query
def get_start_query(subj, pred, obj, table_name): kind = get_kind(subj, pred, obj) query = f"""SELECT cs.value, cp.value, co.value FROM {table_name} INNER JOIN catalog AS cs ON subject = cs.id INNER JOIN catalog AS cp ON predicate = cp.id INNER JOIN catalog AS co ON object = co.id """ if kind == 'spo': query += f"""WHERE subject = ? AND predicate = ? AND object = ? ORDER BY subject, predicate, object""" return query, (subj, pred, obj) elif kind == '???': query += "ORDER BY subject, predicate, object" # query += "ORDER BY predicate, object, subject" # query += "ORDER BY object, subject, predicate" return query, [] elif kind == 's??': query += f"""WHERE subject = ? ORDER BY subject, predicate, object""" return query, [subj] elif kind == 'sp?': query += f"""WHERE subject = ? AND predicate = ? ORDER BY subject, predicate, object""" return query, (subj, pred) elif kind == '?p?': query += f"""WHERE predicate = ? ORDER BY predicate, object, subject""" return query, [pred] elif kind == '?po': query += f"""WHERE predicate = ? AND object = ? ORDER BY predicate, object, subject""" return query, (pred, obj) elif kind == 's?o': query += f"""WHERE object = ? AND subject = ? ORDER BY object, subject, predicate""" return query, (obj, subj) elif kind == '??o': query += f"""WHERE object = ? ORDER BY object, subject, predicate""" return query, [obj] else: raise Exception(f"Unkown pattern type: {kind}")
Get all directories in the analysis output directory corresponding to those that are in the self.genotypes attribute.
def get_all_dirs(self, in_dir): all_dirs = next(os.walk(in_dir))[1] self.dirs_to_analyze = [] for dir in all_dirs: genotype_exists = False for genotype in self.genotypes: if genotype in dir: genotype_exists = True break if genotype_exists == True: full_dir = os.path.join(in_dir, dir) self.dirs_to_analyze.append(full_dir) assert len(self.dirs_to_analyze) != 0, 'No dirs loaded; check in_dir.'
def paths(self): # type: () -> EncodingOutputPathsForOutput return self._paths
A generator function to be used to delete all the segments and subsegments referenced in a manifest.
def get_segments_to_delete_iter(self, req): if not check_utf8(wsgi_to_str(req.path_info)): raise HTTPPreconditionFailed( request=req, body='Invalid UTF8 or contains NULL') vrs, account, container, obj = req.split_path(4, 4, True) if six.PY2: obj_path = ('/%s/%s' % (container, obj)).decode('utf-8') else: obj_path = '/%s/%s' % (wsgi_to_str(container), wsgi_to_str(obj)) segments = [{ 'sub_slo': True, 'name': obj_path}] if 'version-id' in req.params: segments[0]['version_id'] = req.params['version-id'] while segments: # We chose not to set the limit at max_manifest_segments # in the case this value was decreased by operators. # Still it is important to set a limit to avoid this list # growing too large and causing OOM failures. # x10 is a best guess as to how much operators would change # the value of max_manifest_segments. if len(segments) > self.max_manifest_segments * 10: raise HTTPBadRequest( 'Too many buffered slo segments to delete.') seg_data = segments.pop(0) if 'data' in seg_data: continue if seg_data.get('sub_slo'): try: segments.extend( self.get_slo_segments(seg_data['name'], req)) except HTTPException as err: # allow bulk delete response to report errors err_body = err.body if six.PY3 and isinstance(err_body, bytes): err_body = err_body.decode('utf-8', errors='replace') seg_data['error'] = {'code': err.status_int, 'message': err_body} # add manifest back to be deleted after segments seg_data['sub_slo'] = False segments.append(seg_data) else: if six.PY2: seg_data['name'] = seg_data['name'].encode('utf-8') yield seg_data
def delete_groups( self, digs ): for ig in digs: try: del self.vertices[ig] del self.cells[ig] self.igs.remove( ig ) except KeyError: pass
Unzips archivePath (zip file) into targetPath If archive (zip) contains several files, takes 1st one Returns True/False
def unzipFile ( self, archivePath = None, targetPath = None ) : utilities.error = "" if archivePath is None : return False # archive does not exist if not utilities.filePresent( archivePath ) : return False if targetPath is None : return False # by default everything is OK result = True # zip file handler (object) archiveFile = zipfile.ZipFile( archivePath ,'r') archivedFiles = archiveFile.namelist() if utilities.isEmpty( archivedFiles ) : return False # temporary name temporaryName = "__archiver__" # takes first archived file item = archivedFiles [ 0 ] # unzips in temporary file try : # opens temporary file targetFile = file( temporaryName, "wb") # reads content of file in ZIP archive and writes it at once *** MEMORY ??? targetFile.write( archiveFile.read( item ) ) targetFile.close() # copy temporary file into definitive one (works only is unzip was OK) utilities.fileCopy( temporaryName, targetPath ) except Exception, exception : utilities.error = str( exception ) result = False # closes zip file try : archiveFile.close() except Exception, exception : result = False # deletes temporary file utilities.fileDelete( temporaryName ) return result
def verify_archive(self, run, raw_data_path, compressed_data_path): archive = tarfile.open(compressed_data_path) for path in os.listdir(raw_data_path): try: archive_info = archive.getmember(os.path.join(run.results_folder, path)) if archive_info.size < 0: msg = "File {} is corrupt in archive".format(path) self.status.progress_func({'type': 'compress', 'message': msg}) return False except KeyError: msg = "File {} is not in archive".format(path) self.status.progress_func({'type': 'compress', 'message': msg}) return False msg = "Archive verified." self.status.progress_func({'type': 'compress', 'message': msg}) return True
Kabsch alignment of X into Y. Assumes X,Y are both (Dims x N_points). See below for wrapper.
def kabsch_torch(X, Y): # center X and Y to the origin X_ = X - X.mean(dim=-1, keepdim=True) Y_ = Y - Y.mean(dim=-1, keepdim=True) # calculate convariance matrix (for each prot in the batch) C = torch.dot(X_, Y_.t()) # Optimal rotation matrix via SVD V, S, W = torch.svd(C) # determinant sign for direction correction d = (torch.det(V) * torch.det(W)) < 0.0 if d: S[-1] = S[-1] * (-1) V[:, -1] = V[:, -1] * (-1) # Create Rotation matrix U U = torch.dot(V, W) # calculate rotations X_ = torch.dot(X_.t(), U).t() # return centered and aligned return X_, Y_
def rotationTransformMatrix(X, Y, angle, X_dst=None, Y_dst=None): import numpy as np H_rot = np.array( [[np.cos(angle), -np.sin(angle), 0], [np.sin(angle), np.cos(angle), 0], [0, 0, 1]] ) if X_dst == None: X_slim = X[0, :] Y_slim = Y[:, 0] x0_src = np.floor(np.min(X_slim)).astype(np.int) y0_src = np.floor(np.min(Y_slim)).astype(np.int) x1_src = np.ceil(np.max(X_slim)).astype(np.int) y1_src = np.ceil(np.max(Y_slim)).astype(np.int) coords = np.hstack(( np.dot(H_rot, np.array([[x0_src], [y0_src], [1]])), np.dot(H_rot, np.array([[x0_src], [y1_src], [1]])), np.dot(H_rot, np.array([[x1_src], [y0_src], [1]])), np.dot(H_rot, np.array([[x1_src], [y1_src], [1]])) )) x0_dst, y0_dst, dump = np.floor(np.min(coords, axis=1)).astype(np.int) x1_dst, y1_dst, dump = np.ceil(np.max(coords, axis=1)).astype(np.int) dxy_dst = min(np.min(np.abs(X_slim[1:]-X_slim[:-1])), np.min(np.abs(Y_slim[1:]-Y_slim[:-1]))) X_dst, Y_dst = np.meshgrid( np.linspace(x0_dst, x1_dst, int((x1_dst-x0_dst)/dxy_dst)+1), np.linspace(y0_dst, y1_dst, int((y1_dst-y0_dst)/dxy_dst)+1) ) # # Calculate a rotated grid by applying the rotation. # XY_dst = np.vstack((X_dst.ravel(), Y_dst.ravel(), np.ones(X_dst.size))) XY_src_ = np.dot(np.linalg.inv(H_rot), XY_dst) X_indices = XY_src_[0, :].reshape(X_dst.shape) Y_indices = XY_src_[1, :].reshape(X_dst.shape) H = calcTransformMatrix((Y, X), (Y_indices, X_indices)) return H, X_dst, Y_dst
This function takes outer edge/line as an input and it returns all triangle edges it intersects with.
def get_intersecting_edges(self, edge): result = [] for edge_ in self.edges: if edge.is_intersect(edge_): result.append(edge_) return result
def findTheFace(source_in: Inner) -> list: # initialize the list face = list() # starting the face with the source inner node. face.append(source_in) # initialize the ending inner node we will be using for comparison end_in = None # As long as we haven't looped back around, go through the following process. while source_in != end_in: # inner: find adjacent outer face.append(face[-1].getAdjOuter()) # outer: go to right seg face.append(face[-1].getRightSegment()) # segment: go to right outer face.append(face[-1].getRightOuter()) # outer: then adj inner face.append(face[-1].getAdjInner()) # then left inner and repeat. # set this inner node as our node to compare to our starting node. end_in = face[-1].getLeftInner() face.append(end_in) return face
Returns list of slip trace angles. Returns list Slip trace angles based on grain orientation in calcSlipTraces.
def slipTraces(self): if self.slipTraceAngles is None: self.calcSlipTraces() return self.slipTraceAngles
def printSlipTraces(self): self.calcSlipTraces() if self.averageSchmidFactors is None: raise Exception("Run 'calcAverageGrainSchmidFactors' on the EBSD map first") for ssGroup, colour, sfGroup, slipTrace in zip( self.phase.slipSystems, self.phase.slipTraceColours, self.averageSchmidFactors, self.slipTraces ): print('{0}\tColour: {1}\tAngle: {2:.2f}'.format(ssGroup[0].slipPlaneLabel, colour, slipTrace * 180 / np.pi)) for ss, sf in zip(ssGroup, sfGroup): print(' {0} SF: {1:.3f}'.format(ss.slipDirLabel, sf))
환자, 자기, 결정권, 보장하다
이것은 환자에게 자기 결정권을 보장하는 것이다.
재주라는 것은 예절, 음악, 활쏘기, 글쓰기, 말타기, 계산하기다.
Check if all services are alive. If so we have a special banner for top of page.
def all_alive(self): app.logger.debug('Someone wants to know if all are ALIVE') for s in self._services: if not s.is_alive: return False return True
def __is_test_service(self): if self.current_service: return not self.current_service.is_active return False
Reduces the size of all images in the images folder. Saves new image files in downscaled_images folder.
def downscale(size=180): img_path = REPO_PATH / 'images' downscaled_path = REPO_PATH / 'downscaled_images' downscaled_path.mkdir(exist_ok=True) for img_file in list(Path(img_path).glob('*.jpg')): img = cv2.imread(str(img_file)) img = cv2.resize(img, (size, size)) cv2.imwrite(str(downscaled_path / img_file.stem) + '_small.jpg', img)
def resize_images(imdir, imsize): print('resizing {}'.format(imdir)) DIRECTORIES = glob.glob(imdir + '**/') IMAGE_PATHS = glob.glob(imdir + '**/*jpg', recursive=True) IMAGE_PATHS.extend(glob.glob(imdir + '**/*png', recursive=True)) IMAGE_PATHS.extend(glob.glob(imdir + '**/*gif', recursive=True)) IMAGE_PATHS.extend(glob.glob(imdir + '**/*jpeg', recursive=True)) try: os.stat(imdir + '../resized') except: os.makedirs(imdir + '../resized') for directory in tqdm.tqdm(DIRECTORIES): new_directory = directory.split('/')[-2] if new_directory != '../resized': try: os.stat(imdir + '../resized/{}/'.format(new_directory)) except: os.makedirs(imdir + '../resized/{}/'.format(new_directory)) for image_path in tqdm.tqdm(IMAGE_PATHS): image_name = image_path.split('/')[-1] image = cv2.imread(image_path) newimage = cv2.resize(image, (imsize, imsize), interpolation = cv2.INTER_AREA) imagenp = numpy.array(newimage) if image_path.split('/')[-3] == 'Others': subdir = image_path.split('/')[-2] try: os.stat(imdir + '../resized/Others/{}/'.format(subdir)) except: os.makedirs(imdir + '../resized/Others/{}/'.format(subdir)) cv2.imwrite(imdir + '../resized/Others/{}/{}'.format(subdir,image_name), imagenp) else: class_name = image_path.split('/')[-2] if not cv2.imwrite(imdir + '../resized/{}/{}'.format(class_name,image_name), imagenp): print('didnt write ' + imdir + '../resized/{}/{}'.format(class_name,image_name)) return(imdir + '../resized/')
Prints the FR and CDR regions and their corresponding seq. It returns a `list` of 2 `dict`.
def output(self, regionlst): self.regionlst = regionlst self.regiondict= {} if self.scheme == "kabat": print("Annotation in Kabat scheme:") elif self.scheme == "chothia": print("Annotation in Chothia scheme:") elif self.scheme == "contact": print("Annotation in Contact scheme:") else: print("Annotation in IMGT scheme:") if self.chain == "L": print("L-FR1: ", self.regionlst[0]) print("L-CDR1: ", self.regionlst[1]) print("L-FR2: ", self.regionlst[2]) print("L-CDR2: ", self.regionlst[3]) print("L-FR3: ", self.regionlst[4]) print("L-CDR3: ", self.regionlst[5]) print("L-FR4: ", self.regionlst[6]) for region, seq in zip(["L-FR1", "L-CDR1", "L-FR2", "L-CDR2", "L-FR3", "L-CDR3", "L-FR4"], self.regionlst): self.regiondict[region] = seq return self.regiondict else: print("H-FR1: ", self.regionlst[0]) print("H-CDR1: ", self.regionlst[1]) print("H-FR2: ", self.regionlst[2]) print("H-CDR2: ", self.regionlst[3]) print("H-FR3: ", self.regionlst[4]) print("H-CDR3: ", self.regionlst[5]) print("H-FR4: ", self.regionlst[6]) for region, seq in zip(["H-FR1", "H-CDR1", "H-FR2", "H-CDR2", "H-FR3", "H-CDR3", "H-FR4"], self.regionlst): self.regiondict[region] = seq return self.regiondict
def __init__ (self): for self.chr in Variables.order[1]: for self.order in sorted(Variables.order[1][self.chr].keys()): self.contig = Variables.order[1][self.chr][self.order] self.chr1, self.order1, self.orientation1 = Variables.agp[1][self.contig].split() if self.contig in Variables.agp[2]: self.chr2, self.order2, self.orientation2 = Variables.agp[2][self.contig].split() print ("{}\t{}\t{}\t{}\t{}\t{}\t{}".format(self.chr1, self.order1, self.orientation1, self.chr2, self.order2, self.orientation2, self.contig)) else: print ("{}\t{}\t{}\t{}\t{}\t{}\t{}".format(self.chr1, self.order1, self.orientation1, "", "", "", self.contig))
비밀, 철저하다, 지키다
비밀은 굉장히 철저하게 지켜져야 했다.
철저한 글다듬기는 단어, 문장, 글 수준에서 이루어질 필요가 있다.
현재 두바이는 몇 시입니까?
두바이와 아랍에미리트의 현지 시간은 현재 오후 3시 23분입니다. 오늘은 2015년 10월 8일 목요일입니다. 두바이와 아랍에미리트의 시간대는 아랍에미리트 표준시입니다. 아랍에미리트 표준시는 협정 세계시(UTC)/그리니치 평균시(GMT)보다 4시간 빠릅니다.
두바이, 아랍에미리트, 시간. 현재 두바이(아랍에미리트 시간대)의 현지 시간을 표시하는 시계. 두바이, 아랍에미리트, 지도. 확대된 지도 보기. [ 두바이 UAE 공항 ] [ 두바이 UAE 시간 ] [ 두바이 UAE 지도 ] [ 두바이 UAE 부동산 ]
This method contains all the bootstrapping logic used to bootstrap the features. Only used by the train_net.
def _bootstrap_ops(self, net, copied_cur_layer, indices, iteration): # draw features based upon the bootstrapped indices bootstrapped_features = net.Gather( [copied_cur_layer, indices], net.NextScopedBlob("bootstrapped_features_{}".format(iteration)), ) bootstrapped_features = schema.Scalar( (np.float32, self.input_dims), bootstrapped_features ) return bootstrapped_features
def init_setup(self, args: argparse.Namespace, stage=None) -> None: transform = transforms.Compose( [ transforms.ToTensor(), ] ) # load MNIST train dataset with transformation and convert to numpy mnist_full = TorchMNIST(self.data_dir, train=True, transform=transform) mnist_x = next(iter(DataLoader(mnist_full, batch_size=len(mnist_full))))[0].numpy() mnist_y = next(iter(DataLoader(mnist_full, batch_size=len(mnist_full))))[1].numpy() # take train sample and delete from remaining pool train_sample = np.random.choice(len(mnist_y), self.n_train_images, replace=False) self.data_train = BaseDataset(mnist_x[train_sample], mnist_y[train_sample]) mnist_x = np.delete(mnist_x, train_sample, axis=0) mnist_y = np.delete(mnist_y, train_sample, axis=0) # take val sample and delete from remaining pool val_sample = np.random.choice(len(mnist_y), self.n_validation_images, replace=False) self.data_val = BaseDataset(mnist_x[val_sample], mnist_y[val_sample]) mnist_x = np.delete(mnist_x, val_sample, axis=0) mnist_y = np.delete(mnist_y, val_sample, axis=0) # assign remaining pool as unlabelled & test self.data_unlabelled = BaseDataset(mnist_x, mnist_y) self.data_test = self.data_unlabelled print(f"\nInitial training set size: {len(self.data_train)} - shape: {self.data_train.data.shape}") print(f"Initial unlabelled pool size: {len(self.data_unlabelled)} - shape: {self.data_unlabelled.data.shape}") print(f"Validation set size: {len(self.data_val)} - shape: {self.data_val.data.shape}\n") assert self.data_train.data.shape[1:] == torch.Size( [1, 28, 28] ), f"invalid data_train shape: {self.data_train.data.shape[1:]}" assert self.data_val.data.shape[1:] == torch.Size( [1, 28, 28] ), f"invalid data_val shape: {self.data_val.data.shape[1:]}" assert self.data_unlabelled.data.shape[1:] == torch.Size( [1, 28, 28] ), f"invalid data_unlabelled shape: {self.data_unlabelled.data.shape[1:]}"
Return the best cost for the given expression, or None if the best cost is not available
def best_cost_for_expression( exprenv: Union[str, ExprWithEnv], rules: str, time_budget: TimeBudget ) -> Optional[TypeBestCost]: del time_budget return best_results.best_cost_for_exp(exprenv, rules)
def min_cost_flow_cost(G, demand = 'demand', capacity = 'capacity', weight = 'weight'): return network_simplex(G, demand = demand, capacity = capacity, weight = weight)[0]
A platform independent function that will produce a keylogger that is specific to the system in question.
def getKeyLogger(): if 'linux' == sys.platform: from keylogger.linuxkeylogger import LinuxKeyLogger return LinuxKeyLogger() elif 'windows' == sys.platform: from keylogger.windowskeylogger import WindowsKeyLogger return WindowsKeyLogger() return None
def get_logger(name): ...
Analyze the setup, get convergence and capacitance information, populate all_sweep for each item which corresponds to option_name.
def populate_q3d_all_sweep(self, all_sweep: Dict, a_q3d: 'QQ3DRenderer', item: str, option_name: str): #Analyze said solution setup. a_q3d.analyze_setup(a_q3d.pinfo.setup.name) # If 'LastAdaptive' is used, then the pass_number won't affect anything. # If 'AdaptivePass' is used, then the pass_number is used. convergence_df, convergence_txt = a_q3d.pinfo.setup.get_convergence() target, current, pass_min = self._parse_text_from_q3d_convergence( convergence_txt) is_converged = self._test_if_q3d_analysis_converged( target, current, pass_min) cap_matrix = a_q3d.get_capacitance_matrix(variation='', solution_kind='LastAdaptive', pass_number=1) sweep_values = Dict() sweep_values['option_name'] = option_name #sweep_values['option_name'] = option_path[-1] sweep_values['convergence_target'] = target sweep_values['convergence_current'] = current sweep_values['min_number_passes'] = pass_min sweep_values['is_convergence'] = is_converged sweep_values['capacitance'] = cap_matrix sweep_values['convergence_data'] = convergence_df all_sweep[item] = sweep_values
def generate_optiparametric_setup(parameter_sweep_list): return ["NAME:" + Hfss.OPTEMETRIC_SETUP_NAME, "IsEnabled:=", True, ["NAME:ProdOptiSetupDataV2", "SaveFields:=", False, "CopyMesh:=", False, "SolveWithCopiedMeshOnly:=", True], ["NAME:StartingPoint"], "Sim. Setups:=", [Hfss.ANALYSIS_SETUP_NAME], parameter_sweep_list, ["NAME:Sweep Operations"], ["NAME:Goals"]]
Add a dummy element of a given `width` and `height`. Useful for customsized vertical or horizontal spacings.
def custom_spacing(width, height): return c.lift(imgui.dummy, width, height)
def Empty(): return Container(name='(empty)', metadata={}, section_sizes={}, metrics_by_file={})
Create cryptographic key for signing. This function will create a keyfile and stash in the adm_tmp directory
def create_key(self, tmp_keyfile=None): self.tmp_keyfile = tmp_keyfile if self.tmp_keyfile is None: self.tmp_keyfile = adm_tmp \ + '/keyfile.' \ + os.environ['USER'] \ + '.' \ + str(os.getpid()) self.key = self.Fernet.generate_key() try: self.f = open(self.tmp_keyfile, "wb") self.f.write(self.key) os.chmod(self.tmp_keyfile, 0o400) os.chown(self.tmp_keyfile, os.getuid(), os.getgid()) self.f.close() print("Keyfile written to --> {}".format(self.tmp_keyfile)) except Exception as e: print("Error Writing '{}'. Error --> {}". format(self.tmp_keyfile, e))
def create_wallet_key(): wallet = BIP32Node.from_master_secret(ku.get_entropy()) wallet_key = wallet.hwif(as_private=True) return wallet_key
재규어의 무게는 몇 kg입니까?
재규어는 체중에서 상당한 차이를 보입니다. 일반적인 범위는 56-96킬로그램(124-211파운드)일 수 있습니다. 큰 수컷은 159킬로그램(350파운드)까지 나갈 수 있으며, 작은 고양이는 36킬로그램(80파운드)만큼 가벼울 수 있습니다. 수컷은 일반적으로 암컷보다 10%에서 20% 더 큽니다. 재규어에 대한 위키백과 기사의 링크가 제공됩니다.
평균 연필의 무게는 얼마입니까? 평균 재규어의 무게는 얼마입니까? 성체 수컷 재규어는 코에서 꼬리 끝까지 최대 8피트(2.4m)까지 자라며, 어깨 높이는 약 28인치(70cm)이고, 무게는 최대 300파운드(135kg)입니다.
아칸소주에서 장기 요양을 위한 등록 간호사의 급여
아칸소의 장기 요양 간호직 공고에 대한 평균 급여는 전국의 장기 요양 간호직 공고에 대한 평균 급여보다 1% 높습니다. 평균 급여는 전국 주 중 13위에 해당합니다. 델라웨어의 장기 요양 간호직 공고에 대한 평균 급여는 전국의 장기 요양 간호직 공고에 대한 평균 급여보다 12% 낮습니다. 평균 급여는 전국 주 중 39위에 해당합니다.
플로리다 장기 요양 인증 간호 보조원(CNA) 급여. 플로리다 또는 인근 주의 도시별 급여 보고서를 보려면 클릭하십시오. 플로리다 - 탬파 장기 요양 인증 간호 보조원(CNA) 직업. 기본 급여 보고서 | 개인 급여 보고서. 플로리다 - 브래든턴 장기 요양 인증 간호 보조원(CNA) 직업. 기본 급여 보고서 | 개인 급여 보고서.
delete_current_note views. Handle notes/delete/ page call POST. Delete the note passed in POST form for the user.
def delete_current_note(request): try: name = request.POST["name"] note = models.Notes.objects.get(name=name, user=User.objects.get(username=request.user.username)) note.delete() except models.Notes.DoesNotExist as err: # appear whether note does not exist # add error message in request # tag : notes # errors displayed with topper.js messages.error(request, err, extra_tags="notes") except KeyError as err: # appear whether name field is not in request # add error message in request # tag : notes # errors displayed with topper.js messages.error(request, "NAME field is mandatory.", extra_tags="notes") return HttpResponseRedirect(reverse("view_available_notes", args=()))
def delete_comment(request, post_pk, pk=None): if not pk: pklst = request.POST.getlist("delete") else: pklst = [pk] for pk in pklst: Comment.objects.get(pk=pk).delete() return HttpResponseRedirect(reverse("simple_blog.views.post", args=[post_pk]))
넥센은 사직 구장에서 롯데에 4:3으로 승리하면서 2연패의 늪에서 벗어났다.
넥센은 사직에서 롯데를 4-3으로 꺾고 2연패에서 탈출했다.
SK는 문학에서 5연승을 노리던 두산에 6-4로 승리해 2연패에서 벗어났다.
Static method used to add the printer callback to the given list for the given verbose level
def _add_printer(callbacks, verbose, validation_label_letter='v'): if verbose >= 2: return [Tqdm(validation_label_letter=validation_label_letter)] + callbacks elif verbose >= 1: return [Tqdm(validation_label_letter=validation_label_letter, on_epoch=True)] + callbacks else: return callbacks
def create_callbacks(self, parent): super().create_callbacks(parent) self.register_create_table(parent) if self.show_filter: self.register_filter_interface(parent) self.register_show_query(parent)
Increments the win count for a particular type of prize. This value gets stored in the config.
def increment_prize(name: str): _CONFIG.setdefault('prizes', {}).setdefault(name, 0) _CONFIG['prizes'][name] += 1
def inc(self, extra=1): self._count += extra
Checks any given response on being an article and if positiv, passes the response to the pipeline.
def article_parse(self, response, rss_title=None): if not self.helper.parse_crawler.content_type(response): return yield self.helper.parse_crawler.pass_to_pipeline_if_article( response, self.ignored_allowed_domain, self.original_url, rss_title)
def process_response(self, request, response): if (not response.streaming and response.status_code in (200, 404) and response.get('Content-Type', '').startswith('text')): response.content = second_pass_render(request, response.content) response['Content-Length'] = six.text_type(len(response.content)) return response
식도 점액세포내 산성점액질은 어떤 방법을 사용하니?
식도 점액세포내 중성점액질의 검색은 PAS 반응법을, 산성점액질은 AB \( \mathrm{pH} 2.5 \) 염색법을, 산성점액질과 중성점액질의 조성은AB \( \mathrm{pH} 2.5 \)-PAS 염색법을, 산성 점액질 중 sulfomucin은 AB \( \mathrm{pH} 1.0 \) 염색법을, 산성점액질 중 sulfomucin과 sialomucin의 조성은 AF \( \mathrm{pH} 1.7 \)-AB \( \mathrm{pH} 2.5 \) 염색 법과 HID-AB \( \mathrm{pH} 2.5 \) 염색법을 사용하였다.
조운복과 최인장은 메기와 말쥐치의 식도 점액세포들은 중성점액질만을 함유하며, 붕어는 상당량의 산성점액질과 중성점액질이 공존하는 대부분의 점액세포들로 되어있었으나 전어와 참돔의 식도 점액세포내 점액질은 산성점액질과 중성점액질의 혼합성이며, 산성점액질이 더 많은 점액세포들이 약간 섞여 있다고 하였다.
Compute the ratio between class count and total count. Then pick the class with the highest fraction.
def purity(row): ratio = row[('class', 'sum')]/row[('class', 'count')] return max(1.0-ratio, ratio)
def precision(self, clf, X_test, y_test, cls): y_pred = clf.predict(X_test) tp = sum(y_pred[np.where(y_test == cls)] == cls) fp = sum(y_test[np.where(y_pred == cls)] != cls) return tp / (tp + fp)
plotly_study.graph_objs.Line is deprecated. Please replace it with one of the following more specific types plotly_study.graph_objs.scatter.Line plotly_study.graph_objs.layout.shape.Line etc.
def __init__(self, *args, **kwargs): warnings.warn( """plotly_study.graph_objs.Line is deprecated. Please replace it with one of the following more specific types - plotly_study.graph_objs.scatter.Line - plotly_study.graph_objs.layout.shape.Line - etc. """, DeprecationWarning, ) super(Line, self).__init__(*args, **kwargs)
def DrawLine(self, *args, **kw):
주로 폐에 영향을 미치지만, 신장, 림프절 및 수막에서도 발생할 수 있습니다.
결핵은 일반적으로 폐에 영향을 미치지만, 이 질병은 위장관 및 비뇨기계, 뼈, 관절, 신경계, 림프절, 피부를 포함한 다른 장기로 퍼질 수 있습니다. 결핵(TB)은 결핵균(Mycobacterium tuberculosis) 감염으로 인해 발생하는 특정 질병으로, 신체의 거의 모든 조직이나 장기에 영향을 미칠 수 있으며, 이 질병의 가장 흔한 발생 부위는 폐입니다. 1차 결핵은 일반적으로 경미하거나 무증상인 국소 폐 감염입니다.
개에서 림프종은 주로 골수, 흉선, 림프절 및 비장의 림프 조직에 영향을 미치지만, 피부, 눈, 신장, 뇌, 고환, 전립선 및 뼈를 포함한 다른 장기도 영향을 받을 수 있습니다. 림프종의 두 가지 기본 형태가 인식되었습니다: B세포 림프종과 T세포 림프종.
Tuple of i, j coordinates of the grid points. (dependent of the grid's cornered or centered representation.)
def ij_coordinates(self): x = np.arange(self.nx) y = np.arange(self.ny) return np.meshgrid(x, y)
def createGrid(nx, ny, include_center = False): direction = 0 positions = [] if (nx > 1) or (ny > 1): half_x = int(nx/2) half_y = int(ny/2) for i in range(-half_y, half_y+1): for j in range(-half_x, half_x+1): if ((i==0) and (j==0)) and not include_center: continue else: if ((direction%2)==0): positions.append([j,i]) else: positions.append([-j,i]) direction += 1 return positions
Plot a bar chart of the odds ratio for features in a logistic regression model from `sklearn`.
def plot_logistic_regression_odds_ratio(coefs, top_n=1, columns=None, title=None, plotting_context='notebook'): with sns.plotting_context(plotting_context): odds_ratio = pd.Series(np.exp(coefs.ravel()), index=columns) if isinstance(top_n, int): odds_ratio = odds_ratio.loc[odds_ratio.sort_values(ascending=False)[ :top_n].index] elif isinstance(top_n, float): odds_ratio = odds_ratio.loc[odds_ratio.sort_values( ascending=False).index] odds_ratio = odds_ratio[odds_ratio > top_n] ax = odds_ratio.plot.barh(color='C0') ax.set_xlabel('Change in odds ratio') ax.set_ylabel('Feature') if title: ax.set_title(title) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) plt.tick_params(axis='both', which='both', left=False, bottom=False) return ax
def plot_balance_class(classes): unique, counts = np.unique(classes, return_counts=True) plt.bar(unique, counts) plt.title('Class Frequency') plt.xlabel('Class') plt.ylabel('Frequency') plt.show()
Haplopappus에서 체세포가 배양에 의하여 부정배로 되는 중간 단계의 dome 모양의 소집괴를 이루는 조직체는 뭐라고 불러?
Tanaka 등은 Haplopappus에서 체세포가 배양에 의하여 부정배로 되는 중간 단계의 dome 모양의 소집괴를 이루는 조직체로 callus와 부정배의 중간단계의 효율 좋고 유전적으로 안정적인 증식을 하는 조직체로 소집괴가 \( 5 \sim 10 \mathrm{mm} \) 정도가 되었을 때 분할하여 새로운 소집괴(2차 신초원기)를 형성하여 증식하는 조직을 shoot primordium(신초원기)라고 명명하였다.
Neil 등에 의하면 엽록체와 잎의 발달은 서로 매우 밀접한 관계가 있고 엽록체의 발달은 핵내의 유전자와 엽록체가 가지고 있는 유전자에 의해 지배되지만 보다 결정적인 역할을 하는 것은 핵내의유전자인 것으로 보고하였다. Ronald 등에 의하면 엽록체의 발달은 초기단계, 광합성 기구 합성단계, 광합성단계, 노화단계 등 4 부분으로 나눌 수 있으며 초기 단계에서는 식물의 세포 분화가 거의 끝나고, 광합성 기구 합성 단계에서는 엽록체 수의 증가와 엽록체 크기의 증가로 잎의 크기와 부피가 증가하며, 광합성 단계에서는 광합성이 최대로 일어나고, 노화 단계에서는 광합성 기구와 잎의 노화가 함께 일어난다고 하였다.
Tag filtered PDF exporter should generate multiple PDF files for matching report subtrees and skip empty reports.
def test_tag_filtered_pdf(tmpdir): pdf_dir = tmpdir.mkdir("reports").strpath report = TestReport( name="my testplan", entries=[ TestGroupReport( name="Multitest 1", category=ReportCategories.MULTITEST, tags={"simple": {"foo", "bar"}, "color": {"red"}}, ), TestGroupReport( name="Multitest 2", category=ReportCategories.MULTITEST, tags={"simple": {"foo"}, "color": {"blue"}}, ), TestGroupReport( name="Multitest 3", category=ReportCategories.MULTITEST, tags={"simple": {"bar"}, "color": {"green"}}, ), ], ) exporter = TagFilteredPDFExporter( report_dir=pdf_dir, pdf_style=defaults.PDF_STYLE, report_tags=[ "foo", "baz", # this should be skipped {"simple": "bar", "color": ["blue", "green"]}, ], report_tags_all=[ ("foo", "bar"), # this should be skipped {"simple": ("foo", "bar"), "color": "green"}, ], ) export_context = ExportContext() exporter.export(source=report, export_context=export_context) should_exist = [ "report-tags-all-bar__foo.pdf", "report-tags-any-bar__color-blue-green.pdf", "report-tags-any-foo.pdf", ] should_not_exist = [ "report-tags-all-bar__foo__color-green.pdf", "report-tags-any-baz.pdf", ] for path in should_exist: path = os.path.join(pdf_dir, path) assert os.path.exists(path), "Could not generate PDF: {}".format(path) assert os.stat(path).st_size > 0 for path in should_not_exist: path = os.path.join(pdf_dir, path) assert not os.path.exists( path ), "Should not have been generated PDF: {}".format(path)
def _merge_PDFs(self, pdfslides): output_filename = "%s.pdf" % self._get_filename().split(".svg")[0] output_filepath = abspath(join(os.curdir, output_filename)) has_pyPdf = False try: import pyPdf has_pyPdf = True except ImportError: pass if has_pyPdf: logging.info("Using 'pyPdf' to join PDFs to %s", output_filepath) output = pyPdf.PdfFileWriter() inputfiles = [] for slide in pdfslides: inputstream = file(slide, "rb") inputfiles.append(inputstream) reader = pyPdf.PdfFileReader(inputstream) output.addPage(reader.getPage(0)) outputStream = file(output_filepath, "wb") output.write(outputStream) outputStream.close() for f in inputfiles: f.close() else: logging.warning("PyPDF not installed, cannot merge PDF slides")
Randomly choose customers based on density of purchases. Arg is the number to choose. Choosing with replacement.
def choose_customers(self,num=2): out =[] cons = Consumer.objects.all() # fts = [con.fleet_target for con in cons] picked = [] for cntr in range(num): i = random.randint(0,(len(cons)-1)) if i in picked: # pick again but allow it to choose same consumer # reduce likelihood of double build, but not impossible i = random.randint(0,(len(cons)-1)) # pick = random.randint(1,sum(fts)) # i = 0 # val = 0 # while val <= pick: # val += fts[i] # i += 1 # i -= 1 out.append(cons[i]) print "Chose %s" % cons[i].username return out
def _choose_clients(self, c): # select a proportion of clients if c > 1 or c <= 0: raise ValueError(f'The proportion of chosen clients should lie in (0, 1]. Now is {c}') # randomly choose clients idx num = max(c * self.clients_num, 1) idx = [i for i in range(self.clients_num)] np.random.shuffle(idx) idx = idx[:num] return idx
네덜란드 헌법에 따를 때, 의회의 현 의원 및 구 의원과 그 수행원에 대한 보수에 대한 법률안은 어느 경우에 가결할 수 있는가?
네덜란드왕국 헌법 제63조 의회의 현 의원 및 구 의원과 그 수행원에 대한 보수는 법률로 정한다. 의회 양원은 전체 양원 의원 3분의 2 이상이 출석하고 과반수의 동의가 있을 경우에만 해당 사안에 대한 법률안을 가결할 수 있다.
네덜란드왕국 헌법 제119조 네덜란드의 의회의 현 의원 및 구 의원, 장관 및 국무장관은 재임 중 또는 재임 후에 저지른 각종 범죄에 대해 대법원에서 재판을 받는다. 소송 절차는 네덜란드 국왕 칙령 또는 하원 결의안에 따라 진행한다.
Plots Protein Graphs as flattened 3D projections. Requires 3D coordinates to be present in the graph object
def protein_graph_plot_3d( g: dgl.DGLGraph, angle: int, out_path: str = None, figsize: Tuple[int, int] = (10, 7), node_alpha: float = 0.7, node_size_min: float = 20.0, node_size_multiplier: float = 20.0, bg_col: str = "white", out_format: str = ".png", colour_by: str = "degree", edge_col: str = "black", edge_alpha: float = 0.5, ) -> None: # Todo assertions if type(g) is dgl.DGLGraph: node_attrs = ["coords"] g = g.to_networkx(node_attrs=node_attrs) else: assert nx.get_node_attributes( g, "coords" ), "We require coordinate features to draw a 3D plot" # Get node positions pos = nx.get_node_attributes(g, "coords") # print(pos) # Get number of nodes n = g.number_of_nodes() # Get the maximum number of edges adjacent to a single node edge_max = max([g.degree(i) for i in range(n)]) # Define color range proportional to number of edges adjacent to a single node if colour_by == "degree": colors = [plt.cm.plasma(g.degree(i) / edge_max) for i in range(n)] if colour_by == "seq_position": colors = [plt.cm.plasma(i / n) for i in range(n)] # 3D network plot with plt.style.context(("ggplot")): fig = plt.figure(figsize=figsize) ax = Axes3D(fig) # Loop on the pos dictionary to extract the x,y,z coordinates of each node for key, value in pos.items(): xi = value[0] yi = value[1] zi = value[2] # Scatter plot ax.scatter( xi, yi, zi, color=colors[key], s=node_size_min + node_size_multiplier * g.degree(key), edgecolors="k", alpha=node_alpha, ) # Loop on the list of edges to get the x,y,z, coordinates of the connected nodes # Those two points are the extrema of the line to be plotted for i, j in enumerate(g.edges()): x = np.array((pos[j[0]][0], pos[j[1]][0])) y = np.array((pos[j[0]][1], pos[j[1]][1])) z = np.array((pos[j[0]][2], pos[j[1]][2])) # Plot the connecting lines ax.plot(x, y, z, c=edge_col, alpha=edge_alpha) # Set the initial view ax.view_init(30, angle) # Hide the axes ax.set_axis_off() if out_path is not None: plt.savefig(out_path + str(angle).zfill(3) + out_format) plt.close("all") else: plt.show() return
def test_plot3d_projection(data, region): fig = Figure() fig.plot3d( x=data[:, 0], y=data[:, 1], z=data[:, 2], zscale=5, perspective=[225, 30], region=region, projection="R40/10c", style="s1c", fill="green", frame=["ag", "zag"], ) return fig
returns the (max width, max height) of the report This does not take into account any shadows
def get_report_height_width(self): max_width = 0 max_height = 0 for box in self.boxes: tmp = box.x_cm + box.width if tmp > max_width: max_width = tmp tmp = box.y_cm + box.height if tmp > max_height: max_height = tmp max_width += self.report_opts.box_shadow max_width += self.report_opts.littleoffset max_height += self.report_opts.box_shadow max_height += self.report_opts.littleoffset return (max_width, max_height)
def _get_image_size(self): return (3, 32, 32)
Asserts that the two values are not equal. Will raise an exception if the values are equal.
def assert_not_equal(self, first, second, msg=None): self.assertNotEqual(first, second, msg=msg)
def test_not_equal_on_not_equal_attributes(self): a = payloads.LocateRequestPayload( attributes=[ objects.Attribute( attribute_name=objects.Attribute.AttributeName( "Object Group" ), attribute_value=primitives.TextString( value="RoundRobinTestGroup", tag=enums.Tags.OBJECT_GROUP ) ) ] ) b = payloads.LocateRequestPayload( attributes=[ objects.Attribute( attribute_name=objects.Attribute.AttributeName( "Cryptographic Algorithm" ), attribute_value=primitives.Enumeration( enums.CryptographicAlgorithm, value=enums.CryptographicAlgorithm.AES, tag=enums.Tags.CRYPTOGRAPHIC_ALGORITHM ) ) ] ) self.assertTrue(a != b) self.assertTrue(b != a)
Instructed to draw a GKI polymarker. IRAF only implements points for polymarker, so that makes it simple.
def gki_polymarker(self, arg): # record this operation as a tuple in the draw buffer self._plotAppend(self.gki_polymarker, arg) # commit pending WCS changes when draw is found self.wcs.commit() # Reshape to get x's and y's # arg[0] is the num pairs, so: len(arg)-1 == 2*arg[0] verts = gki.ndc(arg[1:]) rshpd = verts.reshape(arg[0], 2) xs = rshpd[:, 0] ys = rshpd[:, 1] # put the normalized data into a Line2D object, append to our list # later we will scale it and append it to the fig. See performance # note in gki_polyline() ll = Line2D(xs, ys, linestyle='', marker='.', markersize=3.0, markeredgewidth=0.0, markerfacecolor=self.markerAttributes.color, color=self.markerAttributes.color) self.__normLines.append(ll)
def insert_line(self, pts): lastidx = len(self.points) # DEBUG make sure num points is divisible by two, or ignore last one? #look at first point and assume all data is similar #works with 2D data only if len(pts[0])==2: #print("insert_line: data appears to be 2D") for i,pt in enumerate(pts): self.points.append( (pts[i][0], pts[i][1], 0) ) if i%2==0: self.polygons.append( [lastidx+1, lastidx+2] ) if len(pts[0])==3: self.points.extend(pts)
verify that SessionManager.checkpoint() creates an image of the suspended session and writes it using the storage system.
def test_checkpoint(self): # Mock the suspend helper, we don't want to suspend our mock objects helper_name = "plainbox.impl.session.manager.SessionSuspendHelper" with mock.patch(helper_name, spec=SessionSuspendHelper) as helper_cls: # Call the tested method self.manager.checkpoint() # Ensure that a fresh instance of the suspend helper was used to # call the suspend() method and that the session state parameter # was passed to it. helper_cls().suspend.assert_called_with( self.context.state, self.storage.location) # Ensure that save_checkpoint() was called on the storage object with # the return value of what the suspend helper produced. self.storage.save_checkpoint.assert_called_with( helper_cls().suspend(self.context.state))
def test_save_checkpoint_for_list(): context.set_context(mode=context.GRAPH_MODE) parameter_list = [] one_param = {} param1 = {} param2 = {} one_param['name'] = "param_test" one_param['data'] = Tensor(np.random.randint(0, 255, [1, 3, 224, 224]), dtype=mstype.float32) param1['name'] = "param" param1['data'] = Tensor(np.random.randint(0, 255, [12, 1024]), dtype=mstype.float32) param2['name'] = "new_param" param2['data'] = Tensor(np.random.randint(0, 255, [12, 1024, 1]), dtype=mstype.float32) parameter_list.append(one_param) parameter_list.append(param1) parameter_list.append(param2) if os.path.exists('./parameters.ckpt'): os.chmod('./parameters.ckpt', stat.S_IWRITE) os.remove('./parameters.ckpt') ckpt_file_name = os.path.join(_cur_dir, './parameters.ckpt') save_checkpoint(parameter_list, ckpt_file_name)
자리, 소리, 지수, 뭉그적거리다, 일어나다
해가 밝아서 자리에서 일어나라는 소리에 지수는 자꾸만 뭉그적거렸다.
재주는 예절, 음악, 활쏘기, 글쓰기, 말타기, 계산하기 등등 이다.
Asserts that two dicts are equal. The dicts can be arbitrarily nested and contain pandas data frames.
def _assert_dict_equal( self, expected: Dict[Any, Any], actual: Dict[Any, Any] ): for key, expected_val in expected.items(): self.assertIn(key, actual, f'Expected key: {key}') actual_val = actual[key] if isinstance(expected_val, dict): self.assertIsInstance(actual_val, dict) self._assert_dict_equal(expected_val, actual_val) elif isinstance(expected_val, pd.DataFrame): self.assertIsInstance(actual_val, pd.DataFrame) pd.testing.assert_frame_equal(expected_val, actual_val) else: self.assertEqual(expected_val, actual_val)
def assert_data_dict_equal(self, real, sample, non_strict=None): non_strict = non_strict or [] self.assertEqual( len(real), len(sample), msg='Number of elements mismatch: {} != {}\n'.format( real.keys(), sample.keys()) ) for key in sample: self.assertIn(key, real) if key not in non_strict: inner_non_strict = subkeys(non_strict, key) self.assert_data_equal( real[key], sample[key], inner_non_strict)
Examines a user's classifiers to determine if they input valid options and a weight equal to 1.0.
def validate_classifiers(self, classifiers): weight = 0.0 for classifier in classifiers: # Verify that the classifier is a valid/known classifier if classifier not in CLASSIFIERS: raise InvalidClassifierError('{} for model {} is not a valid classifier'.format(self.name, classifier)) # Verify that the weight is a valid weight if not (0.0 <= classifiers[classifier] <= 1.0): raise InvalidClassifierWeightError('Model {} has an invalid weight for {} of {}.'.format( self.name, classifier, classifiers[classifier])) # Add weights to weight weight += classifiers[classifier] # Verify that the total weight is equal to 1.00 if weight != 1.0: raise ClassifierWeightError('Model {} weights do not equal 1.0.'.format(self.name)) return classifiers
def is_weighted(self): return self._weighted
Cette fonction copie dans un fichier, tp.xml, le contenue de "s" et retourne le nom du fichier.
def make_file(tp, s): filename = tp + ".xml" with open(filename, 'wb') as f: f.write(s) return filename
def create_tmp (filename, txn, rep): p = svn_look('cat', txn, rep, filename) (fd, tmp) = tempfile.mkstemp() fd = open(tmp, 'w') fd.write(p.communicate()[0]) fd.close() return tmp
Perform an eigen update of the form AA + YY in which Y is a lowrank matrix
def eigenAdd(omega, Q, Y, k): #logging.debug("< eigenAdd >") Parameter.checkInt(k, 0, omega.shape[0]) #if not numpy.isrealobj(omega) or not numpy.isrealobj(Q): # raise ValueError("Eigenvalues and eigenvectors must be real") if omega.ndim != 1: raise ValueError("omega must be 1-d array") if omega.shape[0] != Q.shape[1]: raise ValueError("Must have same number of eigenvalues and eigenvectors") if __debug__: Parameter.checkOrthogonal(Q, tol=EigenUpdater.tol, softCheck=True, arrayInfo="input Q in eigenAdd()") #Taking the abs of the eigenvalues is correct inds = numpy.flipud(numpy.argsort(numpy.abs(omega))) omega, Q = Util.indEig(omega, Q, inds[numpy.abs(omega)>EigenUpdater.tol]) Omega = numpy.diag(omega) YY = Y.conj().T.dot(Y) QQ = Q.dot(Q.conj().T) Ybar = Y - Y.dot(QQ) Pbar, sigmaBar, Qbar = numpy.linalg.svd(Ybar, full_matrices=False) inds = numpy.flipud(numpy.argsort(numpy.abs(sigmaBar))) inds = inds[numpy.abs(sigmaBar)>EigenUpdater.tol] Pbar, sigmaBar, Qbar = Util.indSvd(Pbar, sigmaBar, Qbar, inds) SigmaBar = numpy.diag(sigmaBar) Qbar = Ybar.T.dot(Pbar) Qbar = Qbar.dot(numpy.diag(numpy.diag(Qbar.T.dot(Qbar))**-0.5)) r = sigmaBar.shape[0] YQ = Y.dot(Q) Zeros = numpy.zeros((r, omega.shape[0])) D = numpy.c_[Q, Qbar] YYQQ = YY.dot(QQ) Z = D.conj().T.dot(YYQQ + YYQQ.conj().T).dot(D) F = numpy.c_[numpy.r_[Omega - YQ.conj().T.dot(YQ), Zeros], numpy.r_[Zeros.T, SigmaBar.conj().dot(SigmaBar)]] F = F + Z pi, H = scipy.linalg.eigh(F) inds = numpy.flipud(numpy.argsort(numpy.abs(pi))) H = H[:, inds[0:k]] pi = pi[inds[0:k]] V = D.dot(H) #logging.debug("</ eigenAdd >") return pi, V
def solve_eigenvalue(self, hamil): self.energies, self.coeffs = eigsh(hamil, k=1, which='SA')
임신 중 위험한 질병
임신 중 효모 감염. 임신 중 효모 감염에 더 취약한 이유와 이를 처리하는 방법을 알아보십시오. 임신 중 헤르페스. 헤르페스가 임신에 어떤 영향을 미칠 수 있는지와 아기를 보호하는 방법을 알아보십시오. 임신 중 독감. 독감은 임산부에게 특히 위험할 수 있습니다. 임신 중 독감이 있는지 확인하는 방법과 대처 방법을 알아보십시오.
그러나 임신 중에는 일부 허브와 허브 치료제를 섭취하는 것이 위험할 수 있습니다. 아래의 정보는 임신 중에 위험할 수 있는 허브와 비타민에 대해 다루고 있으며, 이 웹사이트의 다른 페이지인 '임신 중 허브와 비타민'은 건강한 비타민과 허브에 대해 다룹니다. 허브, 임신 및 안전.
풋볼 클럽 바르셀로나의 창단일은?
FC 바르셀로나 풋볼 클럽 바르셀로나 (카탈루냐어: Futbol Club Barcelona, 축구단 바르셀로나)는 스페인 카탈루냐 지방의 바르셀로나를 연고지로 하는 세계 최초이자 세계 최대 규모로 협동조합 형태로 운영되는 축구 클럽이다. 홈 경기장은 캄 노우이며, 1899년 11월 29일에 창단되었다.
아스널 FC 아스널 풋볼 클럽(영어: Arsenal Football Club→아스널 축구단)은 런던을 연고지로 홀로웨이의 에미레이츠 스타디움을 홈구장으로 하는 잉글랜드의 축구 클럽이다. 주장은 로랑 코시엘니이며, 잉글랜드의 1부 리그인 프리미어리그에 속해 있다. 아스널 FC(이하 아스널)는 현재 잉글랜드에서 가장 성공한 클럽들 중 하나이며, 13번의 리그 우승을 이뤘고, FA컵에서 13번의 우승으로 맨체스터 유나이티드를 제치고 잉글랜드 최다 우승 기록을 가지고있다. 그리고 당시 풋볼 리그 1919-20 시즌부터 시작하여 그 동안 한번도 2부 리그로 강등되지 않아 연속적으로 가장 오랫동안 1부 리그에 잔류하고 있는 기록을 세우고 있는 팀이기도 하다.
Adjusts the inputted weighting dictionary based on the occurrences of archetype tags in the inputted data set.
def pull_generic_tag(tag_name, data, weight, archetype_tags, archetype_weight_dict): for dataPiece, dataValue in data: tags = DataExtractor.get_names_from_connector(tag_name, "GenericTag", input_name=dataPiece) tagAmnt = Counter(tags) for match in set(tags).intersection(archetype_tags): # calculates the weighted value of the match, based on it's amount of occurrences, and adds this # to the archetype weighting dictionaries current value weightedWorth = (tagAmnt[match] * (weight + dataValue)) archetype_weight_dict.update({match: (archetype_weight_dict[match] + weightedWorth)}) return archetype_weight_dict
def clean_data(tags, grams): remove_words = [] for word in {word for word in tags if word != word.lower()}: word_lower = word.lower() if word_lower not in tags: tags[word_lower] = {} for tag in tags[word]: if tag not in tags[word_lower]: tags[word_lower][tag] = tags[word][tag] else: tags[word_lower][tag] += tags[word][tag] remove_words.append(word) # Remove words which were lowercased for word in remove_words: del tags[word] # Find rare words and move them to the rare-words tags[RARE_WORD] = {} remove_words = [] for word in tags: if sum(tags[word].values()) < 5: for tag in tags[word]: if tag not in tags[RARE_WORD]: tags[RARE_WORD][tag] = tags[word][tag] else: tags[RARE_WORD][tag] += tags[word][tag] remove_words.append(word) # Remove the less common words for word in remove_words: del tags[word] # Turn count(word with tag) into e(word|tag) for word in tags: for tag in tags[word]: word_tag_count = tags[word][tag] tag_count = grams[1][tag] tags[word][tag] = math.log(word_tag_count / tag_count) # Turn count(WUV) into q(V|WU) for tag_k2 in grams[3].keys(): for tag_k1 in grams[3][tag_k2].keys(): for tag_k in grams[3][tag_k2][tag_k1].keys(): grams[3][tag_k2][tag_k1][tag_k] = \ math.log(grams[3][tag_k2][tag_k1][tag_k] / grams[2][tag_k2][tag_k1]) return tags, grams
Drag an edge/corner of an N2WindowResizable and check that the size changed or didn't change as expected.
async def resize_window(self, options): self.log_test(options['desc'] if 'desc' in options else "Resizing '" + options['selector'] + "' window.") # await self.page.screenshot({'path': 'preresize.png'}) win_hndl = await self.get_handle(options['selector']) pre_resize_bbox = await win_hndl.boundingBox() edge_hndl = await self.get_handle(options['selector'] + ' div.rsz-' + options['side']) edge_bbox = await edge_hndl.boundingBox() new_x = edge_bbox['x'] + \ resize_dirs[options['side']][0] * options['distance'] new_y = edge_bbox['y'] + \ resize_dirs[options['side']][1] * options['distance'] await edge_hndl.hover() await self.page.mouse.down() await self.page.mouse.move(new_x, new_y) await self.page.mouse.up() post_resize_bbox = await win_hndl.boundingBox() dw = post_resize_bbox['width'] - pre_resize_bbox['width'] dh = post_resize_bbox['height'] - pre_resize_bbox['height'] resized = ((dw != 0) or (dh != 0)) if options['expectChange']: self.assertIsNot(resized, False, "The '" + options['selector'] + "' element was NOT resized and should have been.") else: self.assertIsNot(resized, True, "The '" + options['selector'] + "' element was resized and should NOT have been.") # await self.page.screenshot({'path': 'postresize.png'})
def __handleMouseDownDrag(self, event: Event, mode: int, limits: Rect, minSize: int, maxSize: int): if mode & dmDragMove: point = self.origin - event.mouse.where working = True while working: event.mouse.where += point self.__moveGrow(event.mouse.where, self.size, limits, minSize, maxSize, mode) working = self.mouseEvent(event, evMouseMove) # Pop the window to the mouse-up coords event.mouse.where += point self.__moveGrow(event.mouse.where, self.size, limits, minSize, maxSize, mode) else: point = self.size - event.mouse.where working = True while working: event.mouse.where += point self.__moveGrow(self.origin, event.mouse.where, limits, minSize, maxSize, mode) working = self.mouseEvent(event, evMouseMove) # Grow to the mouse-up event.mouse.where += point self.__moveGrow(self.origin, event.mouse.where, limits, minSize, maxSize, mode)
validates datetime into the set format and raises exception if from date is greater than to date
def validate_datetime(self): if self.from_date: self.from_date = purify_datetime(self.from_date) if self.to_date: self.to_date = purify_datetime(self.to_date) if self.from_date >= self.to_date: logger.error(f'{self.from_date} cannot be greater than {self.to_date}') raise ActionException('to_date, to_date must be bigger than from_date', status.HTTP_400_BAD_REQUEST)
def _parse_from_and_until(from_date_str, until_date_str): from_date = None from_granularity = None if from_date_str is not None: try: from_date, from_granularity = parse_date(from_date_str) except ValueError: raise exception.BadArgument(u'Illegal "from" datestamp') until_date = None until_granularity = None if until_date_str is not None: try: until_date, until_granularity = parse_date( until_date_str, datetime.time(23, 59, 59), ) except ValueError: raise exception.BadArgument(u'Illegal "until" datestamp') if (from_date is not None and until_date is not None): if (from_granularity != until_granularity): raise exception.BadArgument( u'Datestamps "from" and "until" have different granularity' ) if (from_date > until_date): raise exception.BadArgument( u'Datestamp "from" is greater than "until"' ) return from_date, until_date
cidrSelector is the CIDR range to allow/deny traffic to. If this is set, dnsName must be unset
def cidr_selector(self) -> Optional[str]: return self.__cidr_selector
def dns_sniffer(self): filter_str = "udp and port 53" victim = self.config['victim'].value if victim is not None: filter_str += " and src %s" % victim sniff(filter=filter_str, store=0, prn=self.spoof_dns, stopper=self.test_stop, stopperTimeout=3)
태아의 신장이 비대해지는 원인은 무엇인가?
태아의 신장 비대 원인. 일부 경우에는 신장 비대가 명백한 원인과 관련이 없을 수 있지만, 확인된 몇 가지 일반적인 원인이 있습니다. 방광요관역류: 이 상태는 요관과 방광의 접합부에 있는 밸브의 기능이 잘못 작동하는 것과 관련이 있습니다.
태아의 신장 비대 원인. 일부 경우에는 신장 비대가 명백한 원인과 관련이 없을 수 있지만, 확인된 몇 가지 일반적인 원인이 있습니다. 방광요관역류: 이 상태는 요관과 방광의 접합부에 있는 밸브의 기능이 잘못 작동하는 것과 관련이 있습니다.
Writes the ITM information info to the file, specified by self.fileName + "_ITMInformation" in the folder ../../evalData.
def writeITMInformation(self, info): with open("../../evalData/" + self.fileName + "_ITMInformation.txt", "a") as f: f.write(info)
def write_file(self): pass
List stored models. If limit is set to None there will be only first 50 records shown.
def list_models(self, limit=None): self._client._models.list(limit=limit)
def list_models(): return jsonify(model_repositories.list_models()), 200
Given an m x n matrix zero the rows and columns that have a 0 in it.
def zero_rows_columns(matrix): rows = [] columns = [] for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: rows.append(i) columns.append(j) for i in range(len(matrix)): for j in range(len(matrix[0])): if i in rows or j in columns: matrix[i][j] = 0 return matrix
def find_empty(bo): for i in range(len(bo)): for j in range(len(bo[i])): if bo[i][j] == 0: return (i, j) # row, col return None
Check that if we try to insert a duplicate district on (council_id, internal_council_id) an IntegrityError is thrown
def test_duplicate_districts(self): self.create_dummy_council() cmd = stub_duplicatedistrict.Command() exception_thrown = False try: cmd.handle(**self.opts) except IntegrityError: exception_thrown = True self.assertTrue(exception_thrown)
def validate_snp_id(SNP_ID): try: snp = SNP.objects.get(SNP_ID__exact=SNP_ID) raise ValidationError(u'This SNP is already in our database. Unfortunately, at this point, we only support associating a SNP with one trait.') except SNP.DoesNotExist: pass
checks if the passed board is at a ternminal node / the game is about to end
def is_terminal_node(board): return winning(board, PLAYER_PIECE) or winning(board, AI_PIECE) or len(get_valid_locations(board)) == 0
def is_goal_state(self): for idx in range(self.N*self.N): if self.orig_board[idx] == 9: continue if self.orig_board[idx] != self.curr_board[idx]: return False self.game_over = True self.game_lost = False return True
get all my custom slot types, you may use nameContains to get slot types, parameter as substring.
def get_all_my_slot_types(): #response=client.get_slot_types(nameContains='dummy') response=client.get_slot_types() # unhash to print the raw response # print response return response[u'slotTypes']
def implements(self) -> List[str]: mro: List[type] = type(self).mro() return [ cast(str, cast(Item, item_type).type) for item_type in mro[:mro.index(Item)] if getattr(item_type, "type", None) ]
Returns pointer to the previous transition. If this is the first transition, this method should return ``None``.
def prev_transition(self): return self._prev_transition
def previous_item(self): if self.previous_sibling: h = self.previous_sibling while h.children: h = h.children[-1] return h elif self.parent: return self.parent
배우와 제작진 모두 힘내라고 이날 찾아왔다.
배우와 제작진 모두가 힘내라고 이날 찾아왔다.
두 배우 모두 배우로서 표현해 내기에 가장 어렵게 느껴진 지점이, 어머니 감골댁의 주검을 발견하는 장면이라고 말했다.
Predicts if z comes from the same distribution as Z, with respect to a significance level e.
def predict_unlabelled(self, z, Z, e): pval = self.calculate_pvalue(z, Z) return (pval > e)
def sigmoid(Z): t1 = 1/(1+math.e**-Z) return t1
We intercept the response coming back from the main images Resource, caching image files to the cache
def process_response(self, resp): if not self.get_status_code(resp) == httplib.OK: return resp request = resp.request if request.method not in ('GET', 'DELETE'): return resp match = get_images_re.match(request.path) if match is None: return resp image_id = match.group(2) if '?' in image_id or image_id == 'detail': return resp if self.cache.is_cached(image_id): if request.method == 'DELETE': logger.info(_("Removing image %s from cache"), image_id) self.cache.delete_cached_image(image_id) return resp resp.app_iter = self.cache.get_caching_iter(image_id, resp.app_iter) return resp
def process_image_request(file_id, size): sizes = {'small': (140,100), 'medium': (400, 300), 'large': (1200, 1000) } col = app.data.driver.db['files'] image = col.find_one({'_id': ObjectId(file_id)}) grid_fs = GridFS(app.data.driver.db) if not grid_fs.exists(_id=image['file']): eve_abort(500, 'No file system found') im_stream = grid_fs.get_last_version(_id=image['file']) im = Image.open(im_stream) if size != 'original': im.thumbnail(sizes[size], Image.ANTIALIAS) img_io = io.BytesIO() im.save(img_io, 'PNG', quality=100) img_io.seek(0) encoded_img = base64.b64encode(img_io.read()) dict = {'mimetype': 'image/png', 'encoding': 'base64', 'src': encoded_img } # Jsonify the dictionary and return it return jsonify(**dict) # Sends an image #return send_file(img_io, mimetype='image/png')
Log in to the SFTP server using the username and password provided and download the specified files.
def download_files(self): stmt = self.att_table.select()\ .where(self.att_table.c.type == 'wiki') transport = paramiko.Transport(self.host) transport.connect(username=self.username, password=self.password) sftp = paramiko.SFTPClient.from_transport(transport) for a in self.engine.execute(stmt).fetchall(): if not a.size or \ a.size > 10000000 or \ a.id == 'PasswordDatabase': print u"SKIPPING %s" % att continue att = Att(a) print u"Downloading %s" % att destdir = att.outputpath() if not os.path.exists(destdir): os.makedirs(destdir) sftp.get(att.fullpath(), att.fulloutputpath())
def download_from_dropbox_and_upload_to_s3(self):#, dropbox_file_paths): dropbox_file_paths = self._filter_files() for file in dropbox_file_paths: _, f = self.dbx.files_download(file) print(f'uploading file {file}') self.s3_resource.Bucket(self.destination_bucket).put_object( Key=os.path.join(self.s3_path, os.path.basename(file)), Body=f.content )
평면 지구 이론은 어디에서 유래되었는가?
1893년 올랜도 퍼거슨이 그린 '평면 지구' 지도. 이 평면 지구의 표현은 오늘날에도 여전히 일부 사람들에게 받아들여진다. 출처: 위키미디어/올랜도 퍼거슨 대부분의 사람들에게 평면 지구론자로 묘사되는 것은 모욕으로 여겨진다. 지구가 평면이라는 생각은 잘못된 것으로 간주될 뿐만 아니라, 잘못됨의 모델로, 무언가에 대해 잘못된 것으로 여겨지는 금본위기준으로 여겨진다.
그들에게 반박 주장을 제시하고 싶은 유혹을 피하면서, 현재의 평면 지구 이론은 무엇이며, 그것은 어디에서 유래했는가?
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
3

Models trained or fine-tuned on CocoRoF/massive_triplet_v3