query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Calculates a client's schedule for a given task.
def schedule_for(current_track, task, client_index): op = task.operation num_clients = task.clients sched = scheduler.scheduler_for(task.schedule, task.params) logger.info("Choosing [%s] for [%s]." % (sched, task)) runner_for_op = runner.runner_for(op.type) params_for_op = track.operation_parame...
[ "def schedule_task(self, task, date):\n return self.connection.schedule_task(task, date)", "def _schedule(self,task_dict):\n times = [time(), None, None, None] # (schedule timestamp, execution timestamp, stop timestamp, get timestamp)\n result_id = self._extract_features.remote(self, times) #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the necessary schedule based on a given number of iterations.
def iteration_count_based(sched, warmup_iterations, iterations, runner, params): next_scheduled = 0 total_iterations = warmup_iterations + iterations if total_iterations == 0: raise exceptions.RallyAssertionError("Operation must run at least for one iteration.") for it in range(0, total_iteratio...
[ "def generate_n_schedule(n=2, m=8, wkday_slot=5, wkend_slot=6, numtrials=1000, prev_opt_cost = np.zeros(m)):\r\n\t# initialize\r\n\tm_cost = np.zeros(m)\r\n\tm_schd = np.zeros(wkday_slot + wkend_slot)\r\n\tn_opt_schd = []\r\n\tfor i in range(n):\r\n\t\tnp.random.seed(i)\r\n\t\topt_schd, m_cost = optimize_schd(m, wk...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a bool indicating whether the passed version matches the minimum required version for the given feature.
def _matches_feature(feature: ContractFeature, version: Optional[str]) -> bool: if version is None: # contracts_version == None means the stock version in development. return True return CONTRACT_FEATURE_VERSIONS[feature].match(Version(version))
[ "def firmware_version_at_least(fw_version, major, minor):\n if fw_version['major'] > major:\n return True\n if fw_version['major'] == major and fw_version['minor'] >= minor:\n return True\n return False", "def supported_version(version, minimum, maximum):\n if minimum and StrictVersion(v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test no heartbeat received.
async def test_no_hb(self): await self.async_setup() pyinsteon.managers.heartbeat_manager.HB_CHECK_BUFFER = 1 self._hb_mgr = pyinsteon.managers.heartbeat_manager.HeartbeatManager( self._address, self._group, 0 ) await asyncio.sleep(1.1) assert self._heartbeat
[ "def test_heartbeatDisabled(self):\n self.assertIdentical(self.client._heartbeat, None)\n self.client.heartbeatInterval = None\n self.client.irc_RPL_WELCOME(\"foo\", [])\n self.assertIdentical(self.client._heartbeat, None)", "def test_heartbeat(self):\n pass", "def broker_null...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the speed of the left and right motors to the given speed. The speed should be in the range of [0, 255]. Sleeps for 0.1 seconds in between setting the left and right motor speeds.
def set_speed(speed): if speed >255: speed =255 elif speed <0: speed =0 set_left_speed(speed) #time.sleep(.1) set_right_speed(speed)
[ "def set_motor_speeds(left, right):\n MOTORS[0].setVelocity(bind_max_speed(left))\n MOTORS[1].setVelocity(bind_max_speed(right))", "def set_left_speed(speed):\n if speed >255:\n speed =255\n elif speed <0:\n speed =0\n return write_i2c_block(ADDRESS,set_left_speed_cmd+[speed,0,0])", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the speed of the left motor. The speed should be in the range of [0, 255]. Returns 1 if the motor speed change fails.
def set_left_speed(speed): if speed >255: speed =255 elif speed <0: speed =0 return write_i2c_block(ADDRESS,set_left_speed_cmd+[speed,0,0])
[ "def _left_speed(self, speed):\n assert 0 <= speed <= 255, 'Speed must be a value between 0 to 255 inclusive!'\n speed += self._left_trim\n speed = max(0, min(255, speed)) # Constrain speed to 0-255 after trimming.\n self._left.setSpeed(speed)", "def set_speed(speed):\n if speed >2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the speed of the right motor. The speed should be in the range of [0, 255]. Returns 1 if the motor speed change fails.
def set_right_speed(speed): if speed >255: speed =255 elif speed <0: speed =0 return write_i2c_block(ADDRESS,set_right_speed_cmd+[speed,0,0])
[ "def set_speed(speed):\n if speed >255:\n speed =255\n elif speed <0:\n speed =0\n set_left_speed(speed)\n #time.sleep(.1)\n set_right_speed(speed)", "def setMotorSpeed(self, idMotor=0, sense=0, speed=0, board=0):\n msg = [idMotor, sense, int(speed / 256.0), speed % 256]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the speed of the left motor. The speed should be in the range of [0, 255]. Returns 1 if the motor speed change fails.
def set_left_speed(speed): if speed >255: speed =255 elif speed <0: speed =0 return write_i2c_block(ADDRESS,set_left_speed_cmd+[speed,0,0])
[ "def _left_speed(self, speed):\n assert 0 <= speed <= 255, 'Speed must be a value between 0 to 255 inclusive!'\n speed += self._left_trim\n speed = max(0, min(255, speed)) # Constrain speed to 0-255 after trimming.\n self._left.setSpeed(speed)", "def set_speed(speed):\n if speed >2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the speed of the right motor. The speed should be in the range of [0, 255]. Returns 1 if the motor speed change fails.
def set_right_speed(speed): if speed >255: speed =255 elif speed <0: speed =0 return write_i2c_block(ADDRESS,set_right_speed_cmd+[speed,0,0])
[ "def set_speed(speed):\n if speed >255:\n speed =255\n elif speed <0:\n speed =0\n set_left_speed(speed)\n #time.sleep(.1)\n set_right_speed(speed)", "def setMotorSpeed(self, idMotor=0, sense=0, speed=0, board=0):\n msg = [idMotor, sense, int(speed / 256.0), speed % 256]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that we're consistently running at 60 ticks/s.
def test_tick_rate(self): history = self.history fps = 60 # I know it's not frames but I find it easier to read than tps. def get_time(history_item): return history_item.game_tick_proto.GameInfo().SecondsElapsed() def is_admissible(history_item): return history...
[ "def test_oneMinute(self):\n self.assertEqual(common.Token.validity.total_seconds(), 60)", "def valid_clocks(self) -> int:\n pass", "def check_timers(self):", "def _is_exact_match(cron, ts):\r\n cron.get_prev()\r\n diff = timeutils.total_seconds(ts - cron.get_next(datetime.datetime...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds data to url. Data should be a list or tuple consisting of 2item
def addGETdata(url, data): return url + '?' + urllib.urlencode(data)
[ "def add_data(self, data):\n self.data = self.data + data", "def addData(self, *items):", "def data(self, data: str):\n index = 0 if self.flush_next is None else 1\n self.data_frames[-1][index].append(data)", "def insert(self, data, language = 'N3') :\n\t\tif language == 'N3' :\n\t\t\tif ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a name like exam_20150128.pdf and returns 20150128.pdf which is the format that Xmr uses.
def normalizeFilenameToCommonDateFormat(filename): rgx_date = re.search(r'(\d+)-(\d+)-(\d+)', filename) if (rgx_date == None): raise ValueError("Not interested in this file!") year = rgx_date.group(1) month = rgx_date.group(2) day = rgx_date.group(3) return "%s%s%s.pdf" % (year, m...
[ "def page_name_to_file_name(page_name):\n if page_name.endswith('.md') or page_name.endswith('.markdown'):\n return page_name\n return page_name + '.md'", "def get_output_pdfname(pdf_name):\n\n # Since we use the pdf name as output filename (e.g. \"foo.pdf\") there\n # could be conflicts if two...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads events data yaml file
def load_events(fich): with fich.open() as fd_conf: yaml_text = fd_conf.read() conf = yaml.safe_load(yaml_text) return yaml_text, conf
[ "def test_load_events(self):\n command = '{0}'.format(\n os.path.join(self.datadir, 'monol_testA.evt'))\n hen.read_events.main(command.split())\n new_filename = self.first_event_file\n ev = hen.io.load_events(new_filename)\n assert hasattr(ev, 'header')\n assert ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a file in `path` with content `text`
def save_file(path, text): with path.open(mode='w') as f_stream: f_stream.write(text)
[ "def save_text_file(text, path):\n os.makedirs(os.path.dirname(path), exist_ok=True)\n with open(path, \"w\") as f:\n f.write(text)", "def write(path, text):\n file = open(path, 'w')\n file.write(text)\n file.close()", "def txtWrite(text, path, mode=\"w\"):\n dirMake(os.path.dirname(pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the actual version of youtubedl
def youtube_dl_version(): import pkg_resources return pkg_resources.get_distribution("youtube-dl").version
[ "def get_version():\n return magpy.get_version()", "def get_version(self):\n return \"built-in\"", "def get_version():\n\n with open('yubico/yubico_version.py', 'r') as f:\n match = VERSION_PATTERN.search(f.read())\n return match.group(1)", "def get_version(self):\n return ar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create new directories and conference file in pyvideo repository to add a new event
def create_dirs(self): for new_directory in [self.event_dir, self.event_dir / 'videos']: new_directory.mkdir(exist_ok=self.overwrite) logger.debug('Dir {} created', new_directory)
[ "def create_event(event_info):\n try:\n new_event = event.Event(*event_info)\n new_event.add_file()\n\n return 1\n except:\n return 0", "def processCreation(self,event):\n\n \t\tprint \"\\n event type : \",event.event_type\n \t\tprint \"\\n even src path : \", event.src_path\n \t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create category.json for the conference
def create_category(self): # , conf_dir, title): category_file_path = self.event_dir / 'category.json' category_data = { 'title': self.title, } category_data_text = json.dumps(category_data, ** JSON_FORMAT_KWARGS) + '\n' save_f...
[ "def new_sub_category() -> jsonify:\n\tnew_sub_category = IncidentSubCategory()\n\tdb.session.add(new_sub_category)\n\tdb.session.commit()\n\treturn jsonify({\"sub_category_id\":new_sub_category.id})", "def test_category_creation(self):\n response = self.client.post(\n '/v2/categories',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download youtube metadata corresponding to this event youtube lists
def download_video_data(self): def scrape_url(url): """Scrape the video list, youtube_dl does all the heavy lifting""" ydl_opts = { "ignoreerrors": True, # Skip private and unavaliable videos } ydl = youtube_dl.YoutubeDL(ydl_opts) w...
[ "def from_youtube(cls, video_data, event):\n self = cls(event)\n\n metadata = self.metadata\n\n metadata['title'] = self.__calculate_title(video_data)\n self.filename = self.__calculate_slug()\n metadata['speakers'] = ['TODO'] # Needs human intervention later\n # youtube_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load video data form existing event video files
def load_video_data(self): self.file_videos = [ Video.from_file(path, self) for path in self.video_dir.glob('*.json') ]
[ "def save_video_data(self):\n if self.overwrite:\n # Erase old event videos\n for path in self.video_dir.glob('*.json'):\n path.unlink()\n for video in self.videos:\n video.save()", "def __loadVideo(self):\n # Check if movie file exists ...\n #\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge old video data when configured so
def merge_video_data(self): if self.overwrite: if self.wipe: self.videos = self.youtube_videos elif self.add_new_files or self.overwrite_fields: old_videos = { video.filename: video for video in self.file_videos ...
[ "def save_video_data(self):\n if self.overwrite:\n # Erase old event videos\n for path in self.video_dir.glob('*.json'):\n path.unlink()\n for video in self.videos:\n video.save()", "def merge(self, new_video, fields):\n merged_video = Video(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save all event videos in PyVideo format
def save_video_data(self): if self.overwrite: # Erase old event videos for path in self.video_dir.glob('*.json'): path.unlink() for video in self.videos: video.save()
[ "def save_video(self):\n # Release the video capture and \n # video write objects \n self.video.release()\n if self.record_video:\n self.video_result.release()\n print(\"The video was successfully saved\")", "def saveVideo(video, outputName,fps = 30):\n pathout = o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new commit in pyvideo repository with the new event data
def create_commit(self, event_data_yaml): os.chdir(str(self.repository_path)) sh.git.checkout(self.branch) sh.git.add(self.event_dir) message_body = ( '\n\nEvent config:\n~~~yaml\n{}\n~~~\n'.format(event_data_yaml) + '\nScraped with [pyvideo_scrape]' +...
[ "def commit(self, commit):\n\t\treq = cp.Protocol.res_commit(commit[\"version\"], commit[\"sequence\"])\n\t\tself.socket.sendall(req)", "def add_commit(repo, cfg, model, developer_gen, date):\n model, kwargs = model_note_change(model, developer_gen, date)\n msg = message_of(\n cfg, model.ticket if mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate title from youtube fields
def __calculate_title(video_data): title = 'Unknown' if 'fulltitle' in video_data.keys(): title = video_data['fulltitle'] elif 'title' in video_data.keys(): title = video_data['title'] elif '_filename' in video_data.keys(): title = video_data['_filenam...
[ "def get_video_title(self, response):\n return response.css(\".watch-title::text\").extract_first(default='')", "def get_title(self):\n self._clean_title()\n return self.vidName", "def video_title(self):\n # type: () -> string_types\n return self._video_title", "def get_vide...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate slug from title
def __calculate_slug(self): return slugify.slugify(self.metadata['title'])
[ "def slugify(self, document):\n first_id, *_ = document.json[\"id\"].split(\"-\")\n document.json[\"slug\"] = (\n slugify(document.json[\"title\"], max_length=60, word_boundary=True) + \"-\" + first_id\n )\n return document", "def slugify_title(title, datetimeon):\n year,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate record date from youtube field and event dates
def __calculate_date_recorded(self, upload_date_str): upload_date = datetime.date( int(upload_date_str[0:4]), int(upload_date_str[4:6]), int(upload_date_str[6:8])) if self.event.know_date: if not (self.event.date_begin <= upload_date <= self.event...
[ "def apply_date(self, wd):\r\n t_range_count = len(self.time_range)\r\n count = 1\r\n c_mod_date = str(self.m_time)[:10].replace(\"-\", \".\")\r\n\r\n # No dates were found. Return source mod date\r\n if len(self.time_range) == 0 and not self.is_carved_gzip and self.use_file_mod_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Contructor. Retrieves video metadata with youtubedl
def from_youtube(cls, video_data, event): self = cls(event) metadata = self.metadata metadata['title'] = self.__calculate_title(video_data) self.filename = self.__calculate_slug() metadata['speakers'] = ['TODO'] # Needs human intervention later # youtube_id = video_dat...
[ "def get_video_info(self) -> VideoInfo:\n\n with self.get_downloader({'skip_download': True, 'noplaylist': True, }) as downloader:\n info = downloader.extract_info(self.url)\n video_info = VideoInfo()\n video_info.title = info['title']\n video_info.author = info['uploader']\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create video copy overwriting fields
def merge(self, new_video, fields): merged_video = Video(self.event) merged_video.filename = self.filename for field in self.metadata: if field in set(fields): merged_video.metadata[field] = new_video.metadata.get(field) else: merged_video....
[ "def get_video(self):\n video_name = self.media_file.split(\"\\\\\")[-1]\n folder = os.path.dirname(os.path.abspath(__file__))\n copyfile(self.media_file, \"\\\\\".join([folder, video_name]))\n self.media_file = video_name", "def __create_blank_video(self):\n video_meta_data = g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
状态转移方程 dp[i,j] = min(dp[i1][j],dp[i][j1]) + grid[i][j]
def minPathSum(self, grid): n = len(grid) m = len(grid[0]) # 初始化状态转移表 dp = [] for i in range(n): dp.append([]) for j in range(m): dp[i].append(0) # 初始化状态转移表dp第一行 sum = 0 for j in range(m): sum += grid[0][...
[ "def minPathSum1(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n if m <= 0 or n <= 0: return 0\n\n # 初始化\n dp = [[0 for _ in range(n)] for _ in range(m)]\n dp[0][0] = grid[0][0]\n for i in range(1, m): dp[i][0] = dp[i-1][0] + grid[i][0]\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
res 파일들의 meta data Example >>> build_meta_res() {
def build_meta_res(): meta = {} fnames = filter( lambda x: not re.match(r'.*\_\d+\.res$', x), os.listdir(os.path.join(XINGAPI_PATH, 'res')) ) def parse_field(line): cols = line.split(',') return { 'name': cols[1].strip(), 'desc': cols[0]....
[ "def extract_meta_data(video_file_name, output_file=meta.txt, *args, **kwargs):", "def _init_meta(self):\n self._strMETACLASS = str(self.__class__).split('.')[1][:-2]\n self._strMETAVERSION = \"0.1\"\n \"\"\"\n | Filename \"_Class_Version_\"\n \"\"\"\n self._strMETAFILE = \"_\" + self._strMETACL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
KOSPI, KOSDAQ 주식종목 xingAPI의 t8430(주식종목조회) 요청을 통해 주식 종목 정보를 불러온다. Example >>> build_meta_stock() {
def build_meta_stock(): stock = query('t8430', {'gubun':'0'}).get('t8430OutBlock', []) return dict(zip( map(lambda s: s['shcode'], stock), stock ))
[ "def getStockData():\n pass", "def init_stock():\n return {\"five\":0, \"one\": 0, \"quarter\": 25, \"dime\": 25, \"nickel\":25}", "def serialize_basic_stock_details(self):\n return {\n 'country': self.country,\n 'currency': self.currency,\n 'exchange': self.exc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query 요청 res[str]`t1102` 사용할 res 파일명 send[dict] 전송할 데이터 {
def query(res, send, cont=False, timeout=10): # res 파일 로드 _query = DispatchWithEvents('XA_DataSet.XAQuery', _QueryHandler) _query.init(res) if not cont: # 전송 현황 업데이트 if not res in _query_status: _query_status[res] = [] while _query_status[res] and _query...
[ "def query_file(self):\n self.print(\"Start sending Query requests of te and te_eb after TE upload\")\n request = copy.deepcopy(self.request_template)\n request['request'][0]['sha1'] = self.sha1\n data = json.dumps(request)\n response_j = json.loads('{}')\n status_label = F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates schedules for a rabi experiment using a Gaussian pulse
def rabi_schedules(amp_list, qubits, pulse_width, pulse_sigma=None, width_sigma_ratio=4, drives=None, cmd_def=None, inst_map=None, meas_map=None): xdata = amp_list # copy the instruction to schedule mapping inst_map = copy.deepcopy(inst_map) if not inst_map: ...
[ "def pulseGenerator(ham: QHamiltonian) -> SchedulerPulseGenerator:\n generator = SchedulerPulseGenerator(ham)\n\n def generateVZ(ham: QHamiltonian, cirLine: CircuitLine) -> QJob:\n \"\"\"\n Generate the virtual-z gate\n \"\"\"\n job = ham.createJob()\n\n onQubit = int(cirLin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates schedules for a drag experiment doing a pulse then the pulse
def drag_schedules(beta_list, qubits, pulse_amp, pulse_width, pulse_sigma=None, width_sigma_ratio=4, drives=None, cmd_def=None, inst_map=None, meas_map=None): xdata = beta_list # copy the instruction to schedule mapping inst_map = copy.deepcopy(inst...
[ "def greedy_dynamic_schedule(problem):", "def greedy_claim_schedule(problem):", "def _create_schedules(self):\n\n ''''''", "def get_pulse_schedule(backend: IBMQBackend) -> Schedule:\n config = backend.configuration()\n defaults = backend.defaults()\n inst_map = defaults.instruction_schedule_ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate beam radius using numerical method.
def beam_radius(self, x, Amp, beam_type='vortex', Amp_Flag=True): # dx = x[[0],[1]]-x[[0],[0]] # # Intensity = (Amp*Amp.conjugate()).real # N,N = Amp.shape # # if beam_type == 'vortex': # # # m,n = matrix_Lib.getPositon(In...
[ "def beamradius(params,z):\n \n w0=params[0] # beam width at waist [e.g. meters]\n zw=params[1] # waist position [e.g. meters]\n lam = params[2] # wavelength [meters]\n \n zR=np.pi*w0**2/lam # Raleigh length [e.g. m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the channel capacity in discrete memoryless channels using OAM communication.
def Channel_capacity(self,L,Pm0_m): N = 2*L+1 C = np.log2(N) A = 0 B = 0 for m in range(-L,L): for m0 in range(-L,L): A += Pm0_m[m,m0]*np.log2(Pm0_m[m,m0]) for m1 in range(-L,...
[ "def channel_capacity(self, x): # pragma: no cover\n cc = channel_capacity(x.reshape((self._crv_size, self._bound)).copy())[0]\n return cc", "def capacity(self):\n return self.buffer_capacity.mean(dim=1)", "def Capacity(self) -> int:", "def get_capacity():\n fs.get_capacity()", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the topological charge probability distribution in received light field while the topological charge of initial light field varies in (m0_Max,m0_Max).
def Pm0_m(self,m0_Max=3,m_Max=5,N=512,Distance=1000*LP.m,Cn2=1e-14): Pm0_m = np.zeros((2*m0_Max+1,2*m_Max+1),dtype='float') # pretreatment of the probability distribution matrix; # In[]: propagate in turbulece and calculate the spiral spectrum coefficients. for m0 in ...
[ "def Channel_capacity(self,L,Pm0_m):\r\n \r\n N = 2*L+1\r\n C = np.log2(N)\r\n \r\n A = 0\r\n B = 0\r\n \r\n for m in range(-L,L):\r\n for m0 in range(-L,L):\r\n \r\n A += Pm0_m[m,m0]*np.log2(Pm0_m[m,m0]) \r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the PIB using numerical methods. PIB, power in the bucket, defined as the ratio of the far field laser power in given size 'bucket' and the total power(percentage), it can be used to describe the laser power concentration, and reflect the focusing ability in far field of practical laser.
def Power_in_the_Bucket(self,PIB_Func,a,b): Temp1 = integrate.dblquad(PIB_Func,0,2*np.pi,lambda x:0,lambda x:b)[0] Temp2 = integrate.dblquad(PIB_Func,0,2*np.pi,lambda x:0,lambda x:a)[0] PIB = Temp1/Temp2 return PIB
[ "def calc_percentages(self):\n self.beyond_lower.calc_percentage(self.total_entries)\n for b in self.buckets:\n b.calc_percentage(self.total_entries)\n self.beyond_upper.calc_percentage(self.total_entries)", "def bucket_ball_params(self):\n golden_bucket_probability = get_golden_bucket_probab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator for handling legend of mpl.Patch
def _patch_legend(obj, draw_options, legend_type): legend = "" if _is_in_legend(obj): # Unfortunately, patch legend entries need \addlegendimage in Pgfplots. do = ", ".join([legend_type] + draw_options) if draw_options else "" legend += "\\addlegendimage{{{}}}\n\\addlegendentry{{{}}}\n\n...
[ "def legend (self, **kwargs):\n axes = self.twin_axes or self.axes\n self.mpl_legend = axes.legend (self.mpl_lines, self.labels, **kwargs)", "def add_legend_data(self, ax, color, label, hatch=None):\n rect = plt.Rectangle([0, 0], 0, 0,\n linewidth=self.linewidth / ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``` Get current weight decay rate ```
def get_weight_decay(self): if type(self.model.optimizer).__name__ == "AdamWeightDecay": return self.model.optimizer.weight_decay_rate else: return None
[ "def weight_decay(self):\n if self._weight_decay is not None:\n return self._weight_decay\n return 5e-5 if 'VG' in self.dataset else 5e-4", "def decay(self):\n return self._decay", "def __getAndUpdateLearningRate(self):\n rate = self.gamma_0 / (1 + (self.gamma_0 / self.d) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``` alias for self.validate(). Returns confusion matrix and optionally prints a classification report. This is currently only supported for binary and multiclass classification, not multilabel classification. By default, this uses val_data, as supplied to ktrain.get_learner(). Other validation or test data can be optio...
def evaluate( self, test_data=None, print_report=True, save_path="ktrain_classification_report.csv", class_names=[], ): return self.validate( val_data=test_data, print_report=print_report, save_path=save_path, class_name...
[ "def evaluate_classifications(self):\n test_labels = open('./digitdata/testlabels', 'r')\n self.init_confusion_matrix()\n i = 0\n class_stats = {0:[0,0], 1:[0,0], 2:[0,0], 3:[0,0], 4:[0,0], 5:[0,0], 6:[0,0], 7:[0,0], 8:[0,0], 9:[0,0]}\n total_correct = 0\n num_labels = 1000...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``` Computes losses on validation set sorted by examples with top losses
def top_losses(self, n=4, val_data=None, preproc=None): # check validation data and arguments if val_data is not None: val = val_data else: val = self.val_data if val is None: raise Exception("val_data must be supplied to get_learner or top_losses") ...
[ "def best_tests():\n return [\n LvqParams(sigma=.2, prototypes_per_class=8, batch_size=256, epochs=4),\n LvqParams(sigma=6, prototypes_per_class=12, batch_size=128, epochs=4),\n LvqParams(sigma=6, prototypes_per_class=12, batch_size=16, epochs=12),\n LvqParams(sigma=1, prototypes_per_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``` View observations with top losses in validation set. Musta be overridden by Learner subclasses. ```
def view_top_losses(self, n=4, preproc=None, val_data=None): raise NotImplementedError( "view_top_losses must be overriden by Learner subclass" )
[ "def view_top_losses(self, n=4, preproc=None, val_data=None):\n val = self._check_val(val_data)\n\n # get top losses and associated data\n tups = self.top_losses(n=n, val_data=val, preproc=preproc)\n\n # get multilabel status and class names\n classes = preproc.get_classes() if pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``` checks whether optimizer attached to model is an "Adamlike" optimizer with beta_1 parameter. ```
def _is_adamlike(self): return self.model is not None and hasattr(self.model.optimizer, "beta_1")
[ "def check_optimizer(self, optimizer):\r\n if optimizer in optimizer_implemented:\r\n return optimizer\r\n else:\r\n raise InvalidNeuralNetwork()", "def optimizer(self):\n return torch.optim.Adam(self._model.parameters())", "def optimize_model(network, alpha, beta1, be...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``` If freeze_range is None, makes all layers trainable=False except last Dense layer. If freeze_range is given, freezes the first layers and unfrezes all remaining layers.
def freeze(self, freeze_range=None): if freeze_range is None: # freeze everything except last Dense layer # first find last dense layer dense_id = None for i, layer in reversed(list(enumerate(self.model.layers))): if isinstance(layer, keras.layers...
[ "def unfreeze(self, exclude_range=None):\n # make all layers trainable\n for i, layer in enumerate(self.model.layers):\n layer.trainable = True\n if exclude_range:\n for i, layer in enumerate(self.model.layers[:exclude_range]):\n layer.trainable = False\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``` Make every layer trainable except those in exclude_range. unfreeze is simply a proxy method to freeze.
def unfreeze(self, exclude_range=None): # make all layers trainable for i, layer in enumerate(self.model.layers): layer.trainable = True if exclude_range: for i, layer in enumerate(self.model.layers[:exclude_range]): layer.trainable = False self._r...
[ "def unfreeze(self,layers):\n inception_layers = 311\n slice = inception_layers-layers\n\n for layer in self.model.layers[:slice]:\n layer.trainable = False\n for layer in self.model.layers[slice:]:\n layer.trainable = True\n\n self.model.compile(optimizer=SGD(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``` Train model using a version of Leslie Smith's 1cycle policy. This method can be used with any optimizer. Thus, cyclical momentum is not currently implemented.
def fit_onecycle( self, lr, epochs, checkpoint_folder=None, cycle_momentum=True, max_momentum=0.95, min_momentum=0.85, class_weight=None, callbacks=[], steps_per_epoch=None, verbose=1, ): if not self._is_adamlike() and c...
[ "def __init__(self, learning_rate, momentum,\n use_locking=False, name=\"Momentum\", use_nesterov=False):\n super(MomentumOptimizer, self).__init__(\n learning_rate=learning_rate,\n momentum=momentum,\n name=name,\n nesterov=use_nesterov)", "def __init__(self,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``` Trains the model. By default, fit is simply a wrapper for model.fit. When cycle_len parameter is supplied, an SGDR learning rate schedule is used. Trains the model.
def fit( self, lr, n_cycles, cycle_len=None, cycle_mult=1, lr_decay=1, checkpoint_folder=None, early_stopping=None, verbose=1, class_weight=None, callbacks=[], steps_per_epoch=None, ): # check early_stopping ...
[ "def fit(\n self,\n lr,\n n_cycles,\n cycle_len=None,\n cycle_mult=1,\n lr_decay=1.0,\n checkpoint_folder=None,\n early_stopping=None,\n class_weight=None,\n callbacks=[],\n steps_per_epoch=None,\n verbose=1,\n ):\n # chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``` Trains the model. By default, fit is simply a wrapper for model.fit (for generators/sequences). When cycle_len parameter is supplied, an SGDR learning rate schedule is used.
def fit( self, lr, n_cycles, cycle_len=None, cycle_mult=1, lr_decay=1.0, checkpoint_folder=None, early_stopping=None, class_weight=None, callbacks=[], steps_per_epoch=None, verbose=1, ): # check early_stopping ...
[ "def fit(\n self,\n lr,\n n_cycles,\n cycle_len=None,\n cycle_mult=1,\n lr_decay=1,\n checkpoint_folder=None,\n early_stopping=None,\n verbose=1,\n class_weight=None,\n callbacks=[],\n steps_per_epoch=None,\n ):\n\n # chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An image with GPS EXIF data should have it stripped out with a new object. Testing the image when added to a brand new publication.
def test_exif_data_removed_from_added_thumbnail(self): # The image that has GPS data: path = "tests/core/fixtures/images/tester_exif_gps.jpg" # Double-check the original image does have some GPS data: exif_dict = piexif.load(path) self.assertEqual(len(exif_dict["GPS"].keys()), ...
[ "def test_exif_data_removed_from_updated_thumbnail(self):\n\n # The image that has GPS data:\n path = \"tests/core/fixtures/images/tester_exif_gps.jpg\"\n\n # Double-check it does have some GPS data:\n exif_dict = piexif.load(path)\n self.assertEqual(len(exif_dict[\"GPS\"].keys())...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A replacement thumbnail should have its GPS data removed. i.e. an image that's added to an existing publication, not a brand new one.
def test_exif_data_removed_from_updated_thumbnail(self): # The image that has GPS data: path = "tests/core/fixtures/images/tester_exif_gps.jpg" # Double-check it does have some GPS data: exif_dict = piexif.load(path) self.assertEqual(len(exif_dict["GPS"].keys()), 15) #...
[ "def test_exif_data_removed_from_added_thumbnail(self):\n\n # The image that has GPS data:\n path = \"tests/core/fixtures/images/tester_exif_gps.jpg\"\n\n # Double-check the original image does have some GPS data:\n exif_dict = piexif.load(path)\n self.assertEqual(len(exif_dict[\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes the fully qualified path of a file as the input. Checks the current working directory. If that directory is within the fully qualified path, returns the local path from working directory to file. If no, returns fully qualified path.
def get_file_path(qualified_path): # Hacky little workaround for different environments running unit test from different, unpredicatble, directories # (PyCharm behavior is particularly odd.) pwd = os.getcwd() pwdl = pwd.split('/') qpl = qualified_path.split('/') stat = False out = [] #...
[ "def get_file_path():\n return os.path.dirname(os.path.abspath(os.path.realpath(__file__)))", "def file_path(file_name, path):\n return path.rstrip('\\/') + \"/{0}\".format(file_name) if path else os.getcwd() + \"/{0}\".format(file_name)", "def relative_path(f):\n return os.path.join(os.path.dirname(__...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Let center be (0.5 train_width, 0.5 train_height) Given the polygon vertices of some canvas, compute how much it needs to be enlarged from the center so we can crop out a centered rectangle of (train_width, train_height)
def compute_canvas_scaling( self, canvas_corners: np.array ) -> float: canvas_box = Polygon(zip(canvas_corners[:, 0], -canvas_corners[:, 1])) train_corners = np.array([ (0, 0), (self.train_width, 0), (self.train_width, self.train_height), (0, self.train_height)])...
[ "def rectangle_vertice(self, center, height, width):\n half_height = height / 2.\n half_width = width / 2.\n\n bias1 = np.ones(4) * half_width\n bias2 = np.ones(4) * half_height\n\n corner1 = np.empty([1, 3], dtype=np.float32)\n corner2 = np.empty([1, 3], dtype=np.float32)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a sequence example from a single image and ordering pair and conserves disk space by not duplicating features
def create_sequence_example(inner_image_path, inner_sample): # serialize a pointer to the disk location of the image features # copying data for every training example would consume too much storage image_path_feature = tf.train.Feature( bytes_list=tf.train.BytesList( ...
[ "def prepare_example(image_path, annotations, label_map_dict):\n print(\"encoding %s\" % image_path)\n with tf.gfile.GFile(image_path, 'rb') as fid:\n encoded_png = fid.read()\n encoded_png_io = io.BytesIO(encoded_png)\n image = pil.open(encoded_png_io)\n\n if image.format != 'PNG':\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the details for the plugin.
def get_details(self): return PluginDetails( plugin_name="bad-string-detail-is-int", plugin_id="MDE007", plugin_enabled_by_default=True, plugin_description=123, plugin_version="0.0.0", plugin_interface_version=1, )
[ "def get_details(self):\n return PluginDetailsV2(\n plugin_name=\"bad-xxx\",\n plugin_id=\"MDE003\",\n plugin_enabled_by_default=True,\n plugin_description=\"Plugin that.\",\n plugin_version=\"0.0.0\",\n plugin_supports_fix=True,\n )", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a Plotly bar plot. Bar plots work with categorical data. Function computes appropriate counts and percentages to create bar plots.
def barplot(self, x = "Predictor", color = None, opacity = 1, template = "ggplot2", has_title = True, barmode="stack", is_horizontal = False, title = None, is_percent = False, show_num = False): if color: #Produce either a stacked or grouped bar plot df_stack = self....
[ "def category_bar_chart(df):\n label_names = df.drop(['message', 'original', 'genre', 'id'], axis=1).columns\n label_counts = []\n for column in label_names:\n label_counts.append(df[column].sum())\n return {\n 'data': [\n Bar(\n x=label_names,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert input to int or None.
def to_int_or_none(value: Union[None, int, str]) -> Optional[int]: return None if value is None else int(value)
[ "def _int(input):\n if input == \"\":\n return None\n return int(input)", "def to_positive_int_or_none(self, value: Any) -> Optional[int]:\n if not value:\n return None\n try:\n int_value = int(value)\n return int_value if int_value > 0 else None\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make converter that returns value or ``None``. ``converter`` is called to further convert non``None`` values.
def value_or_none(converter: Callable[[Any], T]) -> Callable[[Any], Optional[T]]: return lambda value: None if value is None else converter(value)
[ "def truthy_or_none(converter: Callable[[Any], T]) -> Callable[[Any], Optional[T]]:\n return lambda value: converter(value) if value else None", "def none_or(value: Optional[TTT],\n convert: Callable[[TTT], TTT2],\n value_for_none: Optional[\n Callable[[], Optional[TTT2]]] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make converter that returns a truthy value or ``None``. ``converter`` is called to further convert non``None`` values.
def truthy_or_none(converter: Callable[[Any], T]) -> Callable[[Any], Optional[T]]: return lambda value: converter(value) if value else None
[ "def value_or_none(converter: Callable[[Any], T]) -> Callable[[Any], Optional[T]]:\n return lambda value: None if value is None else converter(value)", "def none_or(value: Optional[TTT],\n convert: Callable[[TTT], TTT2],\n value_for_none: Optional[\n Callable[[], Optional[T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make converter that returns a string stripped of newlines or ``None``. ``converter`` is called to further convert non``None`` values.
def stripped_newlines(converter: Callable[[Any], T]) -> Callable[[Any], Optional[T]]: return lambda value: converter(value.replace('\r', '').replace('\n', ''))
[ "def convert_newlines():\n if sys.platform == \"win32\":\n return lambda s: s.replace(\"\\n\", \"\\r\\n\")\n else:\n return lambda s: s", "def to_safe_str_or_none(value: Optional[str]) -> Optional[str]:\n if value is None:\n return None\n v = str(value.strip()).replace('\\r', '')....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make converter that pads a string to the given ``length`` or ``None``. ``converter`` is called to further convert non``None`` values.
def fixed_len_str(length: int, converter: Callable[[Any], T]) -> Callable[[Any], Optional[T]]: return lambda value: converter('{value:{length}}'.format(value=value, length=length))
[ "def left_pad_sequence(length: int) -> Callable:\n return lambda n: str(n).zfill(length)", "def zeroPrepender(source, length):\n if (not source and source != 0) or not length:\n return None\n\n result = str(source)\n if len(result) >= length:\n return result\n\n for i in range(length ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert input to cleaned string or None.
def to_safe_str_or_none(value: Optional[str]) -> Optional[str]: if value is None: return None v = str(value.strip()).replace('\r', '').replace('\n', '') return v or None
[ "def _str(input):\n if input == \"\":\n return None\n return str(input)", "def normalize(value):\n if value is None:\n return None\n if isinstance(value, str):\n value = value.strip()\n if value == '':\n return None\n return value", "def _nullify(self, value):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert input to ServiceCode.
def to_service_code(value: Union[ServiceCode, int, str]) -> ServiceCode: return ServiceCode(int(value))
[ "def service_code(self):\n return self._service_code", "def carrier_service_code(self) -> CarrierServiceCode:\n return self._carrier_service_code", "def service_type_code(self):\n return self._service_type_code", "def name_to_code():\n state_codes = {\"California\": \"CA\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert input to AssignmentType.
def to_assignment_type(value: Union[AssignmentType, int, str]) -> AssignmentType: return AssignmentType(int(value))
[ "def visit_Assign(self, node):\n if type(node.value).__name__ == \"Num\":\n self.var_type = 'scalar'\n else:\n x = TypeDeducer(self.type_deducer_state)\n x.visit(node.value)\n if x.type_deducer_state.new_variable_ref:\n raise Exception(\"Attem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert input to TransactionType.
def to_transaction_type(value: Union[TransactionType, int, str]) -> TransactionType: return TransactionType(int(value))
[ "def get_tran_type(transaction):\n return transaction[0]", "def get_type():\n tx_type = sp.TRecord(to_ = sp.TAddress,\n token_id = sp.TNat,\n amount = sp.TNat).layout(\n (\"to_\", (\"token_id\", \"amount\"))\n )\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert input to RecordType.
def to_record_type(value: Union[RecordType, int, str]) -> RecordType: return RecordType(int(value))
[ "def __convert( source ):\n # Just in case things get this far but we don't know about the record\n if source['recordType'] not in definitions.RECORDS:\n return {\n 'rec_type': source['recordType']\n }\n\n # Create a flat wrapper\n record = estreamer.common.Flatdict( source )\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert input to AvtaleGiroRegistrationType.
def to_avtalegiro_registration_type( value: Union[AvtaleGiroRegistrationType, int, str] ) -> AvtaleGiroRegistrationType: return AvtaleGiroRegistrationType(int(value))
[ "def _type_convert(new_type, obj):\n return new_type(obj)", "def registration_type(self, instance):\r\n try:\r\n reg_type = mark_safe('<a href=\"{0}\">{1}</a>'.format(\r\n reverse(\r\n 'admin:registration_{0}_change'.format(\r\n instanc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert input to date or None.
def to_date_or_none(value: Optional[Union[datetime.date, str]]) -> Optional[datetime.date]: if isinstance(value, datetime.date): return value if value is None or value == '000000': return None return datetime.datetime.strptime(value, '%d%m%y').date()
[ "def _get_date(self,\n date: Optional[Union[str, datetime.date]],\n default: datetime.date) -> datetime.date:\n if type(default) != datetime.date:\n raise Exception(f\"Default date value must be datetime.date, received {type(default)}\")\n\n if date is None...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate an item group index array suppose total = 10, unitlen = 2, then we will return array [0 0 1 1 2 2 3 3 4 4]
def gen_item_group_index(total, group_len): group_count = total / group_len group_index = np.arange(total) for i in range(group_count): group_index[i * group_len: (i + 1) * group_len] = i group_index[(i + 1) * group_len : total] = i + 1 return group_index.tolist()
[ "def slices(groups):\n i = 0\n for group in groups:\n yield i, i + group\n i += group", "def distribute_uniform(totalsize, groups):\n ret = []\n for i in range(groups):\n myn = totalsize // groups\n off = 0\n leftover = totalsize % groups\n if ( i < leftover )...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the appropriate configuration object based on the environment.
def current_config(): if os.environ["ENVIRONMENT"] == "production": return Production() elif os.environ["ENVIRONMENT"] == "staging": return Staging() elif os.environ["ENVIRONMENT"] == "testing": return Testing() elif os.environ["ENVIRONMENT"] == "development": return Deve...
[ "def get_config():\n environment = os.environ.get('ENVIRONMENT', 'development')\n capitalized_env_value = environment[:1].upper() + environment[1:].lower()\n env_config_class_name = '{}Config'.format(capitalized_env_value)\n\n current_module = sys.modules[__name__]\n config_class = getattr(current_mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reteive a unique identifier for a node, or create one.
def create_or_retrieve_node_id(self, wg, node_name): try: return self.retrieve_node_id(wg, node_name) except UnknownNodeError: return self._create_node(wg, node_name)
[ "def establish_id(self):\n if self.config.node_id is None:\n self.config.node_id = str(uuid4()).replace('-', '')\n return self.config.node_id", "def get_unique_node_handle(node_name, node_type_name, node_meta_type):\n user = get_user()\n node_type = get_node_type(node_type_name)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ingest results from a node FITS file.
def ingest_node_results(self, filename, extension=-1): # Which node is this? wg, node_name = utils.parse_node_filename(filename) #node_id = self.retrieve_node_id(wg, node_name) uves_node_id = self.retrieve_node_id(wg, "UVES-{}".format(node_name)) giraffe_node_id = self.retrieve_...
[ "def export_fits(self, filename):", "def test_readfile_fits(self):\n fitsname = os.path.join(self.datadir, 'monol_testA.evt')\n command = \"{0}\".format(fitsname)\n\n hen.io.main(command.split())", "def load_results(self, targets_file):\n results_file = targets_file.replace(\"Targets...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ingest a master list of spectra from a FITS template file.
def ingest_spectra_masterlist(self, filename, extension=-1): image = fits.open(filename) data = image[extension].data # Create mapper between FITS and database columns. columns = ("cname", "ges_fld", "object", "filename", "ges_type", "setup", "wg", "ra", "dec", "snr", "vel"...
[ "def create_spectra(self):\n\t\ttry:\n\t\t\tdummy = self.obsid\n\t\t\tos.chdir(self.directory)\n\t\t\tsubprocess.call(\"punlearn specextract\", shell=True)\n\t\t\tsubprocess.call(\"pset specextract infile=\\\"{}[sky=region({})]\\\"\".format(self.file_name,self.source_file), shell=True)\n\t\t\tsubprocess.call(\"pset...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the density of the mask's model.
def mask_density(mask): return get_number_of_unpruned_weights(mask).float() / get_number_of_weights(mask).float()
[ "def density(self):\n return self.nnz/self.dim", "def density(self):\n return self.get_density()", "def density(self):\n return self.fluid.density(self.T_C)", "def density(self):\n return self._density", "def Density(self, *args):\n return _gmat_py.AtmosphereModel_Density(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return number of unpruned weights.
def get_number_of_unpruned_weights(mask: Mask): return torch.sum(torch.Tensor([torch.sum(torch.Tensor(values.cpu())) for values in mask.values()]))
[ "def num_weights(self):\n pass", "def weight_count(self):\n N = sum([layer.W.size for layer in self.layers])\n return N", "def numWeights(self):\r\n\t\treturn None", "def num_weights(self) -> int:\n return self._num_weights", "def nobs(self):\n return self.sum_weights", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Consume (advancing self.pos) some characters based on a regex. The regex is applied to a slice of self.text starting from self.pos and ending at the end of the string. Note that matches are only ever expected at the start of the string slice.
def _consume(self, pattern): if self.is_finished: raise StopIteration() found = re.match(pattern, self.text[self.pos:]) if found is None: return None self.pos += found.end() return found.group()
[ "def run(self, content):\n parts = []\n offset = 0\n for match in self.regexp.finditer(content):\n parts.append(content[offset:match.start(0)])\n parts.append(self.replace(match))\n offset = match.end(0)\n parts.append(content[offset:])\n return ''...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The forward model must make a prediction of the experimental data we would expect to measure given a specific state of the system, which is specified by the model parameters theta.
def forward_model(self, x, theta): # unpack the model parameters A1, w1, A2, w2, bg = theta # evaluate the peaks peak_1 = A1 / ((1 + ((x - self.c1)/w1)**2)*(pi*w1)) peak_2 = A2 / ((1 + ((x - self.c2)/w2)**2)*(pi*w2)) # return the prediction of the data return peak...
[ "def _predict_trajectory(self, current_state, accel):\n # Computing predicted trajectory\n x_pred = dot(self.a0_mat, current_state) + dot(self.lambda_mat, accel)\n\n return x_pred", "def forward_propagation(self):\n pred_y = argmax(self.model.predict(train_x), axis=1)\n\n accura...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
y is a length n_verts vector of labels returns a length n_verts vector in the same order as the input indicates which block each node is
def _get_block_indices(y): block_labels, block_inv, block_sizes = np.unique( y, return_inverse=True, return_counts=True ) n_blocks = len(block_labels) block_inds = range(n_blocks) block_vert_inds = [] for i in block_inds: # get the inds from the original graph inds = np...
[ "def _get_block_indices(y: np.ndarray) -> Tuple[List[np.ndarray], range, np.ndarray]:\n block_labels: np.ndarray\n block_inv: np.ndarray\n block_sizes: np.ndarray\n block_labels, block_inv, block_sizes = np.unique(\n y, return_inverse=True, return_counts=True\n )\n\n n_blocks = len(block_la...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to calculate check digit and return full bowler ID
def UpdateID(bowler): # initialize weights weights = [1, 3, 6, 7] # initialize sum of products sum_of_products = 0 # loop to compute sum of products for i in range(len(bowler)): sum_of_products += int(bowler[i]) * weights[i] # calculate modulo arithmetic check_digit = sum_of_prod...
[ "def check_digit(self) -> str:\n return self._id[-1]", "def as_ferwar(self):\n # convert to decimal id using 11 least significant bits\n bin_9 = self.as_bin_9()\n decimal_id = int(''.join([str(c) for c in bin_9[:11]]), 2)\n parity_bit = bin_9[-1]\n\n # determine what kind...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize a new iDevice, setting a unique id
def __init__(self, title, author, purpose, tip, icon, parentNode=None): log.debug("Creating iDevice") self.edit = True self.lastIdevice = True self.emphasis = Idevice.NoEmphasis self.version = 0 self.id = unicode(Idevice.nextId) Idevice.next...
[ "def create(cls, imei, device_id):\n try:\n imei_device = cls(imei, device_id)\n imei_device.save()\n except Exception:\n raise Exception", "def initialise_device(self):\n pass", "def set_device_id(d):\n _cudanet.set_device_id(ct.c_int(d))", "def __init...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clone an iDevice just like this one
def clone(self): log.debug("Cloning iDevice") newIdevice = copy.deepcopy(self) return newIdevice
[ "def clone(self):\n miniMe = Idevice.clone(self)\n for field in miniMe.fields:\n field.idevice = miniMe\n return miniMe", "def clone_device(device, new_name):\n command = 'clone \"%s\" \"%s\"' % (device.udid, new_name)\n device_id = _run_command(command)\n\n # The device I...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete an iDevice from it's parentNode
def delete(self): while self.userResources: self.userResources[0].delete() if self.parentNode: self.parentNode.idevices.remove(self) self.parentNode = None
[ "def removeDevice(self, node, fullDeviceName):", "def delete_node(self, node):", "def SceneNode_removeChild(_parent, _node):\n _parent.removeChild(_node)", "def delete(self, node):\n pass", "def remove_device(self, device):\n\n\t\tself._libinput.libinput_path_remove_device(device._handle)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if this is the first iDevice in this node
def isFirst(self): index = self.parentNode.idevices.index(self) return index == 0
[ "def is_found(self):\n return bool(self._get_devices_info())", "def is_first_cell(self):\n\n return self._executor.is_first_cell()", "def is_primary_interface(self, ifname):\n return self.get_primary_interface() == ifname", "def is_head(self):\n return idc.is_head(self.flags)", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if this is the last iDevice in this node
def isLast(self): index = self.parentNode.idevices.index(self) return index == len(self.parentNode.idevices) - 1
[ "def is_last(self) -> bool:\n return self._node is self._linked_list._last", "def is_last(self) -> bool:\n return self._is_last", "def is_end_device(self) -> bool | None:\n if self._zigpy_device.node_desc is None:\n return None\n\n return self._zigpy_device.node_desc.is_en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Upgrades the Idevice class members from version 0 to version 1. Should be called in derived classes.
def _upgradeIdeviceToVersion1(self): log.debug("upgrading to version 1") self._title = self.__dict__.get('title', self.title) self._author = self.__dict__.get('author', self.title) self._purpose = self.__dict__.get('purpose', self.title) self._tip = self.__dict__.get('tip'...
[ "def upgradeToVersion1(self):\n log.debug(\"Upgrading iDevice\")\n if self.class_ in (\"objectives\", \"activity\", \"reading\", \"preknowledge\"):\n self.icon = self.class_\n else:\n self.icon = \"generic\"", "def _upgradeIdeviceToVersion2(self):\n log.debug(\"up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Upgrades the Idevice class members from version 1 to version 2. Should be called in derived classes.
def _upgradeIdeviceToVersion2(self): log.debug("upgrading to version 2, for 0.12") self.userResources = [] if self.icon: self.systemResources = ["icon_"+self.icon+".gif"] else: self.systemResources = []
[ "def _upgradeIdeviceToVersion1(self):\n log.debug(\"upgrading to version 1\")\n self._title = self.__dict__.get('title', self.title)\n self._author = self.__dict__.get('author', self.title)\n self._purpose = self.__dict__.get('purpose', self.title)\n self._tip = self.__dict...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scales the predicted boxes in order to be drawable on the image
def scale_boxes(boxes, image_shape): height = image_shape[0] width = image_shape[1] image_dims = K.stack([height, width, height, width]) image_dims = K.reshape(image_dims, [1, 4]) boxes = boxes * image_dims return boxes
[ "def _scale_boxes(self, boxes):\n height, width = self._dims\n image_dims = K.stack([height, width, height, width])\n image_dims = K.reshape(image_dims, [1, 4])\n boxes = boxes * image_dims\n return boxes", "def scale_boxes(boxes, image_shape):\n height = image_shape[0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the forward pass for an affine function. The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N examples, where each example x[i] has shape (d_1, ..., d_k). We will reshape each input into a vector of dimension D = d_1 ... d_k, and then transform it to an output vector of dimension M.
def affine_forward(x, w, b): ############################################################################ # TODO: Implement the affine forward pass. Store the result in 'out'. You # # will need to reshape the input into rows. # ######################################################...
[ "def affine_forward(x, w, b):\n out = None\n \n # reshape the input into (N, d_1 *...* d_k)\n input_shape = x.shape\n prod = 1\n for i in range(1,len(input_shape)):\n prod *= input_shape[i]\n\n a = x.reshape(x.shape[0],prod)\n out = np.dot(a,w) + b\n \n cache = (x, w, b)\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Factory function returning appropriate XML writer object for chart_type, loaded with series_seq.
def ChartXmlWriter(chart_type, series_seq): try: BuilderCls = { XL_CHART_TYPE.BAR_CLUSTERED: _BarChartXmlWriter, XL_CHART_TYPE.BAR_STACKED_100: _BarChartXmlWriter, XL_CHART_TYPE.COLUMN_CLUSTERED: _BarChartXmlWriter, XL_CHART_TYPE.COLUMN_STACKED: _BarChar...
[ "def _factory(*args_, **kwargs_):\n return SeriesType(*args_, **kwargs_)", "def chooseWriter(self, file_format, vtk_dataset_type):\n if file_format == 'ply':\n return vtk.vtkPLYWriter()\n # For now we'll just return the POLYDATA writer since methods work\n # only with that v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the state of bool and returns it as a string
def get_state_tostring(rapid_data): try: if rapid_data.RapidType == 'bool': res = 'State = %s' % rapid_data.Value return res else: err = 'DataType is ' + rapid_data.RapidType + ' and not bool.' return err except Exception, err: return e...
[ "def boolToString(aBoolean):\n if aBoolean:\n return \"true\"\n return \"false\"", "def bool_to_str(boolean):\n if boolean:\n return \"1\"\n return \"0\"", "def bool2string(bool):\n return ('True' if bool else 'False')", "def test_get_state_tostring_correct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a group for each volume in Cubit and add the volume to its group This is useful when working with assemblies, as the group structuring is retained throughout webcutting for eventual hexmeshing. This makes it easier to apply operations onto entire 'parts', such as imprint and merge operations.
def part_volumes_to_part_groups(prefix=None): if prefix == None: prefix = "part" V = cubit.get_entities("volume") for vid in V: cubit.cmd(f"create group '{prefix}_{vid}'") cubit.cmd(f"{prefix}_{vid} add volume {vid}")
[ "def create_groups ():\n group_list = ['Cores', 'Coords', 'Vols',]\n for group_name in group_list:\n create_group (group_name)", "def make_multi_vgroups(module):\n changed = True\n if not module.check_mode:\n bw_qos_size = iops_qos_size = 0\n names = []\n array = get_array(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cycle through each group in Cubit and apply imprint and merge operations This script is intended to work in conjunction with the `part_volumes_to_part_groups()` method provided above, to simplify imprint and merge mesh operations on assemblies.
def imprint_merge_each_group(): G = cubit.get_entities("group") for gid in G: vid = cubit.get_group_volumes(gid) if len(vid)>1: cubit.cmd(f"imprint vol {list_to_str(vid)}") cubit.cmd(f"merge vol {list_to_str(vid)}")
[ "def part_volumes_to_part_groups(prefix=None):\r\n \r\n if prefix == None:\r\n prefix = \"part\"\r\n V = cubit.get_entities(\"volume\")\r\n for vid in V:\r\n cubit.cmd(f\"create group '{prefix}_{vid}'\")\r\n cubit.cmd(f\"{prefix}_{vid} add volume {vid}\")", "def testProgressiveOutgroupsVsAllOutgroups...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that takes as input a partiallybuilt SQuAD DataFrame (with at least ['context', 'answer', 'answer_start'] columns) and returns the same DataFrame with the new column 'answer_end', that consists of last answer character index
def _add_end_index(self, df): ans_end = [] for index, row in df.iterrows(): t = row.answer s = row.answer_start ans_end.append(s + len(t)) df["answer_end"] = ans_end return df
[ "def parse_df(self, kb_name, df, answer_col, query_col='', context_col='context_string'):\n df = df.assign(context_string = '') if context_col == 'context_string' else df \n df = df.rename(columns = {\n answer_col: 'raw_string', \n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove rows that contain incorrect answers, (either because of the the tokenizer's truncation or because they were not correct in the first place)
def _remove_lost_answers(self, df): tokenized_contexts = self.tokenizer.tokenize( df["context"].tolist(), "context", special=False ) lost_truncated, lost_dirty = self._lost_answers_indexes(df, tokenized_contexts) to_remove = lost_truncated + lost_dirty clean_df = df.d...
[ "def clean_data(inputFile, cutoff=0.95):\r\n ISOcodes = {'sk': 0, 'fr': 1, 'es': 2, 'de': 3, 'pl': 4}\r\n\r\n df = pd.read_csv(inputFile, encoding=\"utf8\")\r\n df['text'].replace('', np.nan, inplace=True)\r\n df.dropna(subset=['text'], inplace=True)\r\n total = len(df)\r\n englishCount, misclassi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Group answers to the same question into a single row
def _group_answers(self, df): if "answer" not in df.columns: return df return ( df.groupby(["question_id", "question", "title", "context_id", "context"]) .agg({"answer": list, "answer_start": list, "answer_end": list}) .reset_index() )
[ "def parse_multiple_answers_question(q_name, index):\n aindex = index + 1\n length_check = len(cells) <= aindex\n cell_type_check = cells[aindex][\"metadata\"][\"ctype\"] != \"answer\"\n\n if length_check or cell_type_check:\n raise Exception(\"WARNING: multiple answers question has no answer cel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots up to 4 columns as before and after normalization, using the number of bins as passed
def compare_histograms(df, df_norm, fignum, fields, binns): fig = plt.figure(num=fignum, figsize=(18,18)) fig.suptitle('Histogram before and after normalization', fontsize=22) ax1 = fig.add_subplot(421, axisbg='0.94') ax2 = fig.add_subplot(422, axisbg='0.94') ax3 = fig.add_subplot(423, axisbg='0.94'...
[ "def convert_to_hist(df,nbins = 100,normalise = True):\n x_values = []\n y_values = []\n x_unique = df.x.unique()\n x_max = df.x.max()\n x_min = df.x.min()\n x_values.append(x_min)\n print(x_min)\n y_values.append(df.y[df.x == x_min].tolist()[0])\n bins = np.linspace(x_min,x_max,nbins)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to validate fetcher access points of a given data source
def checkAccessPoint(AccessPoint): def wrapper(*args): if AccessPoint.__name__ not in args[0].valid_access_points: raise InvalidFetcherAccessPoint( "'%s' not available with '%s' src. Available access point(s): %s" % (AccessPoint.__name__, a...
[ "def validate_url_access_rule_condition(self, args: dict[str, Any]):\n validate = partial(validate_argument, args=args)\n if args.get(\"source_address\") == ArgumentValues.ENABLE.value:\n validate(key_=\"source_address_type\")\n if args.get(\"source_address_type\") == ArgumentVal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch and return data as xarray.DataSet Returns
def to_xarray(self, **kwargs): if not self.fetcher: raise InvalidFetcher( " Initialize an access point (%s) first." % ",".join(self.Fetchers.keys()) ) xds = self.fetcher.to_xarray(**kwargs) xds = self.postproccessor(xds) return xds
[ "def fetch(self, grouped: VirtualDatasetBox, **load_settings: Dict[str, Any]) -> xarray.Dataset:\n raise NotImplementedError", "def to_xarray(self, errors: str = 'ignore'):\n\n # Download data\n if not self.parallel:\n if len(self.uri) == 1:\n ds = self.fs.open_datas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear data cached by fetcher
def clear_cache(self): if not self.fetcher: raise InvalidFetcher( " Initialize an access point (%s) first." % ",".join(self.Fetchers.keys()) ) return self.fetcher.clear_cache()
[ "def clear_cache(self):", "def clearCache( self ):\n self._cache = self._dataset", "def clear_cache(self):\n requests.get(url=self.proxy_url+'/clear_cache')", "def clear_cache(self):\n pass", "def clear_data_cache():\n load_glove.cache_clear()", "def clear_cache(self):\n self._c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch and return index data as xarray DataSet This is a shortcut to .load().index.to_xarray() Returns
def to_xarray(self, **kwargs): if self._AccessPoint not in self.valid_access_points: raise InvalidFetcherAccessPoint( " Initialize an access point (%s) first." % ",".join(self.Fetchers.keys()) ) return self.load().index.to_xarray(**kwargs)
[ "def get_data_by_index(self, index):\n pass", "def get_results(self):\n self.store.consolidate()\n\n # TODO: replace index variables data with simulation data\n # (could be advanced Index objects that don't support serialization)\n\n ds_out = (\n self.store.open_as_xr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a learning rate argument into an initial rate and an optional scheduler callback.
def parse_learning_rate_arg(learning_rate: str): sp = str(learning_rate).split('*') initial = float(sp[0]) if len(sp) == 1: return initial, [] elif len(sp) == 2: return initial, [_parse_schedule(sp[1])] assert False
[ "def init_lr(self):\n if isinstance(self.config.train.lr, str):\n self.learning_rate = 0.02\n else:\n self.learning_rate = self.config.train.lr", "def _update_initial_learning_rate(configs, learning_rate):\n\n optimizer_type = get_optimizer_type(configs[\"train_config\"])\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }