query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Creates a utf8 encoded file with each argument in arguments on a separate line.
def CreateArgFile( arguments, tmpDir ): tmpFile = os.path.join( tmpDir, "args.txt" ) with io.open( tmpFile, 'w', encoding="utf-8-sig" ) as fileHandle: fileHandle.write( "\n".join( arguments ) ) return tmpFile
[ "def export_ascii(self, filename):", "def writeArgs(args,out):\n\n\t#Make string with all arguments\n\targString = ''\n\tfor arg,value in sorted(vars(args).items()):\n\t\tif type(value) is list:\n\t\t\tif len(value) > 0:\n\t\t\t\tvalue = ','.join(map(str,value))\n\t\t\telse:\n\t\t\t\tvalue = value[0]\n\t\targStri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run DeadlineCommand with the specified arguments returning the standard out
def CallDeadlineCommand(arguments, hideWindow=True, useArgFile=False, useDeadlineBg=False, raiseOnExitCode=False): deadlineCommand = GetDeadlineCommand( useDeadlineBg ) tmpdir = None if useArgFile or useDeadlineBg: tmpdir = tempfile.mkdtemp() if useDeadlineBg: arguments = [ "-outputfil...
[ "def _call_deadline_command_raw(self, arguments):\n # make a copy so we don't mutate the caller's reference\n arguments = list(arguments)\n arguments.insert(0, self._deadline_command_path)\n try:\n proc = subprocess.Popen(\n arguments,\n stdin=sub...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the path to the file where we will store sticky settings
def GetStickySettingsFilePath(): global submissionInfo deadlineHome = submissionInfo[ "UserHomeDir" ].strip() return os.path.join( deadlineHome, "settings", "katana_sticky.json" )
[ "def getMeteorSettingsFilePath(self):\n directory = tempfile.gettempdir()\n name = self.settingsFile.name\n return os.path.join(directory, name)", "def settingsFilePath(self):\n return self._settingsFilePath", "def bot_settings_file(self):\r\n return os.path.join(self.bot_fold...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the current settings from Submitter UI to the sticky settings file.
def WriteStickySettings( gui ): global stickySettingWidgets, stickyWidgetSaveFunctions print( "Writing sticky settings..." ) configFile = GetStickySettingsFilePath() stickySettings = {} for setting, widgetName in stickySettingWidgets.iteritems(): try: widget = getattr( gui, wi...
[ "def save_settings(self):\n logging.info(\"Saving settings.\")\n write_settings(self.settings)", "def save_settings(self):\n with open(self.settings_path, \"w\") as f:\n json.dump(self.settings, f, indent=4)", "def save_settings(self):\n settings = self.get_settings()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads in settings from the sticky settings file, then update the UI with the new settings
def LoadStickySettings( gui ): global stickySettingWidgets, stickyWidgetLoadFunctions configFile = GetStickySettingsFilePath() print( "Reading sticky settings from: %s" % configFile ) stickySettings = None try: with io.open( configFile, "r", encoding="utf-8" ) as fileHandle: sti...
[ "def update_settings(settings):", "def update_control_widgets(self):\n logger.info(f'Loading settings: {self.settings_dict}')\n for k, section in self.settings_dict.items():\n for setting_name, value in section.items():\n self.set_control_value(setting_name, value)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a url patternesque string into a path, given a context dict, and splits the result.
def pathify(urlpattern, **context): repl = lambda match: context[match.group(1)] path = re.sub(r':([a-z]+)', repl, urlpattern) return tuple(path[1:].split('/'))
[ "def split_string_path(base, path):\n for i in range(len(path)):\n if isinstance(base, string_types):\n return path[:i], path[i:]\n base = base[path[i]]\n return path, ()", "def splitpath(self):\n \n pass", "def urlToPath(url):", "def resolveContext(self, context):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
init cluster_temp for all the center point
def __initCluster(self): data_size, cluster_center = self.data_size, self.cluster_center self.cluster_temp = np.zeros(data_size, dtype=int) self.cluster_upper_bound = np.full(len(cluster_center), float('inf'), dtype=float) for center in cluster_center: self.cluster_temp[cente...
[ "def initClusters(self):\n print 'Initializing Cluster Centers'\n numFeatureAddedForCluster = [0]*self.k\n # initialize numclass of -out of-k cluster to be the center of the full sketches\n if self.numclass <= self.k:\n for fidx in self.fullIndex:\n fclass = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculate the delta of each vector save the delta point as master
def calculate_delta(self): rho_des_index, distance, data_size = self.rho_des_index, self.distance, self.data_size self.result[rho_des_index[0]][1] = -1 for i in range(1, data_size): for j in range(0, i): old_i, old_j = rho_des_index[i], rho_des_index[j] ...
[ "def delta(vector):\r\n if (len(vector) <= 1):\r\n return 0\r\n \r\n else:\r\n result_vector = []\r\n for index in range(len(vector)-1):\r\n result_vector.append(vector[index+1] - vector[index])\r\n return result_vector", "def calc_dDelta(self):\n self.dDelta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
use the multiplication of normalized rho and delta as gamma to determine cluster center
def calculate_gamma(self): result = self.result # scaler = preprocessing.StandardScaler() # train_minmax = scaler.fit_transform(result) # st_rho, st_delta = train_minmax[:, 0], train_minmax[:, 1] # self.gamma = (st_delta + st_rho) / 2 self.gamma = result[:, 0] * result[:,...
[ "def calculate_cluster_center(self, threshold):\n gamma = self.gamma\n self.cluster_center = np.where(gamma >= threshold)[0]", "def _estimate_gamma_dist(self,mean,std):\n var = std*std\n k = mean*mean/var\n omega = var/mean\n\n assert (k>0) & (omega>0), \"No gamma distribution with mean:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Intercept a point with gamma greater than 0.2 as the cluster center
def calculate_cluster_center(self, threshold): gamma = self.gamma self.cluster_center = np.where(gamma >= threshold)[0]
[ "def gaussian(centre, k, intensity, xpos):\r\n\treturn intensity * np.exp(- np.power(k * (xpos - centre), 2))", "def predict_center(point):\n point_cluster_num = predict_cluster(point)\n center = centers[point_cluster_num]\n return center", "def center(x):\n return x - x.mean()", "def orthogonalIn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initial configuration. Used to specify your username, password and domain. Configuration is stored in ~/.accountable/config.yaml.
def configure(username, password, domain): art = r''' Welcome! __ ___. .__ _____ ____ ____ ____ __ __ _____/ |______ \_ |__ | | ____ \__ \ _/ ___\/ ___\/ _ \| | \/ \ __\__ \ | __ \| | _/ __ \ / __ \\ \__\ \__( <_> ) | / | \ | / __ \| \_\ \ |_...
[ "def login_with_config(self):\n username = self.cfg.get('user', 'username')\n password = token = None\n\n try:\n password = self.cfg.get('user', 'password')\n except configparser.NoOptionError:\n pass\n try:\n token = self.cfg.get('user', 'token')\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all issue types. Optional parameter to list issue types by a given project.
def issuetypes(accountable, project_key): projects = accountable.issue_types(project_key) headers = sorted(['id', 'name', 'description']) rows = [] for key, issue_types in sorted(projects.items()): for issue_type in issue_types: rows.append( [key] + [v for k, v in sor...
[ "def request_issue_types(cfg):\n url = cjm.request.make_cj_url(cfg, \"issuetype\")\n return cjm.request.make_cj_request(cfg, url).json()", "def issue_types(self):\n return ['issue']", "def get_relevant_issue_classes(project):\n allowed_tags = ['generic'] + [tag.name for tag in project.tags]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists all comments for a given issue key.
def comments(accountable): comments = accountable.issue_comments() headers = sorted(['author_name', 'body', 'updated']) if comments: rows = [[v for k, v in sorted(c.items()) if k in headers] for c in comments] rows.insert(0, headers) print_table(SingleTable(rows)) ...
[ "def request_issue_comments_regexp(cfg, issue_key, comment_re):\n # pylint: disable=too-many-nested-blocks\n\n comments = []\n comments_url = cjm.request.make_cj_url(cfg, \"issue\", issue_key, \"comment\")\n\n start_at = 0\n max_results = 50\n\n while True:\n response = cjm.request.make_cj_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a comment to the given issue key. Accepts a body argument to be used as the comment's body.
def addcomment(accountable, body): r = accountable.issue_add_comment(body) headers = sorted(['author_name', 'body', 'updated']) rows = [[v for k, v in sorted(r.items()) if k in headers]] rows.insert(0, headers) print_table(SingleTable(rows))
[ "def add_issue_comment(self, issue_comment):\r\n\t\tself[\"issueComments\"][issue_comment[\"id\"]] = issue_comment", "def create_issue_comment(self, body):\n json = None\n if body:\n owner, repo = self.repository\n owner = owner.split('/')[-1]\n u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all worklogs for a given issue key.
def worklog(accountable): worklog = accountable.issue_worklog() headers = ['author_name', 'comment', 'time_spent'] if worklog: rows = [[v for k, v in sorted(w.items()) if k in headers] for w in worklog] rows.insert(0, headers) print_table(SingleTable(rows)) else: ...
[ "def get_worklog(issue):\n\tworklogs = []\n\tworklog_field = issue.get('fields', {}).get('worklog', False)\n\n\tif worklog_field:\n\t\tworklogs = worklog_field.get('worklogs', [])\n\n\treturn worklogs", "def obtain_worklogs(issues, start_date, end_date, session_data):\n issue_keys = dict()\n all_wor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all possible transitions for a given issue.
def transitions(accountable): transitions = accountable.issue_transitions().get('transitions') headers = ['id', 'name'] if transitions: rows = [[v for k, v in sorted(t.items()) if k in headers] for t in transitions] rows.insert(0, headers) print_table(SingleTable(rows...
[ "def get_transitions(issue):\n\ttransitions = issue.get('transitions', [])\n\treturn [\n\t\t{\n\t\t\t'name': transition.get('name', ''),\n\t\t\t'id': transition.get('id', ''),\n\t\t}\n\t\tfor transition in transitions\n\t]", "def list_transitions_command(args):\n issue_id = args.get('issueId')\n transitions...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Debug breakpoint while in curses mode
def _D(stdscr): curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() import pdb; pdb.set_trace()
[ "def debugger_enable_breakpoint():", "def debugger_break_now():", "def debugger_add_hw_breakpoint():", "def gdb_breakpoint():\n _gdb_python_call_gen('gdb_breakpoint')()", "def debugger_show_breakpoints():", "def debugger_add_sw_breakpoint():", "def _debug_trace():\n from PyQt4.QtCore import pyqtRe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve yaml data from a given path if file not exist, return False
def get_yaml_data(path): yaml_path = "%s%s.yml" % (CONTENT_FILE_DIR, path[:-5]) if os.path.isfile(yaml_path): f = open(yaml_path, 'r') template_data = yaml.load(f) return template_data else: return False
[ "def load_yaml(path):\n if os.path.exists(path):\n f = open(path)\n data = yaml.load(f)\n f.close()\n return data\n else:\n return {}", "def load(key, path='farmboy.yaml'):\n try:\n doc = yaml.load(open(path))\n return doc.get(key, None)\n except IOErro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try and determine the correct _ (underscore) template matching the files directory structure
def determine_template_by_path(path): path = path.lstrip('/') path_chunks = re.split('\/', path) if len(path_chunks) <= 1: return path else: """ For now be ignorant and just return the first entry of the list as the possible template name, so in fact ...
[ "def find_custom_template(args):\n for arg in args:\n if os.path.isdir(arg):\n dirlist = os.listdir(arg)\n if \"custom.html\" in dirlist:\n return os.path.join(arg, \"custom.html\")\n elif \"custom.jinja\" in dirlist:\n return os.path.join(arg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
constructor instantiate a Document with a term_list to be converted into dict
def __init__(self, term_list, links=[]): # do type check if not isinstance(term_list, list): raise TypeError('term_list must be of type list') if not isinstance(links, list): raise TypeError('links must be of type list') self.term_dict = {x: term_list.count(x) for x in term_list} self.links = copy.deepc...
[ "def parse_doc(self, doc_as_list):\n\n tweet_id = doc_as_list[0]\n tweet_date = doc_as_list[1]\n full_text = doc_as_list[2]\n url = doc_as_list[3]\n indice = doc_as_list[4]\n retweet_text = doc_as_list[5]\n retweet_url = doc_as_list[6]\n retweet_indice = doc_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
init Construct a DocumentSet with main document
def __init__(self, main_doc): if not isinstance(main_doc, Document): raise TypeError('term must be of type Document') self.main_doc = main_doc self.env_docs = []
[ "def create(init_document: 'Document') -> 'DocumentArray':", "def __init__(self, description, corpus_documents):\n self.description = description\n self.documents = corpus_documents\n self.doc_map = {}\n for doc in self.documents:\n self.doc_map[doc.identifier] = doc", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add Env Page append a new env_page to env_docs
def add_env_page(self, env_page): if not isinstance(env_page, Document): raise TypeError('env_page must be of type Document') self.env_docs.append(env_page)
[ "def addPage(self, name, page, **attrs):\n page.globalConfig = self.globalConfig\n page.pageConfig['pageName'] = name\n self.globalConfig.pageList.append(name)\n self.globalConfig.pageAttributes[name] = dict(attrs)\n setattr(self,name,page) # Link page into page tree (for Cherry...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Count term in environment calculate idf of a term in main doc
def __count_term_in_env(self, term): # type check if not isinstance(term, str): raise TypeError('term must be of type str') total_cnt = float(len(self.env_docs)) + 1.0 if total_cnt == 1.0: return 1.0 cnt = 1.0 for doc in self.env_docs: if term in doc.term_dict: cnt += 1.0 return math.log(to...
[ "def _calculate_idf(self, term):\n term = self._ignore_case(term)\n if term not in self._docs:\n return 0\n else:\n num_occ = len(self._docs[term])\n return math.log(self._num_docs/num_occ)", "def term_idf(self, term):\n idf = math.log(2 + self.count_te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Statistic TF calculate and sort terms in main doc by tf
def statistic_tf(self): return sorted(self.main_doc.term_dict.items(), key=operator.itemgetter(1), reverse=True)
[ "def statistic_tfidf(self):\n\t\t# calculate df-idf for all words\n\t\tcount_dict = {x: self.main_doc.term_dict[x] * self.__count_term_in_env(x) for x in self.main_doc.term_dict}\n\t\t# sort them by df and idf\n\t\treturn sorted(count_dict.items(), key=operator.itemgetter(1), reverse=True)", "def tf(word, documen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Statistic TFIDF calculate and sort terms in main doc by tfidf
def statistic_tfidf(self): # calculate df-idf for all words count_dict = {x: self.main_doc.term_dict[x] * self.__count_term_in_env(x) for x in self.main_doc.term_dict} # sort them by df and idf return sorted(count_dict.items(), key=operator.itemgetter(1), reverse=True)
[ "def tf_idf_score():\n\n global final_doc_set\n global final_dictionary\n final_score = []\n\n for doc_id in final_doc_set:\n score = 0\n for query_term in final_dictionary.keys():\n if final_dictionary[query_term][1].get(doc_id):\n tf = final_dictionary[query_ter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the menu and return either None (if an exit key was pressed) or FindTweetMenu.BACK_INDEX
def showAndGet(self): keywords = TerminalInterface.getSearchKeywords() # If user did not enter any keywords, return FindUserMenu.BACK_INDEX if keywords is None: return FindTweetMenu.BACK_INDEX tweetGeneratorMethod = lambda: TweetsTableTools.findTweets( self._connection, keywords) menu = TweetsMenu(self...
[ "def return_menu(self):\n while True:\n number = pyip.inputNum(\"0. Back to the main menu: \")\n if number == 0:\n # Clean up the console\n self.clear_console()\n # back to the main menu\n self.run()\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses an index array to obtain indices using an index array along an axis.
def select_indices(arr,index_arr,axis=-1): shape_list=(lambda x,y: [ 1 if dim!=x else y for dim in range(len(arr.shape))] ) indices_list=[np.reshape(np.arange(length),shape_list(length_id,length)) for length_id,length in enumerate(arr.shape)] indices_list[axis]=index_arr return arr.rav...
[ "def index(dims, axis):\n return intrinsic('index', axis, *dims)", "def pndindex(*args):\r\n return np.ndindex(*args)", "def pndindex(*args):\n return np.ndindex(*args)", "def view_along_axis(arr, indices, axis):\n slices = [slice(None)] * arr.ndim\n slices[axis] = sliceify(indices)\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Continous loop of inputs and answers
def evaluateCycle(self): print("Enter q or quit to exit") input_sentence = '' while(1): # Get input sentence input_sentence = input('> ') # Check if it is quit case if input_sentence == 'q' or input_sentence == 'quit': break ans = self....
[ "def user_answer(self):\n #for inputs in range(0, 1):\n self.answer.append(input(\"Your Answer: \"))\n return self.answer", "def main():\n min_random = 10 #keeping constant for the min random number range\n max_random = 99 #keeping constant for the max random number range\n count = 0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute html_reporter if html flag is exist in sys.argv.
def __execute_reporter(self): if not self.__args.report: return reporter.HTMLReporter().generate_report_from_file( self.__lst_json_files)
[ "def do_html(self, subcmd, opts, path):\n mgr = Manager()\n try:\n if opts.browse:\n htmls = []\n buf = mgr.buf_from_path(path, lang=opts.lang)\n html = buf.to_html(True, True, title=path,\n do_trg=opts.do_trg,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all scenario in folder. Recursive to sub folder if "rd" argument appear in sys.argv.
def __get_list_scenarios_in_folder(self): # If both directory and recur_directory are exist # then show "Invalid command" and exit. if self.__args.directory is not "" \ and self.__args.recur_directory is not "": utils.print_error("\n{}\n".format(constant.ERR_COMMAND_E...
[ "def getImmediateSubdirectories(dir):", "def get_run_subdirs(dirpath):\n patt = '^' + dirpath + r'/run'\n return get_subdirs(dirpath, patt)", "def open_run_list(base_path, filter=None):\n dir_list = listdir(base_path)\n if not dir_list:\n return []\n if filter is not None:\n filter_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a tuple representing a circle as (x,y,radius) and returns a tuple with the x,y coordinates and width,size (x,y,w,h)
def circle_2_tuple(circle): assign_coord = lambda x,y: x - y if x > y else 0 x = assign_coord(circle[0],circle[2]) y = assign_coord(circle[1],circle[2]) assign_size = lambda x,y : y*2 if x > y else y*2 - (y-x) w = assign_size(circle[0],circle[2]) h = assign_size(circle[1],circle[2]) retur...
[ "def circle_2_bbox(circle):\n x,y,w,h = circle_2_tuple(circle)\n return ((x,y),(x+w,y+h))", "def circle(r):\r\n pi=3.14\r\n area=pi*r*r\r\n perimeter=2*pi*r\r\n return(area,perimeter)", "def circle(radius=2, exclude_center: bool=False) -> tuple:\n if radius < 0:\n return\n rr = (r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a tuple representing a circle as (x,y,radius) and returns a tuple represeting a bbox ((x,y),(x',y'))
def circle_2_bbox(circle): x,y,w,h = circle_2_tuple(circle) return ((x,y),(x+w,y+h))
[ "def circle_2_tuple(circle):\n assign_coord = lambda x,y: x - y if x > y else 0\n x = assign_coord(circle[0],circle[2])\n y = assign_coord(circle[1],circle[2])\n\n assign_size = lambda x,y : y*2 if x > y else y*2 - (y-x) \n w = assign_size(circle[0],circle[2])\n h = assign_size(circle[1],circle[2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a tuple of tuples represeting a bbox ((x,y),(x',y')) and returns
def fix_bbox(bbox,img_shape): x = min(bbox[1][0],img_shape[1]) y = min(bbox[1][1],img_shape[0]) return ((bbox[0]),(x,y))
[ "def circle_2_bbox(circle):\n x,y,w,h = circle_2_tuple(circle)\n return ((x,y),(x+w,y+h))", "def get_bbox(bbox):\n xmin, ymin, w, h = bbox\n xmin = round(xmin)\n ymin = round(ymin)\n xmax = round(xmin + w) - 1\n ymax = round(ymin + h) - 1\n return [xmin, ymin, xmax, ymax]", "def points_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws bboxes in a image given an array of circles [(x,y,radius)]
def bbox_from_circle(img, circles): seg_imgs = [] bboxes = [] aux = img.copy() for i,el in enumerate(circles): bbox = circle_2_bbox(el['coord']) bbox = fix_bbox(bbox,aux.shape) cv.rectangle(aux,bbox[0],bbox[1],(0,255,0)) bboxes.append(bbox) return bboxes
[ "def draw_bboxes(img, bboxes, c='r'):\n plt.imshow(img)\n for bbox in bboxes:\n draw_bbox(bbox, c)", "def show_bboxes(img, bounding_boxes, facial_landmarks=[]):\n\n img_copy = np.copy(img)\n\n for b in bounding_boxes:\n x1, y1, x2, y2 = int(b[0]), int(b[1]), int(b[2]), int(b[3])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate heterozygosity samples = list of sample names vcf = VCF file
def calHet( inFile, varType ): names = [] print("Sample\tfracHet\thetCt\thomCt") # print header with open( inFile, 'r') as files: # open sample name file for i in files: i = i.rstrip() vcf = i + "." + varType + ".vcf" ...
[ "def get_samples(self):\n\t\twith gzip.open(self.vcf, 'r') as infile:\n\t\t\tfor line in infile:\n\t\t\t\tif line.startswith(\"##\"):\n\t\t\t\t\tself.header = self.header + line\n\t\t\t\tif line.startswith(\"#C\"):\n\t\t\t\t\tself.samples = line.strip().split('\\t')[9:]\n\t\t\t\t\tself.samples = ('|').join(self.sam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A convenience function for getting a single suggestion.
def get_suggestion(): global _suggestions_iterator while True: try: return next(_suggestions_iterator) except StopIteration: _suggestions_iterator = iter(suggestions)
[ "def suggestion(self):\n return self._suggestion", "def suggestion(self, suggestion_id):\r\n return suggestions.Suggestion(self, suggestion_id)", "def pull_suggestion(self, callback, who, arg):\n\t\t\n random_sug = self.dong.db.get_random_row('suggest')\n res = self.google_suggest(ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds game board by retrieving a sudoku puzzle preset from a sudoku dataset and then sets up the game board. Also calls a backtracking algorithm to derive a solution for the sudoku puzzle.
def build_game_board(self): # retrieves new sudoku puzzle from dataset sudoku_set = self.data.get_sudoku_set() sudoku_problem, sudoku_solution = sudoku_set[0], sudoku_set[1] # removes old game boards self.board = [] self.puzzle = [] self.alg_solution = [] ...
[ "def new_sudoku(self):\n self.sudokus = [generate()]\n self.index = 0\n self.solution = next(bruteforce(self.sudokus[0]))\n self.hints = None\n self.hinted_sudoku = None\n\n print(\"Generating new sudoku. Rating: %d/10\" % rate(self.sudokus[0]))\n if self.settings.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Requests user input for the row column and number input they would like to enter as the next entry to the Sudoku puzzle. Has some lightweight data validation through a try / except format and asks for another input attempt if invalid inputs were provided.
def request_number_input(self): try: self.print_board(self.board) row = int(input("Please enter row to add number to (0-8): ")) col = int(input("Please enter column to add number to (0-8): ")) num = int(input("Please enter number you wish to add (1-9): ")) ...
[ "def get_input(self):\n while True:\n try:\n self.rows = int(input(\"Number of rows: \"))\n while self.rows < 2 or self.rows > 30:\n self.rows = int(input(\"Please enter a number between 2 and 30: \"))\n break\n except Valu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the requested square to change is an original input for the puzzle, which cannot be changed.
def new_input_does_not_overlap_original_board(self, col, row): return self.puzzle[row][col] == 0
[ "def test_squares_equal_with_different_squares(self):\n board = Board()\n board.set_square(1, 'X')\n board.set_square(2, 'O')\n board.set_square(3, 'X')\n self.assertFalse(board.squares_equal((1, 2, 3)))", "def validSquare(self, square):\n assert(isinstance(square[0], int) an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method for retrieving game state.
def get_game_state(self): return self.game_state
[ "def get_game_state(self):\r\n return self._game_state", "def get_game_state():\n global game_state\n return game_state", "def get_game_state(self):\n return self._game_status", "def get_new_gamestate(self):", "def state_(game):\n return game.initial", "def game_state():\n da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Nethod for playing a game of sudoku. Prints out rules and instructions and asks for user inputs. If current puzzle is solved, asks player if they would like to play again and provides a new puzzle.
def play_sudoku(puzzle): print_instructions() print("For review and grading purposes purposes, here is a sample solution:") puzzle.print_board(puzzle.alg_solution) # while puzzle is not solved, continues to ask user for their next input while puzzle.get_game_state() != "Solved!": puzzle.re...
[ "def main():\n game = SudokuGame(3)\n game.print_grid()\n choice = input(\"Would you like to play the board or would you like a \"\n \"solution to be generated for you? Enter 'Play' or 'Generate' \")\n choice.lower()\n if choice == \"play\":\n while not game.is_full():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints to console a set of instructions for how to play a game of Sudoku.
def print_instructions(): print("Welcome to the game of Sudoku!") print("--------------------------------") print("The goal of the game is to fill every 'square' here with a number.") print("The rules of the game are simple:") print(" Rule No 1: You can only enter numbers 1-9 in each square.") ...
[ "def instructions():\n\t\n\tprint('''\\n\n\tToday we will play the perennial favorite game of...\\n\n\tRock! Paper!! Scissors!!!.\\n\n\tThe objective of the game is to outthink your opponent (in this case me) and defeat.\\n\n\tThe rules are very simple\\n\n\t1. Paper covers the Rock\\n\n\t2. Rock breaks the Scissor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates four plotly visualizations using the New York Times Archive API
def return_figures(): # Add New York Times API Key nyt = NYTAPI("AsjeHhqDYrePA2GMPpYoY1KAKAdG7P99") # Select Year and Month of articles data = nyt.archive_metadata( date = datetime.datetime(2020, 7, 1) ) def data_to_df(data): # Initiate list for restructured information data_list = [] ...
[ "def return_figures():\n # read the energy data\n energy_df = pd.read_csv(\"data/all_energy_statistics.csv\")\n \n color1 = 'rgb(0,153,0)'\n color2 = 'rgb(02,102,255)'\n color3 = 'rgb(255,204,153)'\n color4 = 'rgb(153,0,153)'\n \n # CHART 1 ================================================...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Since virtual steppers are virtual, we don't need pins or step sequences. We're still using delay and n_steps to resemble physical steppers.
def __init__(self, name = None, n_steps = 256, delay = 1e-3): self.fig, self.ax = plt.subplots(figsize=(3, 3)) self.n_steps = n_steps self.delay = delay self.step_size = 2 * pi / self.n_steps if name is None: self.name = 'Stepper {}'.format(VirtualStepper.count + 1) self.angle = 0.0 self.check() se...
[ "def SetStepDelay(self,delay=200): \n self.Bus.Transaction(chr(self.Address)+chr(0x43)+chr(delay))", "def fixed_steps_trajectories(self, noise=0, nt=1, ll=0.1, limit=None):\n\n print('Generating Trajectories...')\n for i in tqdm.tqdm(range(self.ntraj)):\n\n if self.hop_distr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rotate the stepper by this angle (radians unless specified) Positive angles rotate clockwise, negative angles rotate counterclockwise
def rotate_by(self, angle, degrees = False): target = angle * pi / 180 if degrees else angle if self.inv: target = -target if target > 0: n = int(target // self.step_size) + 1 for _ in range(n): self.step_c() else: n = int(-target // self.step_size) + 1 for _ in range(n): self.step_cc()...
[ "def rotateWheel(self, radians):\n pass", "def rotate(self, direction):\n electro = pygame.mixer.Sound('resources/Electro_Motor.wav')\n electro.set_volume(0.2)\n self.rotation += min(max(direction, -1), 1)\n if self.rotation >= 4:\n self.rotation = 0\n elif sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert csv into numpy
def csv_2_numpy(file, path=INPUT_PATH, sep=',', type='int8'): file_path = path + file reader = csv.reader(open(file_path, "r"), delimiter=sep) x = list(reader) dataset = numpy.array(x).astype(type) return dataset
[ "def csv_to_numpy(path, skip_header=False):\n data = [r for r in iterate_csv(path, skip_header)]\n result = np.array(data, dtype=object)\n return result", "def csv_to_numpy_list(self, src):\n\t\t# with open(src, 'r') as input:\n\t\t\t# reader = csv.reader(input, delimiter=\",\")\n\t\tdat = pd.read_csv(sr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a vocabulary mapping from word to index based on the sentences. Returns vocabulary mapping and inverse vocabulary mapping.
def build_vocab(sentences): # Build vocabulary word_counts = Counter(itertools.chain(*sentences)) # 实际没用到 # Mapping from index to word vocabulary_inv = [x[0] for x in word_counts.most_common()] vocabulary_inv = list(sorted(vocabulary_inv)) # 加入 <UNK> vocabulary_inv.insert(0, '</s>') # M...
[ "def build_vocab(self, sentences):\n\t\t# Build the vocab\n\t\tword_counts = collections.Counter(sentences)\n\n\t\t# Mapping from index to word (get the indices of most common words)\n\t\tvocab_inv = [x[0] for x in word_counts.most_common()] # Do we need this?\n\t\tvocab_inv = list(sorted(vocab_inv))\n\n\t\t# Mapp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Estimate the true signal mean and interpolate bad channels. This function implements the functionality of the `performReference` function as part of the PREP pipeline on mne raw object. Notes This function calls robust_reference first Currently this function only implements the functionality of default settings, i.e., ...
def perform_reference(self): # Phase 1: Estimate the true signal mean with robust referencing self.robust_reference() if self.noisy_channels["bad_all"]: self.raw.info["bads"] = self.noisy_channels["bad_all"] self.raw.interpolate_bads() self.reference_signal = ( ...
[ "def robust_reference(raw, reference_out, montage_kind='standard_1020'):\n raw.rename_channels(lambda s: s.strip(\".\"))\n ch_names = raw.info['ch_names']\n\n # Warn if evaluation and reference channels are not the same for robust\n if not set(reference_out['ref_chs']) == set(reference_out['eval_chs']):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detect bad channels and estimate the robust reference signal. This function implements the functionality of the `robustReference` function as part of the PREP pipeline on mne raw object.
def robust_reference(self): raw = self.raw.copy() raw._data = removeTrend(raw.get_data(), sample_rate=self.sfreq) # Determine unusable channels and remove them from the reference channels noisy_detector = NoisyChannels(raw, do_detrend=False) noisy_detector.find_all_bads(ransac=s...
[ "def robust_reference(raw, reference_out, montage_kind='standard_1020'):\n raw.rename_channels(lambda s: s.strip(\".\"))\n ch_names = raw.info['ch_names']\n\n # Warn if evaluation and reference channels are not the same for robust\n if not set(reference_out['ref_chs']) == set(reference_out['eval_chs']):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the reference signal from the original EEG signal. This function implements the functionality of the `removeReference` function as part of the PREP pipeline on mne raw object.
def remove_reference(signal, reference, index=None): if np.ndim(signal) != 2: raise ValueError( "RemoveReference: EEG signal must be 2D array (channels * times)" ) if np.ndim(reference) != 1: raise ValueError("RemoveReference: Reference signal must be ...
[ "def removeReference(self, reference: ghidra.program.model.symbol.Reference) -> None:\n ...", "def remove_reference(self):\n\n if hasattr(self, '_reference'):\n delattr(self, '_reference')", "def removeReferenceGlyph(self, *args):\n return _libsbml.GeneralGlyph_removeReferenceGly...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the buy list for the board
def setBuyList(self, buyList): parsedBuyList = [] for bought in buyList: if hasattr(bought, "unitType"): parsedBuyList.append(bought) elif isinstance(bought, dict) and u'unitType' in bought and u'territory' in bought: parsedBuyList.append(createBou...
[ "def buys(self, buys):\n\n self._buys = buys", "def set_buy_sell_deal_account(self, account_list):\n self.multiple_items_selection_from_kendo_dropdown(self.buy_sell_deal_account_dropdown_locator, account_list)\n self.wait_for_ajax_spinner_load()", "def update_buy_caps(self):\n for st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts json string in related object object_to_serialize have to be an instace of the desired to convert object
def DeserializeJson(self, json_string, object_to_serialize): object_to_serialize.__dict__ = json.loads(str(json_string)) return object_to_serialize
[ "def json_deserialize(json_object):\n raise NotImplementedError('json_deserialize must be overriden')", "def serialize(self, obj):\n return obj", "def serialize(obj):\n return serialization_manager.serialize(obj)", "def _json_to_obj(cls, serialized_str):\n json_dict = json.loads(serial...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a DVR object
def DVR( domain=None, divs=None, classes=None, potential_function=None, g=None, g_deriv=None, scf=False, potential_optimize=False, **base_opts ): return DVRConstructor.construct( domain=domain, divs=divs, classes=classe...
[ "def __init__(self, dr_ds: DatasetReader) -> None:\n super().__init__()\n\n self.dr_ds = dr_ds\n try:\n self.cmap = dr_ds.colormap(1)\n except ValueError:\n pass\n\n crs = dr_ds.crs\n res = dr_ds.res[0]\n\n with WarpedVRT(dr_ds, crs=crs) as dr:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the ``Response`` object into django's ``HttpResponse``
def _finalize_response(self, response): res = HttpResponse(content=response.content, content_type=self._get_content_type()) # status_code is set separately to allow zero res.status_code = response.code return res
[ "def to_http_response(self) -> HttpResponse:\n response = (\n JsonResponse(self.body)\n if (self.headers or {}).get(\"Content-Type\") == \"application/json\"\n else HttpResponse(self.body)\n )\n response.headers = self.headers\n return response", "def m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return ContentType header with charset info.
def _get_content_type(self): return '%s; charset=%s' % (self.content_type, self.charset)
[ "def getCharset(content):\n\treturn content.headers['content-type'].split('charset=')[-1]", "def get_ctype(self):\n ctype = self.response.getheader('Content-Type')\n\n end = 0\n try:\n end = ctype.index(';')\n mediatype = ctype[:end]\n except:\n mediaty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the manager. The ``_datamappers`` dictionary is initialized here to make testing easier.
def __init__(self): self._datamappers = { '*/*': DataMapper() }
[ "def _initialize_mappers(mappers_factory, work_dir=None):\n if work_dir is not None:\n os.chdir(work_dir) # needed for ray\n G.F_MAPPERS = Composed(mappers_factory)", "def init_dataloaders(self):\n raise NotImplementedError()", "def init(self):\n self.init_db_header()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select appropriate formatter based on the request.
def select_formatter(self, request, resource): # 1. get from resource if resource.mapper: return resource.mapper # 2. get from url mapper_name = self._get_name_from_url(request) if mapper_name: return self._get_mapper(mapper_name) # 3. get from ac...
[ "def _determine_format(self, request):\n return determine_format(request, self._meta.serializer, default_format=self._meta.default_format)", "def determine_format(request, serializer, default_format='application/json'):\r\n # First, check if they forced the format.\r\n if request.GET.get('format'):\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select appropriate parser based on the request.
def select_parser(self, request, resource): # 1. get from resource if resource.mapper: return resource.mapper # 2. get from content type mapper_name = self._get_name_from_content_type(request) if mapper_name: return self._get_mapper(mapper_name) #...
[ "def select_parser(self, request, parsers):\n return parsers[0]", "def parser(cls, type, dom):\r\n parser_class = cls.parsers.get(type)\r\n if parser_class:\r\n return parser_class(dom)", "def __find_parser__( self, input=None ):\n\n ## Check with parser name\n for name, pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returs mapper based on the content type.
def get_mapper_by_content_type(self, content_type): content_type = util.strip_charset(content_type) return self._get_mapper(content_type)
[ "def get_mapping_type(cls):\n ...", "def loadMimemapper():", "def _get_mapper(obj):\n its_a_model = isinstance(obj, type)\n mapper = class_mapper if its_a_model else object_mapper\n return mapper(obj)", "def lookup_by_content_type(self, content_type):\n return self.__by_content_type[content...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the default mapper to be used, when no format is defined. This is the same as calling ``register_mapper`` with ``/`` with the exception of giving ``None`` as parameter.
def set_default_mapper(self, mapper): mapper = mapper or DataMapper() self._datamappers['*/*'] = mapper
[ "def _get_default_mapper(self):\n\n return self._datamappers['*/*']", "def set_mapper(obj, mapper):\n setattr(obj, MAPPER, mapper)\n return mapper", "def get_default_generator(self):\n raise self.format_generator_map[self.default_format].generator_class", "def __init__(self, mapper=None):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the default mapper.
def _get_default_mapper(self): return self._datamappers['*/*']
[ "def create_mapper() -> Mapper:\n return Mapper()", "def _get_mapper(self,modelname):\r\n mapmodule = __import__('cone.carbon.mapping')\r\n return mapmodule.carbon.mapping.MAPPERS[modelname]()", "def set_default_mapper(self, mapper):\n\n mapper = mapper or DataMapper()\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the mapper based on the given name.
def _get_mapper(self, mapper_name): if mapper_name in self._datamappers: # mapper found return self._datamappers[mapper_name] else: # unsupported format return self._unknown_format(mapper_name)
[ "def get_mapper(modelname):\r\n mapmodule = __import__('cone.carbon.mapping')\r\n return mapmodule.carbon.mapping.MAPPERS[modelname]()", "def _get_mapper(self,modelname):\r\n mapmodule = __import__('cone.carbon.mapping')\r\n return mapmodule.carbon.mapping.MAPPERS[modelname]()", "def _get_ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get name from ContentType header
def _get_name_from_content_type(self, request): content_type = request.META.get('CONTENT_TYPE', None) if content_type: # remove the possible charset-encoding info return util.strip_charset(content_type) return None
[ "def _content_type__get(self):\n header = self.headers.get('Content-Type')\n if not header:\n return None\n return header.split(';', 1)[0]", "def content_type_header(request: Request) -> str:\n return request.content_type", "def get_content_type(self, headers):\n if hea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine short name for the mapper based on the URL. Short name can be either in query string (e.g. ?format=json) or as an extension to the URL (e.g. myresource.json).
def _get_name_from_url(self, request): format = request.GET.get('format', None) if not format: match = self._format_query_pattern.match(request.path) if match and match.group('format'): format = match.group('format') return format
[ "def build_url_name(cls, name, name_prefix=None):\r\n if name_prefix is None:\r\n name_prefix = 'api_{0}'.format(\r\n cls.__name__.replace('Resource', '').lower()\r\n )\r\n\r\n name_prefix = name_prefix.rstrip('_')\r\n return '_'.join([name_prefix, name])", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deal with the situation when we don't support the requested format.
def _unknown_format(self, format): raise errors.NotAcceptable('unknown data format: ' + format)
[ "def supports_format_conversion(self):\n return # boolean", "def valid_formats():\n return ('json',)", "def _determine_format(self, request):\n return determine_format(request, self._meta.serializer, default_format=self._meta.default_format)", "def GetFormatSpecification(self):\n return N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the mapper has valid signature.
def _check_mapper(self, mapper): if not hasattr(mapper, 'parse') or not callable(mapper.parse): raise ValueError('mapper must implement parse()') if not hasattr(mapper, 'format') or not callable(mapper.format): raise ValueError('mapper must implement format()')
[ "def verify_signature(self, inputs, signature):\n pass", "def _verify_signature(self):\n #FIXME\n return True", "def signature_check(dummy, *args, **kwargs):\n try:\n dummy(*args, **kwargs)\n return True\n\n except TypeError:\n return False", "def check_signatur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an airport code input after validating it
def airportCodeInput(self, prompt): while True: code = input(prompt).upper() if code not in self.travel_db.airports: print("Invalid airport code") else: return code
[ "def validateAirport(self, code):\n print(code)\n if code in self.travel_db.airports:\n return True\n else:\n return False", "def validate_arrival_airport(ctx, param, value):\n\tlocation_request = make_location_request(value) \n\n\tif location_request.status_code != 200:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a country name input after validating it
def countryInput(self, prompt): while True: name = input(prompt) if name not in self.travel_db.countries: print("Invalid country name. Please make sure name is capitalized.") else: return name
[ "def check_country_name(self):\n if (self.edit_mode):\n code_test=self.country_code\n if(not code_test ):\n self.print_log(\"Error: Country name was not found in the database.\\n\")\n return(code_test)\n else:\n front_page_variables=pre_vars['...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a currency code input after validaing it
def currencyInput(self, prompt): while True: code = input(prompt).upper() if code not in self.travel_db.currencies: print("Invalid currency code") else: return code
[ "def __set_input_currency(self):\r\n input_currency = self.__symbols_dictionary.get(self.__values.input_currency)\r\n if input_currency is None:\r\n input_currency = self.__values.input_currency\r\n return input_currency", "def getUserCurrency():", "def get_country(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if airport code valid, False otherwise.
def validateAirport(self, code): print(code) if code in self.travel_db.airports: return True else: return False
[ "def is_valid_code(self, code):\r\n if code:\r\n scheme_codes = self.get_scheme_codes()\r\n if code in scheme_codes.keys():\r\n return True\r\n else:\r\n return False\r\n else:\r\n return False", "def is_valid_code(code):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if country_name valid, False otherwise.
def validateCountry(self, country_name): if country_name in self.travel_db.countries: return True else: return False
[ "def is_name_country_code(filename: Path) -> bool:\n name = filename.stem\n\n try:\n country = countries.get(name)\n except KeyError:\n print(f\"INVALID ISO 3166-1 alpha-2 country code: {name} ({filename})\")\n return False\n\n if country.alpha2.lower() != name.lower():\n # V...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if currency_code valid, False otherwise.
def validateCurrency(self, currency_code): if currency_code in self.travel_db.currencies: return True else: return False
[ "def _is_valid_code(self, code):\r\n return code in COUNTRY_CODES", "def is_valid_code(self, code):\r\n if code:\r\n scheme_codes = self.get_scheme_codes()\r\n if code in scheme_codes.keys():\r\n return True\r\n else:\r\n return False\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dictionary of Currency objects, with key = currency code. Created from info stored in filename
def buildCurrencyDict(filename): currencies = {} with open(os.path.join("input", filename), "rt", encoding="utf8") as f: reader = csv.reader(f) for line in reader: currencies[line[1]] = Currency(line[1], line[0], float(line[2])) return currencies
[ "def currencies(self):\n currency_dict={}\n a = self.countries_file\n for i in a:\n currency_dict[i['name']]=i['currency']\n return currency_dict", "def buildCountryDict(filename, currencies_dict):\n # This function requires the currency dictionary to be built already...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dictionary of Country objects, with key = country name. Created from info stored in filename
def buildCountryDict(filename, currencies_dict): # This function requires the currency dictionary to be built already. countries = {} with open(os.path.join("input", filename), "rt", encoding="utf8") as f: reader = csv.reader(f) for line in reader: try: ...
[ "def get_iso_codes_by_continent(filename):\n fobj=open(filename, 'r', encoding=\"utf-8\") #open file\n dct={}\n \n for line in fobj: #go line by line\n line_upper=line.upper().strip(\"\\n\") #change everything in the line to upper case, remove \\n\n lst=line_upper.split(\"\\t\") #split the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dictionary of Airport objects, with key = airport code. Created from info stored in filename
def buildAirportDict(filename, countries_dict): # This function requires the country dictionary to be built already. airports = {} with open(os.path.join("input", filename), "rt", encoding="utf8") as f: reader = csv.reader(f) for line in reader: try: ...
[ "def load_airport_info(airport_file):\n with open(airport_file, 'r') as file_handle:\n for line in file_handle:\n line = line.split(',')\n name, code, latitude, longitude = line[1].strip('\"'), line[4].strip('\"'), float(line[6]), float(line[7])\n AIRPORT_LOCATIONS[code] =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of routes from a file, in the format [name, [airport code list]]. Return None if file not found.
def getRouteInputFile(filename): if filename[-4:] != ".csv": # Make sure the filename is a .csv return None routes = [] try: with open(os.path.join("input", filename), "rt", encoding="utf8") as f: reader = csv.reader(f) for line in read...
[ "def get_flight_route_from_file(self):\n returnList = []\n with open(FILENAME, 'r', encoding=\"utf8\") as csvFile:\n csvReader = csv.DictReader(csvFile, delimiter=',')\n for line in csvReader:\n returnList.append(line)\n self.__dictList = returnList\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a csv input file, given a list of routes. Routes are lists of names and airport codes.
def writeRoutesCSV(filename, routes): if filename[-4:] != ".csv": # Make sure the filename is a .csv filename += ".csv" try: with open(os.path.join("input", filename), "w", newline='') as f: writer = csv.writer(f, delimiter=",") writer.writerow...
[ "def route_data(route):\n os.chdir(\"../Data/test\") #change to whatever directory your data files are stored in\n with open(\"../Sorted Data/\"+str(route)+\"_data.csv\",\"w\",newline=\"\") as result_file: #storing resulting data in csv file in different directory\n wr=csv.writer(result_file, dialect='...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write output .csv file for list of itineraries. Output file shows cheapest route and its cost.
def writeItineraryOutput(filename, itins): if filename[-4:] != ".csv": # Make sure the filename is a .csv filename += ".csv" try: with open(os.path.join("output", filename), "w", newline='') as f: writer = csv.writer(f, delimiter=",") firstline...
[ "def get_output(self, total_costs):\n with open(f\"./data/outputfiles/chip_{self.chip_id}_net_{self.netlist_id}.csv\", 'w') as file:\n \n # This other output file can be used for the check50\n # with open('./data/outputfiles/output.csv', 'w') as file:\n output = writer(file)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an input file with randomly generated routes for num_people.
def generateRandomInput(filename, num_people, travel_db): import random routes = [] for i in range(num_people): route = travel_db.randomRoute() route.insert(0,"Person " + str(i)) # Add a name for each route. routes.append(route) if FileHandler.writeRo...
[ "def generer(nombre, distance):\n with open(\"test/{}.pts\".format(nombre), \"w\") as file:\n file.write(\"{}\\n\".format(distance))\n for _ in range(nombre):\n point = random(), random()\n file.write(\"{}, {}\\n\".format(point[0], point[1]))\n file.close()", "def gen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests API call to fetch multiple NS descriptor resources
def test_get_ns_descriptors(get_ns_descriptors_keys): sonata_nsd = SONATAClient.Nsd(HOST_URL) sonata_auth = SONATAClient.Auth(HOST_URL) _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD)) _token = json.loads(_token["data"]) response = json.loads(sonata_nsd.get_ns_descr...
[ "def get_many_descriptors(self, uuids):", "def test_get_list(self):\n for dataset_attr in self.dataset_attrs:\n self.datasets.append(create_external_dataset(**dataset_attr))\n self.story.datasets.add(self.datasets[0], self.datasets[1])\n self.story.save()\n self.assertEqual(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests API call to read information about an NS descriptor resources
def test_get_ns_descriptors_nsdinfoid(): sonata_nsd = SONATAClient.Nsd(HOST_URL) sonata_auth = SONATAClient.Auth(HOST_URL) _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD)) _token = json.loads(_token["data"]) _nsd_list = json.loads(sonata_nsd.get_ns_descriptors( ...
[ "def test_get_ns_descriptors(get_ns_descriptors_keys):\r\n sonata_nsd = SONATAClient.Nsd(HOST_URL)\r\n sonata_auth = SONATAClient.Auth(HOST_URL)\r\n _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD))\r\n _token = json.loads(_token[\"data\"])\r\n\r\n response = json.loads(sona...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests API call to delete NS descriptor resources
def test_delete_ns_descriptors_nsdinfoid(delete_ns_descriptors_nsdinfoid_keys): sonata_vnfpkgm = SONATAClient.VnfPkgm(HOST_URL) sonata_nsd = SONATAClient.Nsd(HOST_URL) sonata_auth = SONATAClient.Auth(HOST_URL) _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD)) _token = ...
[ "def test_delete_descritors(self, nsd_proxy, vnfd_proxy):\n nsds = nsd_proxy.get(\"/rw-project:project[rw-project:name='default']/nsd-catalog/nsd\", list_obj=True)\n for nsd in nsds.nsd:\n xpath = \"/rw-project:project[rw-project:name='default']/nsd-catalog/nsd[id={}]\".format(quoted_key(ns...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns halo (row of data) given a ``nodeIndex``
def get_halo(self, index): try: halo = self.data.loc[index] except KeyError: raise IndexError( "Halo id %d not found in %s" % (index, self.filename) ) return halo
[ "def halo_host(self, index):\n halo = self.get_halo(index)\n return (\n halo\n if halo.name == halo[\"hostIndex\"]\n else self.halo_host(self.get_halo(halo[\"hostIndex\"]).name)\n )", "def __get_node_by_index(root, index):\n if isinstance(root, TreePlan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds indices of all progenitors of a halo, recursively.
def halo_progenitor_ids(self, index): _progenitors = [] def rec(i): _progenitor_ids = self.data[self.data["descendantHost"] == i][ "hostIndex" ].unique() logging.debug("Progenitors recursion: %d > %d (%d progenitors)", index...
[ "def halo_progenitor_ids(self, index):\n _progenitors = []\n\n def rec(i):\n _progenitor_ids = self.data[self.data[\"descendantHost\"] == i][\n \"hostIndex\"\n ].unique()\n logging.debug(\n \"Progenitors recursion: %d > %d (%d progenitors)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds host of halo. Recursively continues until hits the main halo, in case of multiply embedded subhaloes.
def halo_host(self, index): halo = self.get_halo(index) return ( halo if halo.name == halo["hostIndex"] else self.halo_host(self.get_halo(halo["hostIndex"]).name) )
[ "def extract_halos( bricks, grid, halo_type, sides='all' ):\n assert grid.halo_shape.any(), \"Grid has no halo!\"\n assert halo_type in ('outer', 'inner')\n assert sides in ('lower', 'upper', 'all')\n\n def zero_fill(vol, box, full_box):\n \"\"\"\n Given a volume, it's corresponding box, a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds mass of central halo and all subhaloes.
def halo_mass(self, index): return self.data[self.data["hostIndex"] == index][ "particleNumber" ].sum()
[ "def get_halfmass_radius(halo):\n # generate a profile for the halo's stellar particles\n with pynbody.analysis.halo.center(halo, mode=\"pot\"):\n p = pynbody.analysis.profile.Profile(halo.s, nbins=1000, ndim=2)\n\n M_star = sum(halo.s[\"mass\"])\n\n # Find the radius at which half the stellar ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates mass assembly history for a given halo. Treebased approach has been abandoned for performace reasons.
def collapsed_mass_history(self, index, nfw_f): logging.debug("Looking for halo %d", index) halo = self.get_halo(index) if halo["hostIndex"] != halo.name: raise ValueError("Not a host halo!") m_0 = self.halo_mass(index) progenitors = pd.concat( [ ...
[ "def collapsed_mass_history(self, index, nfw_f):\n\n logging.debug(\"Looking for halo %d\", index)\n halo = self.get_halo(index)\n if halo[\"hostIndex\"] != halo.name:\n raise ValueError(\"Not a host halo!\")\n m_0 = self.halo_mass(index)\n\n progenitors = pd.concat(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Number of progenitors at one given snapshot z1
def find_progenitors_at_z(self, SH, mtree, z1, z2): for ss in range(z1, z2): # nodes at redshift ss ss_indx = np.where(mtree.data.snapshotNumber.values == ss) nodeID = mtree.data.index.values[ss_indx] nodeID_desc = mtree.data.descendantIndex.values[ss_ind...
[ "def num_pauses(self):\r\n objects = self.__get_objects()\r\n z1 = str(objects[1]).strip().split()\r\n return int(z1[1])", "def count_gates(qobj, basis, qubits):\n\n #TO DO\n pass", "def get_num_photo1(self):\n return self.photo1.get_num_photo()", "def count(self,val):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule WB category export on Scrapinghub.
def category_export(url: str, chat_id: int, spider='wb', priority=2) -> str: logger.info(f'Export {url} for chat #{chat_id}') client, project = init_scrapinghub() scheduled_jobs = scheduled_jobs_count(project, spider) max_scheduled_jobs = env('SCHEDULED_JOBS_THRESHOLD', cast=int, default=1) if pri...
[ "def _download_categories_csv(self, filename):\n\n # Login if necessary.\n self._login()\n\n # Log time consuming step.\n LOGGER.info(\"Downloading categories\")\n\n # Load the export page.\n url = (\n self._admin_url +\n \"?m=ajax_export&instance=cate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Train a simple conv net img_h = sentence length (padded where necessary) img_w = word vector length (300 for word2vec) filter_hs = filter window sizes hidden_units = [x,y] x is the number of feature maps (per filter window), and y is the penultimate layer sqr_norm_lim = s^2 in the paper lr_decay = adadelta decay parame...
def train_conv_net(datasets,datasets_weights, U, U_Topical, img_w=300, filter_hs=[3,4,5], hidden_units=[100,2], dropout_rate=[0.5], shuffle_batch=True, n_epochs=25, ...
[ "def train(self, x_train, y_train, w2v_size=300, w2v_window=5, w2v_min_count=1,\n w2v_epochs=100, k_max_sequence_len=500, k_batch_size=128, k_epochs=32, k_lstm_neurons=128,\n k_hidden_layer_neurons=(128, 64, 32), verbose=1):\n # Set variables\n self.w2v_size = w2v_size\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the absolute path to a valid plugins.cfg file. Copied from sf_OIS.py
def getPluginPath(): import sys import os import os.path paths = [os.path.join(os.getcwd(), 'plugins.cfg'), '/etc/OGRE/plugins.cfg', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'plugins.cfg')] for path in paths: ...
[ "def get_plugin_dir(self, f): # f should be __file__\n d = f.split(os.sep)[-2]\n return os.path.abspath( os.path.join(\"plugins\", d) )", "def get_config_file_location():\n\n return './' + CONFIG_FILE_NAME", "def config_file_and_path():\n return str(rmfriend_dir() / 'config.cfg')", "def config_pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This shows the config dialog and returns the renderWindow.
def configure(ogre_root): user_confirmation = ogre_root.showConfigDialog() if user_confirmation: return ogre_root.initialise(True, "OGRE Render Window") else: return None
[ "def get_config_dialog(self):", "def on_config(self, e):\n self.config_window = configwindow.ConfigWindow(self)\n self.config_window.Show()", "def config_show():\n Config().show()", "def openRocConfig(self):\n self.rocConfig_Window = QtWidgets.QDialog()\n self.rocConfig_ui = Ui_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a DICOM file, raising an exception if the 'DICM' marker is not present at byte 128. dicom.read_file() does this as of pydicom 0.9.5.
def read_dicom_file(fname): fo = open(fname) try: preamble = fo.read(128) magic = fo.read(4) if len(preamble) != 128 or magic != 'DICM': raise InvalidDicomError fo.seek(0) do = dicom.read_file(fo) finally: fo.close() return do
[ "def dicom_read(dicom_path):", "def dcmread(dcm_file, force = False) :\n try:\n ds = pydicom.read_file(dcm_file)\n except pydicom.filereader.InvalidDicomError as e:\n if self.options.force:\n ds = pydicom.read_file(dcm_file, force = force)\n else:\n raise pydicom.filereader.InvalidDicomError(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given our dicom_files and studies records and a patient ID, return a list of (datetime, study instance UID) ordered by date+time
def patient_studies(dicom_files, studies, patient_id): ps = [] for uid in dicom_files[patient_id]: datetime = '%s%s' % studies[uid] ps.append([datetime, uid]) ps.sort(lambda a, b: cmp(a[0], b[0])) for el in ps: date_time_parts = (el[0][0:4], el[0][4:6]...
[ "def get_samples_from_patient_id(patient_id):\n all_files = FileRepository.all()\n q_pid = Q(metadata__cmoPatientId=patient_id)\n q_fg = build_argos_file_groups_query()\n q = q_pid & q_fg\n files = FileRepository.filter(queryset=all_files, q=q, filter_redact=True)\n data = list()\n for current_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a project/subject/session identifier is valid. Identifiers can only contain alphanumeric characters and underscores.
def _validate_identifier(self, identifier): for c in identifier: if c not in string.letters + string.digits + '_': return False return True
[ "def IsProjectIDValid(project):\n if len(project) < 6 or len(project) > 30:\n return False\n return bool(re.match('^[a-z][a-z0-9\\\\-]*[a-z0-9]$', project))", "def check_valid_identifier(identifier):\n return bool(re.match(\"[_A-Za-z][_a-zA-Z0-9]*$\", identifier))", "def is_valid_id(id_):\n if not re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalizes USD price with thousand separator into float value
def normalize_price(price: str) -> float: return float(price.strip().replace(',', ''))
[ "def get_price(str_val):\n return float(str_val.replace('.', '').replace(',', '.'))", "def price_str_to_float(tkt_item):\n try:\n tkt_item[10] = float(tkt_item[10].replace(',', '.'))\n except:\n tkt_item[10] = 0\n\n return tkt_item", "def convert(price_usd) :\n\tprice_eur = price_usd /...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the csv file CSV file should contain ['Question', 'Answer'] columns Remove NaN values Throw error if format is bad or file does not exist
def parse_csv_file(self, csv_file: str): try: df = pd.read_csv(csv_file) if not set(['Question', 'Answer']).issubset(df.columns): raise BadCSVFile( "CSV file does not contain ['Question', 'Answer'] columns.") df.dropna(inplace=True) ...
[ "def custom_read_csv(self):\n # read csv file into 'data' data frame\n # strip data of leading or tailing whitespaces\n df = pd.read_csv(self.path, skipinitialspace=True)\n # drop \"fnlwgt\" column\n df.drop(columns=\"fnlwgt\", inplace=True)\n # replace all \"?\" with NaN\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a vector for a given query
def get_vector(self, query: list): if len(query) == 0: raise BadQueryParameter("Query (list) can not be empty.") return self.vectorizer.transform(query)
[ "def get_vector_for_query(self, query: Query) -> np.ndarray:\n return self._vectorizer.transform([query.text])", "def _to_full_vector(self, query_vector: List[Tuple[str, float]]) -> np.array:\n terms = list(self.index.get_terms())\n terms.sort()\n vector = np.zeros(len(terms))\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Groups data in SimulationReport's by the value of alpha or gamma2
def group_data(simulation_reports: List[SimulationReport]) -> Dict[float, SimulationTable]: heat_maps: OrderedDict[float, SimulationTable] = OrderedDict() for report in simulation_reports: if report.param not in heat_maps: param_name = "alpha" if report.growth_type == GrowthType.Polynomial e...
[ "def alpha_stats (alphas, groups, significant = 0.05):\n\t\n\tK = alphas.shape[1]\n\tgroup1 = np.array(groups)\n\tgroup2 = ~ group1\n\n\t#T-test\n\ta = alphas[group1 ] \n\tb = alphas[group2]\n\n\t#T-test\n\ttt,p_tt = ttest_ind (a,b)\n\t# Mann Whitney Test\n\tmw = []\n\tp_mw =[]\n\tfor i in range (K):\n\t\t m,p =man...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Abstract method invoked when a trial is completed or terminated. Do nothing by default.
def trial_end(self, parameter_id, success, **kwargs):
[ "def on_trial_complete(self, trial_runner, trial, result):\n\n raise NotImplementedError", "def on_trial_complete(self, trial: Trial, result: Dict[str, Any]):\n pass", "def trial(self):\n pass", "def trial_clean_up(self):\n pass", "def on_trial_result(self, trial_runner, trial, r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }