query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
Build a full for PMS.
def url(self, path): if self.token: delim = '&' if '?' in path else '?' return '%s%s%sX-Plex-Token=%s' % (self.baseurl, path, delim, self.token) return '%s%s' % (self.baseurl, path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build():", "def build(_):", "def build(self) -> None:", "def _build(self):", "def _build(self):", "def build(self):\n pass", "def build(self):\n pass", "def __init__(self, full=False):\n self.full = full", "def build(root):", "def build(self):", "def build(self):", "d...
[ "0.64432496", "0.5995165", "0.5785159", "0.56959456", "0.56959456", "0.5673759", "0.5673759", "0.55980897", "0.5589734", "0.5580928", "0.5580928", "0.5580928", "0.548814", "0.54823315", "0.5479324", "0.54228485", "0.5419625", "0.5403888", "0.5380733", "0.5379059", "0.5359603"...
0.0
-1
Update the use of a cache.
def _update_use(self, key): if (self._replace_pol == Cache.LRU): self.cache[key]= self.hashmap[key] if (self._replace_pol == Cache.LRU_S): self.cache[key] = self.hashmap[key]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_cache(self, val):\n pass", "def update(self, cache_key):\r\n self._write_sha(cache_key)", "def set_to_cache(self, url, data):\n cache_key, cache_lookup = self.get_cacheable_info(url)\n MEM_CACHE[cache_key][cache_lookup] = (data, time.time())", "def do_api_calls_update_cache(se...
[ "0.70355237", "0.67454726", "0.66589284", "0.66395354", "0.6594092", "0.658877", "0.655342", "0.63988495", "0.63722324", "0.63371176", "0.6319258", "0.6313111", "0.6270669", "0.62608325", "0.623213", "0.6211307", "0.6194371", "0.61508423", "0.61492276", "0.61486644", "0.61116...
0.7350366
0
Return the name, arguments, and return type of the first function definition found in code. Arguments are returned as [(type, name), ...].
def parse_function_signature(code): m = re.search("^\s*" + re_func_decl + "\s*{", code, re.M) if m is None: print(code) raise Exception("Failed to parse function signature. " "Full code is printed above.") rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] else: args = [tuple(arg.strip().split(' ')) for arg in args.split(',')] return name, args, rtype
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_functions(code):\n regex = \"^\\s*\" + re_func_decl + \"\\s*{\"\n \n funcs = []\n while True:\n m = re.search(regex, code, re.M)\n if m is None:\n return funcs\n \n rtype, name, args = m.groups()[:3]\n if args == 'void' or args.strip() == '':\n ...
[ "0.68184936", "0.66357005", "0.6627714", "0.6380974", "0.634481", "0.6164433", "0.59679073", "0.5878357", "0.58456427", "0.58147675", "0.57996273", "0.5772736", "0.57490474", "0.57399726", "0.56921184", "0.56889397", "0.56479543", "0.56471384", "0.5646925", "0.55967027", "0.5...
0.6752605
1
Return a list of (name, arguments, return type) for all function definition2 found in code. Arguments are returned as [(type, name), ...].
def find_functions(code): regex = "^\s*" + re_func_decl + "\s*{" funcs = [] while True: m = re.search(regex, code, re.M) if m is None: return funcs rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] else: args = [tuple(arg.strip().split(' ')) for arg in args.split(',')] funcs.append((name, args, rtype)) code = code[m.end():]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_prototypes(code):\n\n prots = []\n lines = code.split('\\n')\n for line in lines:\n m = re.match(\"\\s*\" + re_func_prot, line)\n if m is not None:\n rtype, name, args = m.groups()[:3]\n if args == 'void' or args.strip() == '':\n args = []\n ...
[ "0.6066096", "0.6015459", "0.5959938", "0.59203005", "0.583354", "0.56550306", "0.56340224", "0.5607439", "0.557955", "0.554569", "0.5541941", "0.5537403", "0.5534576", "0.5530362", "0.5520808", "0.5512901", "0.54985154", "0.5478151", "0.54779917", "0.54722935", "0.5433578", ...
0.6613337
0
Return a list of signatures for each function prototype declared in code. Format is [(name, [args], rtype), ...].
def find_prototypes(code): prots = [] lines = code.split('\n') for line in lines: m = re.match("\s*" + re_func_prot, line) if m is not None: rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] else: args = [tuple(arg.strip().split(' ')) for arg in args.split(',')] prots.append((name, args, rtype)) return prots
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_functions(code):\n regex = \"^\\s*\" + re_func_decl + \"\\s*{\"\n \n funcs = []\n while True:\n m = re.search(regex, code, re.M)\n if m is None:\n return funcs\n \n rtype, name, args = m.groups()[:3]\n if args == 'void' or args.strip() == '':\n ...
[ "0.6960925", "0.6853837", "0.6183662", "0.6137309", "0.61293304", "0.585127", "0.58011335", "0.5792403", "0.5768999", "0.5726607", "0.571727", "0.5692678", "0.56545895", "0.5620403", "0.55659837", "0.5563249", "0.55443704", "0.5544288", "0.5539026", "0.55336374", "0.55096585"...
0.76626337
0
Return a list of template variables found in code.
def find_template_variables(code): return re.findall(re_template_var, code)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def vars(cls):\n for key in dir(cls):\n if key.startswith('var_'):\n yield key[4:]", "def variables(self):\n return {u for u in self if u.type == 'var'}", "def variables_referenced(text):\n return set(substitution_pattern.findall(text))", "def variables(self):\r\n ...
[ "0.66962886", "0.65876555", "0.6326123", "0.6295308", "0.62385863", "0.62311065", "0.62209594", "0.6211561", "0.61806494", "0.61253965", "0.61250657", "0.6060957", "0.6031869", "0.6000928", "0.59701294", "0.5965443", "0.5964786", "0.5951391", "0.59493124", "0.592245", "0.5907...
0.8810326
0
Returns a function for generating trials for a model op. Infers the Python main module for the operation and returns the `gen_trials` function defined for that module. Raise `TypeError` if the operation does not use a Python main module (either explicitly with the `main` attribute or implicitly in the `exec` attribute.
def optimizer_trial_generator(model, op_name): try: module_name = _model_op_main(model, op_name) except ValueError as e: raise TypeError( f"could not get main module for {model.name}{op_name}: {e}" ) from None else: try: main_mod = importlib.import_module(module_name) except ImportError: raise TypeError( f"could not import main module {module_name} for " f"{model.name}:{op_name}" ) from None else: try: return main_mod.gen_trials except AttributeError: raise TypeError( f"{main_mod.__name__} optimizer module does not " "implement gen_trials" ) from None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_test_routine(\n self,\n ) -> Callable[\n [\n torch.utils.data.Dataset,\n argparse.Namespace,\n torch.nn.Module,\n Progress,\n TaskID,\n ],\n Tuple[Dict[str, float], pd.DataFrame],\n ]:\n pass", "def main(_):\n...
[ "0.52469647", "0.50867206", "0.49812433", "0.49300626", "0.48819524", "0.48743096", "0.48729882", "0.48613867", "0.4854776", "0.48491868", "0.48481944", "0.48190248", "0.48174357", "0.47987285", "0.47749686", "0.47592515", "0.47589567", "0.47463167", "0.4741073", "0.4720266", ...
0.75061655
0
Looks for main module in exec spec for model op. Raises `ValueError` if exec spec is empty or not in the exepcted format.
def _op_main_for_exec(exec_): if not exec_: raise ValueError("exec spec not specified") m = re.search(r"-u?m ([^ ]+)", exec_) if not m: raise ValueError(f"unexpected exec spec: {exec_!r}") return m.group(1)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _find_module(model, mod_name):\n for name, module in model.named_modules():\n if name == mod_name:\n return module\n return None", "def search_executable(op, description = None):\n checked = []\n ret = None\n if isinstance(op, (list, tuple)):\n for ii in op:\n if not ii in ...
[ "0.53562915", "0.53267694", "0.5284103", "0.5240484", "0.51123273", "0.50640464", "0.5061494", "0.50039196", "0.4992714", "0.4973761", "0.49309054", "0.49113435", "0.49091592", "0.49087858", "0.49011794", "0.48769084", "0.4876754", "0.48592058", "0.48583668", "0.48241246", "0...
0.6107568
0
Whether the user can view the app.
def is_visible_to(self, user): return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def can_view(self, user):\r\n return True", "def can_view(self, user):\n if self.applicant == user:\n return True\n elif user.has_perm('funding.view_all_applications'):\n # Fundihg commitee\n return True\n elif user.has_perm('funding.make_application_d...
[ "0.79821163", "0.7801342", "0.7659866", "0.7364578", "0.72992426", "0.72992426", "0.72992426", "0.7284491", "0.726636", "0.7259897", "0.7252951", "0.72216725", "0.7215882", "0.72110295", "0.71833014", "0.7176226", "0.7165583", "0.7093514", "0.7021715", "0.7016737", "0.6983384...
0.66767985
34
Apps should provide their entries to be added to the main nav
def main_menu(self): return self.sitemap
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main_menu(self):\n return [SitemapEntry(self.config.options.mount_label.title(), '.')]", "def main_menu(self):\n return [SitemapEntry(self.config.options.mount_label.title(), '.')]", "def get_app_menu(self): # real signature unknown; restored from __doc__\n pass", "def top_menu_items...
[ "0.6041133", "0.6041133", "0.59611654", "0.58503586", "0.5769742", "0.57452404", "0.5667387", "0.5649428", "0.55988616", "0.5581878", "0.5566973", "0.55109316", "0.5496839", "0.5493429", "0.54604423", "0.5444736", "0.54136664", "0.5399929", "0.5395823", "0.53948635", "0.53865...
0.582685
4
Returns the list of Packages available in the current folder
def getPackages(self): cat = getToolByName(self.context, 'portal_catalog') ideeSejour = getattr(self.context, 'idee-sejour') url = '/'.join(ideeSejour.getPhysicalPath()) contentFilter = {} path = {} path['query'] = url path['depth'] = 1 contentFilter['path'] = path contentFilter['portal_type'] = ['Package'] contentFilter['sort_on'] = 'effective' contentFilter['sort_order'] = 'reverse' results = cat.queryCatalog(contentFilter) results = list(results) return results
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def list_packages():\n\n shelf_dir = settings.shelf_dir\n\n package_list = os.listdir(shelf_dir)\n\n package_list.sort()\n\n return package_list", "def packages(self):\n return []", "def get_packages_in_current_dir() -> list:\n from os import listdir\n\n pkgs = []\n ext = ('.tgz', '...
[ "0.77415687", "0.7680992", "0.7671494", "0.7380899", "0.73055834", "0.7287107", "0.720107", "0.71151006", "0.70794725", "0.7072952", "0.70491385", "0.70418817", "0.70418817", "0.70418817", "0.69878227", "0.6978179", "0.696851", "0.69578356", "0.6949087", "0.69228244", "0.6912...
0.6942359
19
Return a vignette for the package
def getVignette(self, packageUrl): cat = getToolByName(self.context, 'portal_catalog') results = cat.searchResults(portal_type='Vignette', path={'query': packageUrl}) if results: return results[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def for_slug(slug):\n vig = Vignette.objects.filter(slug=slug).first()\n if not vig:\n vig = Vignette(slug=slug, content=json.dumps({'data': [\n {'type': 'text', 'data': {\n 'text': 'Missing Vignette `' + slug + '`'}}]}))\n return vig", "def _prov...
[ "0.6036985", "0.53940934", "0.5330004", "0.530821", "0.52660775", "0.5136677", "0.5044925", "0.5041591", "0.5003167", "0.49641988", "0.49498764", "0.49451274", "0.48880824", "0.48761797", "0.48731172", "0.4868222", "0.48601785", "0.48379087", "0.48331505", "0.48277253", "0.48...
0.7263297
0
This function creates a new hdf5 file in the active directory taking as the sole argument a string name for the file.
def new_hdf5(new_filename): # handling input errors if not isinstance(new_filename, str): raise TypeError('Passed value of `filename` is not a string! Instead, it is: ' + str(type(new_filename))) # w- mode will create a file and fail if the file already exists hdf5 = h5py.File('{}.hdf5'.format(new_filename), 'w-') hdf5.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _create_file(self, filepath):\n folder, _filename = os.path.split(filepath)\n if not os.path.isdir(folder):\n os.makedirs(folder)\n file = h5py.File(filepath, 'a')\n return file", "def save_as_hdf5(self, filename):", "def hdf5_file(self):\n if self._hdf5_file i...
[ "0.7140792", "0.6980622", "0.68066597", "0.6773389", "0.6753648", "0.6693808", "0.65225184", "0.6473293", "0.6460949", "0.63484126", "0.6270696", "0.6265804", "0.62491304", "0.62026066", "0.61233056", "0.6107673", "0.6106745", "0.6065954", "0.60572034", "0.60490173", "0.60163...
0.740254
0
This function adds Raman calibration data to an existing hdf5 file. It uses the spectrafit.fit_data function to fit the data before saving the fit result and the raw data to the hdf5 file.
def add_calibration(hdf5_filename, data_filename, label=None): # handling input errors if not isinstance(hdf5_filename, str): raise TypeError('Passed value of `cal_filename` is not a string! Instead, it is: ' + str(type(hdf5_filename))) if not hdf5_filename.split('/')[-1].split('.')[-1] == 'hdf5': raise TypeError('`cal_filename` is not type = .hdf5! Instead, it is: ' + hdf5_filename.split('/')[-1].split('.')[-1]) if not isinstance(data_filename, str): raise TypeError('Passed value of `data_filename` is not a string! Instead, it is: ' + str(type(data_filename))) # r+ is read/write mode and will fail if the file does not exist cal_file = h5py.File(hdf5_filename, 'r+') if data_filename.split('.')[-1] == 'xlsx': data = pd.read_excel(data_filename, header=None, names=('wavenumber', 'counts')) elif data_filename.split('.')[-1] == 'csv': data = pd.read_csv(data_filename, header=None, names=('wavenumber', 'counts')) else: print('data file type not recognized') # ensure that the data is listed from smallest wavenumber first if data['wavenumber'][:1].values > data['wavenumber'][-1:].values: data = data.iloc[::-1] data.reset_index(inplace=True, drop=True) else: pass # peak detection and data fitting fit_result, residuals = spectrafit.fit_data(data['wavenumber'].values, data['counts'].values) # write data to .hdf5 using custom label if provided if label is not None: cal_file['{}/wavenumber'.format(label)] = data['wavenumber'] cal_file['{}/counts'.format(label)] = data['counts'] cal_file['{}/residuals'.format(label)] = residuals for i, result in enumerate(fit_result): # create custom datatype my_datatype = np.dtype([('fraction', np.float), ('center', np.float), ('sigma', np.float), ('amplitude', np.float), ('fwhm', np.float), ('height', np.float), ('area under the curve', np.float)]) if i < 9: dataset = cal_file.create_dataset('{}/Peak_0{}'.format(label, i+1), (1,), dtype=my_datatype) else: dataset = cal_file.create_dataset('{}/Peak_0{}'.format(label, i+1), (1,), dtype=my_datatype) # apply data to tuple data = tuple(result[:7]) data_array = np.array(data, dtype=my_datatype) # write new values to the blank dataset dataset[...] = data_array else: label = (data_filename.split('/')[-1]).split('.')[0] cal_file['{}/wavenumber'.format(label)] = data['wavenumber'] cal_file['{}/counts'.format(label)] = data['counts'] cal_file['{}/residuals'.format(label)] = residuals for i, result in enumerate(fit_result): # create custom datatype my_datatype = np.dtype([('fraction', np.float), ('center', np.float), ('sigma', np.float), ('amplitude', np.float), ('fwhm', np.float), ('height', np.float), ('area under the curve', np.float)]) if i < 9: dataset = cal_file.create_dataset('{}/Peak_0{}'.format(label, i+1), (1,), dtype=my_datatype) else: dataset = cal_file.create_dataset('{}/Peak_{}'.format(label, i+1), (1,), dtype=my_datatype) # apply data to tuple data = tuple(result[:7]) data_array = np.array(data, dtype=my_datatype) # write new values to the blank dataset dataset[...] = data_array print("""Data from {} fit with compound pseudo-Voigt model. Results saved to {}.""".format(data_filename, hdf5_filename)) cal_file.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def write(self,data): \n \n if not os.path.exists(self.output_dir):\n os.makedirs(self.output_dir)\n\n # We will store these in a separate file and link them to the level2s\n fname = data.filename.split('/')[-1]\n units = {'A':'K','x0':'degrees','y0':'degrees','...
[ "0.62519884", "0.6020593", "0.57739514", "0.5635872", "0.5571112", "0.543021", "0.5419918", "0.54129684", "0.5387982", "0.53669906", "0.53284085", "0.53150004", "0.5314605", "0.53093696", "0.530017", "0.5263094", "0.52598375", "0.5245885", "0.5220459", "0.5217278", "0.5214079...
0.6727075
0
This function adds Raman experimental data to an existing hdf5 file. It uses the spectrafit.fit_data function to fit the data before saving the fit result and the raw data to the hdf5 file. The data_filename must be in a standardized format to interact properly with this function. It must take the form anyname_temp_time.xlsx (or .csv) since this function will parse the the temp and time from the filename to label the data and fit result in the hdf5 file.
def add_experiment(hdf5_filename, exp_filename): # handling input errors if not isinstance(hdf5_filename, str): raise TypeError('Passed value of `hdf5_filename` is not a string! Instead, it is: ' + str(type(hdf5_filename))) if not hdf5_filename.split('/')[-1].split('.')[-1] == 'hdf5': raise TypeError('`hdf5_filename` is not type = .hdf5! Instead, it is: ' + hdf5_filename.split('/')[-1].split('.')[-1]) if not isinstance(exp_filename, str): raise TypeError('Passed value of `data_filename` is not a string! Instead, it is: ' + str(type(exp_filename))) # confirm exp_filename is correct format (can handle additional decimals in exp_filename label = '.'.join(exp_filename.split('/')[-1].split('.')[:-1]) if len(label.split('_')) < 2: raise ValueError("""Passed value of `exp_filename` inapproprate. exp_filename must contain at least one '_', preferably of the format somename_temp_time.xlsx (or .csv)""") # r+ is read/write mode and will fail if the file does not exist exp_file = h5py.File(hdf5_filename, 'r+') if exp_filename.split('.')[-1] == 'xlsx': data = pd.read_excel(exp_filename, header=None, names=('wavenumber', 'counts')) elif exp_filename.split('.')[-1] == 'csv': data = pd.read_csv(exp_filename, header=None, names=('wavenumber', 'counts')) else: print('data file type not recognized') # ensure that the data is listed from smallest wavenumber first if data['wavenumber'][:1].values > data['wavenumber'][-1:].values: data = data.iloc[::-1] data.reset_index(inplace=True, drop=True) else: pass # peak detection and data fitting fit_result, residuals = spectrafit.fit_data(data['wavenumber'].values, data['counts'].values) # extract experimental parameters from filename specs = exp_filename.split('/')[-1].split('.')[-2] if len(specs) > 1: spec = '' for _, element in enumerate(specs): spec = str(spec+element) specs = spec specs = specs.split('_') time = specs[-1] temp = specs[-2] # write data to .hdf5 exp_file['{}/{}/wavenumber'.format(temp, time)] = data['wavenumber'] exp_file['{}/{}/counts'.format(temp, time)] = data['counts'] exp_file['{}/{}/residuals'.format(temp, time)] = residuals for i, result in enumerate(fit_result): # create custom datatype my_datatype = np.dtype([('fraction', np.float), ('center', np.float), ('sigma', np.float), ('amplitude', np.float), ('fwhm', np.float), ('height', np.float), ('area under the curve', np.float)]) if i < 9: dataset = exp_file.create_dataset('{}/{}/Peak_0{}'.format(temp, time, i+1), (1,), dtype=my_datatype) else: dataset = exp_file.create_dataset('{}/{}/Peak_{}'.format(temp, time, i+1), (1,), dtype=my_datatype) # apply data to tuple data = tuple(result[:7]) data_array = np.array(data, dtype=my_datatype) # write new values to the blank dataset dataset[...] = data_array print("""Data from {} fit with compound pseudo-Voigt model. Results saved to {}.""".format(exp_filename, hdf5_filename)) exp_file.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_calibration(hdf5_filename, data_filename, label=None):\n # handling input errors\n if not isinstance(hdf5_filename, str):\n raise TypeError('Passed value of `cal_filename` is not a string! Instead, it is: '\n + str(type(hdf5_filename)))\n if not hdf5_filename.split('/...
[ "0.62783426", "0.54187465", "0.52853376", "0.52826935", "0.5281087", "0.5270762", "0.52683157", "0.5252653", "0.52074903", "0.51874214", "0.5176318", "0.5172828", "0.51372814", "0.5134237", "0.51305115", "0.5124579", "0.511208", "0.5110209", "0.5110135", "0.5080256", "0.50620...
0.7044707
0
Function that allows the user to manually add or remove peaks from the automatic spectra fitting by inputing an add_list and/or a drop_list. The function pulls some data from the existing fit and overwrites it with the new results.
def adjust_peaks(hdf5_file, key, add_list=None, drop_list=None, plot_fits=False): # handling input errors if not isinstance(hdf5_file, str): raise TypeError('Passed value of `hdf5_file` is not a string! Instead, it is: ' + str(type(hdf5_file))) if not hdf5_file.split('/')[-1].split('.')[-1] == 'hdf5': raise TypeError('`hdf5_file` is not type = .hdf5! Instead, it is: ' + hdf5_file.split('/')[-1].split('.')[-1]) if not isinstance(key, str): raise TypeError('Passed value of `key` is not a string! Instead, it is: ' + str(type(key))) if add_list is None: pass else: if not isinstance(add_list, list): raise TypeError('Passed value of `add_list` is not a list! Instead, it is: ' + str(type(add_list))) if drop_list is None: pass else: if not isinstance(drop_list, list): raise TypeError('Passed value of `drop_list` is not a list! Instead, it is: ' + str(type(drop_list))) if not isinstance(plot_fits, bool): raise TypeError('Passed value of `plot_fits` is not a boolean! Instead, it is: ' + str(type(plot_fits))) hdf5 = h5py.File(hdf5_file, 'r+') # extract raw x-y data x_data = np.asarray(hdf5['{}/{}'.format(key, 'wavenumber')]) y_data = np.asarray(hdf5['{}/{}'.format(key, 'counts')]) # extract peak center and height locations from hdf5 peaks = [] for _, peak in enumerate(list(hdf5[key])[:-3]): peaks.append(list(hdf5['{}/{}'.format(key, peak)][0])) # drop desired tuples from peaks if drop_list is not None: drop_index = [] for _, name in enumerate(drop_list): drop_index.append(int(name.split('_')[-1])-1) for i, index in enumerate(drop_index): peaks.pop(index-i) else: pass if add_list is not None: # interpolate data comp_int = interpolate.interp1d(x_data, y_data, kind='cubic') # iterate through add_list peaks_add = [] for _, guess in enumerate(add_list): height = comp_int(int(guess)) peaks_add.append((int(guess), int(height))) else: peaks_add = [] # build new model fit_result, residuals = spectrafit.build_custom_model(x_data, y_data, peaks, peaks_add, plot_fits) # delete old fit data del hdf5[key] # write data to .hdf5 hdf5['{}/wavenumber'.format(key)] = x_data hdf5['{}/counts'.format(key)] = y_data hdf5['{}/residuals'.format(key)] = residuals for i, result in enumerate(fit_result): # create custom datatype my_datatype = np.dtype([('fraction', np.float), ('center', np.float), ('sigma', np.float), ('amplitude', np.float), ('fwhm', np.float), ('height', np.float), ('area under the curve', np.float)]) if len(result) == 7: if i < 9: dataset = hdf5.create_dataset('{}/Peak_0{}'.format(key, i+1), (1,), dtype=my_datatype) else: dataset = hdf5.create_dataset('{}/Peak_{}'.format(key, i+1), (1,), dtype=my_datatype) elif len(result) == 8: if i < 9: dataset = hdf5.create_dataset('{}/Peak_0{}*'.format(key, i+1), (1,), dtype=my_datatype) else: dataset = hdf5.create_dataset('{}/Peak_{}*'.format(key, i+1), (1,), dtype=my_datatype) else: print('fit_result for Peak_{} contains an inappropriate number of values'.format(i)) # apply data to tuple data = tuple(result[:7]) data_array = np.array(data, dtype=my_datatype) # write new values to the blank dataset dataset[...] = data_array hdf5.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fitPeaks(self, new_peaks, peaks_type):\n # Check if we need to do anything.\n if (new_peaks[\"x\"].size > 0):\n\n # Update status of current peaks (if any) that are near\n # to the new peaks that are being added.\n #\n if (self.mfitter.getNFit() > 0):\n...
[ "0.56082404", "0.5501705", "0.53077525", "0.52218217", "0.50149703", "0.4998173", "0.4938318", "0.49304774", "0.48862016", "0.48674485", "0.48613563", "0.4812949", "0.48021144", "0.47739965", "0.4761532", "0.4754908", "0.47529873", "0.47505748", "0.4730679", "0.4723984", "0.4...
0.6284394
0
This function prints out a display of the contents of any hdf5 file. It prints the filename followed by a list of the groups and datasets in a familiar directory/file format. Groups (folders appear bold) while datasets (files) appear in a standard font.
def view_hdf5(filename): # handling input errors if not isinstance(filename, str): raise TypeError('Passed value of `filename` is not a string! Instead, it is: ' + str(type(filename))) if not filename.split('/')[-1].split('.')[-1] == 'hdf5': raise TypeError('`filename` is not type = .hdf5! Instead, it is: ' + filename.split('/')[-1].split('.')[-1]) # pring groups and datasets in first three layers print('**** {} ****'.format(filename)) hdf5 = h5py.File(filename, 'r') for _, layer_1 in enumerate(list(hdf5.keys())): if isinstance(hdf5[layer_1], h5py.Group): print('\033[1m{}\033[0m'.format(layer_1)) for _, layer_2 in enumerate(list(hdf5[layer_1].keys())): if isinstance(hdf5['{}/{}'.format(layer_1, layer_2)], h5py.Group): print('| \033[1m{}\033[0m'.format(layer_2)) for _, layer_3 in enumerate(list(hdf5['{}/{}'.format(layer_1, layer_2)])): if isinstance(hdf5['{}/{}/{}'.format(layer_1, layer_2, layer_3)], h5py.Group): print('| | \033[1m{}\033[0m/...'.format(layer_3)) else: print('| | {}'.format(layer_3)) else: print('| {}'.format(layer_2)) else: print('{}'.format(layer_1)) hdf5.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def print_h5(fname: str) -> None:\n try:\n with h5py.File(fname, 'r') as h:\n print(fname)\n recursively_print_structure(h, ' ')\n except IOError as e:\n print(f\"Cannot open HDF5 file {fname}\")\n print(f\"IOError: {e}\")", "def printAllColumnsInH5(pathToData):\...
[ "0.6818465", "0.6535027", "0.64906377", "0.63089246", "0.60178846", "0.5999033", "0.5991033", "0.5967706", "0.5928091", "0.59176594", "0.58546895", "0.57313806", "0.571641", "0.56861824", "0.5656443", "0.5614497", "0.55950373", "0.5567397", "0.55614275", "0.5533533", "0.55089...
0.74592173
0
Creates a `SentenceModelFactory` instance for building various models that operate over (samples, max_sentences, max_tokens) input.
def __init__(self, num_classes, token_index, max_sents, max_tokens, embedding_type='glove.6B.100d', embedding_dims=100): self.num_classes = num_classes self.token_index = token_index self.max_sents = max_sents self.max_tokens = max_tokens # This is required to make TimeDistributed(word_encoder_model) work. # TODO: Get rid of this restriction when https://github.com/fchollet/keras/issues/6917 resolves. if self.max_tokens is None: raise ValueError('`max_tokens` should be provided.') if embedding_type is not None: self.embeddings_index = get_embeddings_index( embedding_type, embedding_dims) self.embedding_dims = list(self.embeddings_index.values())[ 0].shape[-1] else: self.embeddings_index = None self.embedding_dims = embedding_dims
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_train_model(self):\n st = LancasterStemmer()\n with open(self.data_path, encoding='utf8') as f_name:\n sentences = [[st.stem(w) for w, t in pos_tag(line.lower().split()) if 'N' in t] for line in f_name]\n sentences = [filter(lambda x: len(x) > 2, (word.strip(punctuati...
[ "0.649424", "0.64815533", "0.6167754", "0.6115422", "0.6060521", "0.60161954", "0.5934859", "0.58826303", "0.5877546", "0.5857269", "0.5842144", "0.5838569", "0.5797957", "0.5765662", "0.57590467", "0.5757475", "0.5740668", "0.5732668", "0.57317764", "0.5691755", "0.5645558",...
0.0
-1
Builds a model that first encodes all words within sentences using `token_encoder_model`, followed by `sentence_encoder_model`.
def build_model(self, token_encoder_model, sentence_encoder_model, trainable_embeddings=True, output_activation='softmax'): if not isinstance(token_encoder_model, SequenceEncoderBase): raise ValueError("`token_encoder_model` should be an instance of `{}`".format( SequenceEncoderBase)) if not isinstance(sentence_encoder_model, SequenceEncoderBase): raise ValueError("`sentence_encoder_model` should be an instance of `{}`".format( SequenceEncoderBase)) if not sentence_encoder_model.allows_dynamic_length() and self.max_sents is None: raise ValueError("Sentence encoder model '{}' requires padding. " "You need to provide `max_sents`") if self.embeddings_index is None: # The +1 is for unknown token index 0. embedding_layer = Embedding(len(self.token_index), self.embedding_dims, input_length=self.max_tokens, mask_zero=token_encoder_model.allows_dynamic_length(), trainable=trainable_embeddings) else: embedding_layer = Embedding(len(self.token_index), self.embedding_dims, weights=[build_embedding_weights( self.token_index, self.embeddings_index)], input_length=self.max_tokens, mask_zero=token_encoder_model.allows_dynamic_length(), trainable=trainable_embeddings) word_input = Input(shape=(self.max_tokens,), dtype='int32') x = embedding_layer(word_input) word_encoding = token_encoder_model(x) token_encoder_model = Model( word_input, word_encoding, name='word_encoder') doc_input = Input( shape=(self.max_sents, self.max_tokens), dtype='int32') sent_encoding = TimeDistributed(token_encoder_model)(doc_input) x = sentence_encoder_model(sent_encoding) x = Dense(self.num_classes, activation=output_activation)(x) return Model(doc_input, x)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_model(self):\n doc_input = Input(shape=(self.max_sent_num ,self.max_sent_length,512), dtype='float32')\n doc_in=Flatten()(doc_input)\n \n #masked3=Masking(mask_value=Special_value)(doc_input)\n \n # self.model_sent = self.build_sent_encoder()\n \n # do...
[ "0.7207636", "0.65596676", "0.65070325", "0.64531505", "0.64466906", "0.62836134", "0.6221808", "0.62141067", "0.621274", "0.6124433", "0.6087191", "0.6082598", "0.60455835", "0.60281765", "0.6019139", "0.6015008", "0.6004691", "0.59985435", "0.599706", "0.5967237", "0.596513...
0.6447885
4
create int of baseN (num symbols, i.e. length of alphabet)
def base_alphabet(cls, value): assert type(value) is str key_length = len(value) return sum( cls.RANGE ** (key_length - (x + 1)) * ord(value[x]) for x in range(key_length) )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generateNchars(inputChar, inputNum):\n return inputChar * int(inputNum)", "def n_char_generate(self,char,n):\n return char*n", "def encode(n, minlen=1):\n\n chs = []\n while n > 0:\n r = n % BASE\n n //= BASE\n\n chs.append(CHARSET[r])\n\n if len(chs) > 0:\n c...
[ "0.73624295", "0.6971849", "0.6857297", "0.67848146", "0.6775475", "0.67715347", "0.6763257", "0.676158", "0.6749873", "0.6745837", "0.6560807", "0.6547647", "0.6545008", "0.6540678", "0.6525718", "0.6508941", "0.6499854", "0.648003", "0.6460463", "0.64499015", "0.64289117", ...
0.6567565
10
cast sha256 to int
def sha256(cls, value): assert type(value) is str return int(sha256(value.encode()).hexdigest(), 16)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def hashToInt(h):\n orderBits = Curve.N.bit_length()\n orderBytes = (orderBits + 7) // 8\n if len(h) > orderBytes:\n h = h[:orderBytes]\n\n ret = int.from_bytes(h, byteorder=\"big\")\n excess = len(h) * 8 - orderBits\n if excess > 0:\n ret = ret >> excess\n return ret", "def ha...
[ "0.7448692", "0.72365516", "0.7121622", "0.7021218", "0.68548185", "0.68216866", "0.6709854", "0.66627985", "0.66617006", "0.66617006", "0.6653154", "0.6538216", "0.64865804", "0.6485043", "0.64513963", "0.6443496", "0.64202505", "0.6406009", "0.64018744", "0.6398126", "0.637...
0.7255353
1
Load the python module containing the classes that all examples instantiate.
def python_module(self) -> ModuleType: if self._python_module is None: # See: https://github.com/linkml/linkml/issues/1219 src = self.schemaview.schema.source_file if not src: src = self.schemaview.schema pygen = PythonGenerator(src) self._python_module = pygen.compile_module() return self._python_module
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def import_all():\n import theory", "def load(self) -> t.Iterable[docspec.Module]:\n # Load all haystack modules\n temp_loader = PythonLoader(search_path=[\"../../../haystack\"])\n temp_loader.init(Context(directory=\".\"))\n all_modules = list(temp_loader.load())\n\n # Coll...
[ "0.6332696", "0.63256395", "0.62903935", "0.62903935", "0.62903935", "0.62782633", "0.6124982", "0.6099244", "0.60306317", "0.5978794", "0.5963904", "0.5955786", "0.58788013", "0.58769953", "0.5871985", "0.5869336", "0.5856597", "0.5833367", "0.5829729", "0.577127", "0.576049...
0.0
-1
Get the current validator
def validator(self) -> DataValidator: if self._validator is None: self._validator = JsonSchemaDataValidator(self.schemaview.schema) return self._validator
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def validator(self):\n return self._validator", "def get_validator(self):\n return self.get_validator_class()(**self.get_validator_kwargs())", "def get_validator(cls):\n cls.validator.model = cls\n return cls.validator or SageValidator", "def _get_validator(self):\n validat...
[ "0.84234047", "0.7831641", "0.755783", "0.7489887", "0.7456082", "0.7314924", "0.7252698", "0.72407633", "0.70353335", "0.69353026", "0.6270272", "0.62356675", "0.60385144", "0.5871536", "0.5861421", "0.5847166", "0.5826005", "0.5799112", "0.5779669", "0.5738615", "0.57354414...
0.69687504
9
Process all examples in the input directory. Filenames should be of the form CLASSNAMEEXAMPLENAME.yaml E.g Person001.yaml
def process_examples(self): input_dir = self.input_directory counter_example_dir = self.counter_example_input_directory if input_dir is None: input_dir = Path.cwd() / "examples" if counter_example_dir is None: counter_example_dir = Path.cwd() / "counter_examples" for fmt in self.input_formats: input_examples = glob.glob(os.path.join(str(input_dir), f"*.{fmt}")) input_counter_examples = glob.glob(os.path.join(str(counter_example_dir), f"*.{fmt}")) if not input_counter_examples: logging.warning( f"No counter examples found in {self.counter_example_input_directory}" ) self.process_examples_from_list(input_examples, fmt, False) self.process_examples_from_list(input_counter_examples, fmt, True)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def process_yamls(folder):\n for item in iglob(folder + \"/*.yaml\"):\n data_file = os.path.join(folder, item)\n data = yaml.load(open(data_file))\n load_data(data)", "def generate_yaml_tests(directory):\n for yml_file in directory.glob(\"*/*.yml\"):\n data = yaml.safe_load(yml_...
[ "0.6632809", "0.62900645", "0.62750703", "0.61933035", "0.6179182", "0.6156422", "0.60064507", "0.5971663", "0.5965593", "0.5941546", "0.59226394", "0.59129375", "0.5911364", "0.58914095", "0.58837914", "0.58785766", "0.5834951", "0.583384", "0.5827961", "0.58051383", "0.5797...
0.74208486
0
Get the list of example source inputs.
def example_source_inputs(self, class_name: str = None) -> List[str]: input_dir = self.input_directory if input_dir is None: return [] all_inputs = [] for fmt in self.input_formats: glob_expr = f"*.{fmt}" if class_name is not None: glob_expr = f"{class_name}-{glob_expr}" input_examples = glob.glob(os.path.join(str(input_dir), glob_expr)) all_inputs.extend(input_examples) return all_inputs
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_train_inputs(self, example):\n return example", "def inputs(self) -> List[str]:\n return self._model.inputs", "def get_inputs(self):\n return self.inputs", "def prepare_inputs(example):\n return example['input_ids'], example['label_ids']", "def prepare_inputs(example):\n ...
[ "0.7428947", "0.7054078", "0.6997518", "0.6961838", "0.6961838", "0.6924607", "0.6878051", "0.6812642", "0.6788958", "0.6788958", "0.6788958", "0.6773123", "0.6742478", "0.67293483", "0.67270637", "0.6706153", "0.6706153", "0.6660394", "0.6660394", "0.6660394", "0.66560566", ...
0.7485938
0
Load an object from a dict, using the target class to determine the type of object to create.
def _load_from_dict(self, dict_obj: Any, target_class: Union[str, ElementName] = None) -> Any: if not self.use_type_designators: return dict_obj sv = self.schemaview if target_class is None: target_class_names = [c.name for c in sv.all_classes().values() if c.tree_root] if len(target_class_names) != 1: raise ValueError( f"Cannot determine single target class, found: {target_class_names}" ) target_class = target_class_names[0] if isinstance(dict_obj, dict): if target_class not in sv.all_classes(): raise ValueError(f"No such class as {target_class}") td_slot = sv.get_type_designator_slot(target_class) if target_class else None if td_slot: if td_slot.name in dict_obj: target_class = dict_obj[td_slot.name] elif "@type" in dict_obj: target_class = dict_obj["@type"] del dict_obj["@type"] if ":" in target_class: target_classes = [c for c in sv.all_classes() if sv.get_uri(c) == target_class] if len(target_classes) != 1: raise ValueError( f"Cannot find unique class for URI {target_class}; got: {target_classes}" ) target_class = target_classes[0] new_dict_obj = {} for k, v in dict_obj.items(): if v is not None: islot = sv.induced_slot(k, target_class) v2 = self._load_from_dict(v, target_class=islot.range) new_dict_obj[k] = v2 py_target_class = getattr(self.python_module, camelcase(target_class)) return py_target_class(**new_dict_obj) elif isinstance(dict_obj, list): return [self._load_from_dict(x, target_class) for x in dict_obj] else: return dict_obj
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_create_obj_by_type_from_dict(self):\n test_obj = {}\n returned_obj = self.tested_class._create_obj_by_type(test_obj)\n self.assertIsInstance(returned_obj, self.tested_class)", "def from_dict(cls, obj):\r\n raise NotImplementedError", "def load(d):\n\n def _load(d):\n ...
[ "0.70920396", "0.6989815", "0.6780296", "0.6534313", "0.65280795", "0.650231", "0.64138657", "0.6346336", "0.625308", "0.62314886", "0.62314886", "0.62314886", "0.62314886", "0.62314886", "0.62314886", "0.62314886", "0.62314886", "0.62314886", "0.62314886", "0.62314886", "0.6...
0.7511082
0
Process a folder of examples and a folder of counter examples. Each example in the folder
def cli(schema, prefixes, output: TextIO, **kwargs): schemaview = SchemaView(schema) prefix_map = yaml.safe_load(open(prefixes)) if prefixes else None runner = ExampleRunner(schemaview=schemaview, prefix_map=prefix_map, **kwargs) runner.process_examples() output.write(str(runner.summary))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def process_examples(self):\n input_dir = self.input_directory\n counter_example_dir = self.counter_example_input_directory\n if input_dir is None:\n input_dir = Path.cwd() / \"examples\"\n if counter_example_dir is None:\n counter_example_dir = Path.cwd() / \"coun...
[ "0.78269464", "0.6656942", "0.65103865", "0.65040845", "0.6154279", "0.61059445", "0.610163", "0.60033727", "0.59996426", "0.59944636", "0.59923977", "0.59606147", "0.59056246", "0.5898781", "0.5840964", "0.582327", "0.58181506", "0.5793695", "0.57936", "0.5792655", "0.57912"...
0.0
-1
Setup logging based on envvars and opinated defaults
def _set_logging(): log_level = os.getenv("TRIKI_LOG_LEVEL", "INFO") quiet = os.getenv("TRIKI_NO_LOG_FILE") handlers = [logging.StreamHandler()] if not quiet: handlers.append(logging.FileHandler("triki_click_analysis.log")) logging.basicConfig( level=log_level, format="%(asctime)-15s %(levelname)s: %(message)s", handlers=handlers, )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setup_logging():\n log.setup('keystone')", "def init_logging():\n global logger\n logging.basicConfig(\n format='%(levelname)s - %(message)s',\n )\n logger = logging.getLogger('runner')\n logger.setLevel(os.environ.get('LOGGING_LEVEL', 'INFO'))", "def setup_logging():\n product_...
[ "0.77894735", "0.778805", "0.7648802", "0.76262087", "0.760029", "0.7522381", "0.7515096", "0.7487156", "0.7406425", "0.73714036", "0.7370101", "0.72803473", "0.7247044", "0.7243538", "0.7200977", "0.7124689", "0.7087081", "0.70848393", "0.70652217", "0.7027191", "0.7013562",...
0.7095803
16
read sites configuration and accept and reject flows for cookie extraction
def _config(): config = None try: with open("%s/sites.yaml" % CONFIG_PATH, "r", encoding="utf8") as f: config = yaml.load(f, Loader=yaml.FullLoader) except Exception as e: LOG.error("Could not load triki configuration: %s", e) raise e return config
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run():\n # Configure logging\n _set_logging()\n\n # Read sites configuration\n config = _config()\n click_stats = {}\n for site in config[\"sites\"]:\n if site[\"flow_type\"] == \"browse\":\n continue\n\n if site[\"url\"] not in click_stats:\n click_stats[s...
[ "0.5378927", "0.5242658", "0.5178188", "0.51298445", "0.5017823", "0.50134027", "0.4965012", "0.49474362", "0.48570472", "0.48500076", "0.4831116", "0.4825486", "0.47815484", "0.4760439", "0.47474295", "0.47219288", "0.4694982", "0.46906415", "0.46869075", "0.46702552", "0.46...
0.0
-1
Analyze cookies for a given site
def run(): # Configure logging _set_logging() # Read sites configuration config = _config() click_stats = {} for site in config["sites"]: if site["flow_type"] == "browse": continue if site["url"] not in click_stats: click_stats[site["url"]] = {} clicks = 0 for step in site["flow"]: if step["action"] == "click": clicks += 1 click_stats[site["url"]][site["flow_type"]] = clicks result = clean_incomplete_flows(click_stats) with open("%s/click_stats.json" % (CWD), "w") as f_out: f_out.write(json.dumps(result)) freq = Counter(result.values()) for key in freq: LOG.info("There are %s percentage of sites that differ in %s clicks between accepting and rejecting cookies", round((freq[key]*100/len(result))), key) LOG.debug(result)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_cookies( headers ):", "def grep(self, request, response):\n # do this check every time\n self._ssl_cookie_via_http(request, response)\n\n #\n # Analyze the response headers and find cookies\n #\n headers = response.get_headers()\n\n for header_name in he...
[ "0.67518246", "0.6578689", "0.6539356", "0.63395107", "0.6263239", "0.6111756", "0.60297865", "0.5971601", "0.59561706", "0.5937958", "0.5852501", "0.5837196", "0.5815859", "0.58023125", "0.5709723", "0.57086116", "0.5672636", "0.5664885", "0.55777025", "0.55619085", "0.55350...
0.5326529
35
Inject Any Dependencies From The Service Container.
def __init__(self, request: Request, response: Response): self.request = request self.response = response
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def Inject(self,injector):\n pass", "async def setup(self, context: InjectionContext):", "def initService(self):", "def services(**kwargs):\n pass", "def init_services(self):\n service_prefix = rospy.get_name() + \"/\"\n\n self._request_components_serv = rospy.Service(service_prefix...
[ "0.6321331", "0.60637295", "0.58977234", "0.58319396", "0.57913065", "0.57750326", "0.57496077", "0.5727155", "0.57216495", "0.56859267", "0.56859267", "0.5597493", "0.54877263", "0.5482274", "0.5453893", "0.54455453", "0.5443783", "0.5441859", "0.5347433", "0.53454655", "0.5...
0.0
-1
Run This Middleware Before The Route Executes.
def before(self): access_token = self.request.header("HTTP_AUTHORIZATION") if utils.validate_token(access_token) is True: token = re.sub("Bearer ", "", access_token) creator_info = utils.decode_token(token) if creator_info != False: creator_user = User.find(creator_info.get("id")) self.request.set_user(creator_user) else: self.response.json({"error": "Unauthorized access"}) if utils.validate_token(access_token) is not True: self.response.json({"error": "Unauthorized access"})
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def before(self, before: Route.Decorator):\n pass", "def pre_runroute_callable(self, route, request):\n return None", "def middleware_after(self):\n pass", "def before_request():\n pass", "def _pre_dispatch(self, request, *args, **kwargs):\n pass", "def do_before(self):\r\n...
[ "0.7504729", "0.73824203", "0.6575558", "0.6395645", "0.63564706", "0.63337", "0.62230784", "0.6183446", "0.61774933", "0.6144887", "0.60888386", "0.6057136", "0.60180676", "0.6015318", "0.600473", "0.594866", "0.59341025", "0.5919592", "0.5748845", "0.5690697", "0.56729746",...
0.5446374
41
Run This Middleware After The Route Executes.
def after(self): pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def middleware_after(self):\n pass", "def after(self, after: Route.Decorator):\n pass", "def post_runroute_callable(self, request):\n return None", "def _after_serve_actions(self):\n pass", "def apply(self, callback, route):", "def pre_runroute_callable(self, route, request):\...
[ "0.8286496", "0.74243283", "0.6934516", "0.6435996", "0.63623714", "0.6270385", "0.59775054", "0.5895936", "0.5744064", "0.5728528", "0.57117546", "0.568691", "0.568691", "0.567398", "0.56448543", "0.5641409", "0.56315535", "0.5599871", "0.5599871", "0.55885375", "0.55782104"...
0.58419746
9
Finds batch norm layers and folds them into preceding layers.
def FoldBatchNorms(graph): _FoldFusedBatchNorms(graph) _FoldUnfusedBatchNorms(graph)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _FoldFusedBatchNorms(graph):\n for match in _FindFusedBatchNorms(graph):\n scope, sep, _ = match.layer_op.name.rpartition('/')\n # Make sure new ops are added to `graph` and put on the same device as\n # `bn_op`. The '/' (i.e. `sep`) ensures that we reuse the existing scope\n # named `scope`. Othe...
[ "0.7719156", "0.7229461", "0.7133129", "0.6721417", "0.6679974", "0.6655169", "0.6560131", "0.6371349", "0.63444275", "0.6342733", "0.6340251", "0.63326925", "0.6292316", "0.6287235", "0.6279157", "0.6265701", "0.62345254", "0.61971396", "0.6180347", "0.6166072", "0.61603427"...
0.71650577
2
Finds fused batch norm layers and folds them into preceding layers.
def _FoldFusedBatchNorms(graph): for match in _FindFusedBatchNorms(graph): scope, sep, _ = match.layer_op.name.rpartition('/') # Make sure new ops are added to `graph` and put on the same device as # `bn_op`. The '/' (i.e. `sep`) ensures that we reuse the existing scope # named `scope`. Otherwise, TF creates a unique scope whose name starts with # `scope`. with graph.as_default(), graph.name_scope(scope + sep), ops.device( match.bn_op.device): with graph.name_scope(scope + sep + 'BatchNorm_Fold' + sep): # new weights = old weights * gamma / sqrt(variance + epsilon) # new biases = -mean * gamma / sqrt(variance + epsilon) + beta multiplier_tensor = match.gamma_tensor * math_ops.rsqrt( match.variance_tensor + match.bn_op.get_attr('epsilon')) bias_tensor = math_ops.subtract( match.beta_tensor, match.mean_tensor * multiplier_tensor, name='bias') # The shape of depthwise weights is different, so we need to reshape the # multiplier_tensor to ensure that the scaled_weight_tensor has the # expected shape. if match.layer_op.type == 'DepthwiseConv2dNative': new_shape = [ match.weight_tensor.get_shape().as_list()[2], match.weight_tensor.get_shape().as_list()[3] ] multiplier_tensor = array_ops.reshape( multiplier_tensor, new_shape, name='scale_reshape') # TODO(suharshs): This naming of the following ops needs to carefully # follow the naming expected by quantize.py. Generalize the quantize code # to not require these delicate naming conventions. scaled_weight_tensor = math_ops.multiply( match.weight_tensor, multiplier_tensor, name='mul_fold') new_layer_tensor = _CloneWithNewOperands( match.layer_op, match.input_tensor, scaled_weight_tensor) bias_add_tensor = math_ops.add( new_layer_tensor, bias_tensor, name='add_fold') nodes_modified_count = graph_editor.reroute_ts(bias_add_tensor, match.output_tensor) if nodes_modified_count != 1: raise ValueError( 'Unexpected inputs to op: %s' % match.output_tensor.name)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def FoldBatchNorms(graph):\n _FoldFusedBatchNorms(graph)\n _FoldUnfusedBatchNorms(graph)", "def _FoldUnfusedBatchNorms(graph):\n input_to_ops_map = input_to_ops.InputToOps(graph)\n\n for bn in common.BatchNormGroups(graph):\n has_scaling = _HasScaling(graph, input_to_ops_map, bn)\n\n # The mangling cod...
[ "0.72084844", "0.70753294", "0.6888734", "0.6833401", "0.65570444", "0.63252455", "0.6297912", "0.6279781", "0.62624854", "0.6249418", "0.62053025", "0.61905295", "0.6186012", "0.6178468", "0.6162257", "0.6147891", "0.61445254", "0.60991395", "0.6081668", "0.6066008", "0.6028...
0.81622905
0
Clones layer_op with input_tensor and weight_tensor as new inputs.
def _CloneWithNewOperands(layer_op, input_tensor, weight_tensor): new_layer_name = layer_op.name.split('/')[-1] + '_Fold' if layer_op.type == 'Conv2D': return nn_ops.conv2d( input_tensor, weight_tensor, strides=layer_op.get_attr('strides'), padding=layer_op.get_attr('padding'), use_cudnn_on_gpu=layer_op.get_attr('use_cudnn_on_gpu'), data_format=layer_op.get_attr('data_format'), name=new_layer_name) elif layer_op.type == 'MatMul': return math_ops.matmul( input_tensor, weight_tensor, transpose_a=layer_op.get_attr('transpose_a'), transpose_b=layer_op.get_attr('transpose_b'), name=new_layer_name) elif layer_op.type == 'DepthwiseConv2dNative': return nn.depthwise_conv2d( input_tensor, weight_tensor, strides=layer_op.get_attr('strides'), padding=layer_op.get_attr('padding'), name=new_layer_name) else: raise ValueError('Cannot handle operation of type: %s' % layer_op.type)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _CloneOp(op, new_name, new_inputs):\n inputs = list(op.inputs)\n for new_input in new_inputs:\n inputs[new_input[0]] = new_input[1]\n return _OP_CLONER.Clone(op, inputs, new_name)", "def build(self, input_layer, trainable=True):\n\n with tf.variable_scope(self.name):\n # Determine the size...
[ "0.62645614", "0.6237233", "0.6156408", "0.61453366", "0.5968321", "0.58285654", "0.5824187", "0.58094114", "0.58049345", "0.5748741", "0.5666261", "0.5660313", "0.5655159", "0.5610911", "0.5606715", "0.55708444", "0.55697495", "0.5538788", "0.5504511", "0.547193", "0.5451717...
0.7447388
0
Finds all ops and tensors related to found FusedBatchNorms.
def _FindFusedBatchNorms(graph): input_pattern = graph_matcher.OpTypePattern('*') weight_pattern = graph_matcher.OpTypePattern('*') gamma_pattern = graph_matcher.OpTypePattern('*') beta_pattern = graph_matcher.OpTypePattern('*') mean_pattern = graph_matcher.OpTypePattern('*') variance_pattern = graph_matcher.OpTypePattern('*') conv_pattern = graph_matcher.OpTypePattern( 'Conv2D|DepthwiseConv2dNative', inputs=[input_pattern, weight_pattern]) # MatMul has a Reshape between it and FusedBatchNorm. matmul_pattern = graph_matcher.OpTypePattern( 'MatMul', inputs=[input_pattern, weight_pattern]) matmul_reshape_pattern = graph_matcher.OpTypePattern( 'Reshape', inputs=[matmul_pattern, graph_matcher.OpTypePattern('*')]) conv_batch_norm_pattern = graph_matcher.OpTypePattern( 'FusedBatchNorm', inputs=[ conv_pattern, gamma_pattern, beta_pattern, mean_pattern, variance_pattern ]) matmul_batch_norm_pattern = graph_matcher.OpTypePattern( 'FusedBatchNorm', inputs=[ matmul_reshape_pattern, gamma_pattern, beta_pattern, mean_pattern, variance_pattern ]) matmul_bn_output_reshape_pattern = graph_matcher.OpTypePattern( 'Reshape', inputs=[matmul_batch_norm_pattern, graph_matcher.OpTypePattern('*')]) conv_matcher = graph_matcher.GraphMatcher(conv_batch_norm_pattern) matmul_matcher = graph_matcher.GraphMatcher(matmul_bn_output_reshape_pattern) def _GetCommonTensors(match_result, bn_op, bn_input_tensor): """Gets tensors needed for FusedBatchNormMatch from match_result.""" input_tensor = match_result.get_tensor(input_pattern) weight_tensor = match_result.get_tensor(weight_pattern) gamma_tensor = match_result.get_tensor(gamma_pattern) beta_tensor = match_result.get_tensor(beta_pattern) # FusedBatchNorm in training is different from that in inference. It takes # empty 'mean' and empty 'variance', and produces the mean and the variance # of the batch. Therefore, when is_training is true, mean_tensor and # variance_tensor point to 1st and 2nd (0-based) output of bn_op, # respectively; when is_training is false, they point to bn_op's inputs. is_training = bn_op.get_attr('is_training') if is_training: # FusedBatchNormGrad doesn't compute gradients of the batch_mean and # batch_variance outputs, so we need to substitute our own custom # gradient. # TODO(suharshs, raghuramank): Find a way to avoid needing this hack. # pylint: disable=protected-access bn_op._set_attr( '_gradient_op_type', attr_value_pb2.AttrValue(s=compat.as_bytes('FoldFusedBatchNormGrad'))) # pylint: enable=protected-access mean_tensor = bn_op.outputs[1] # The batch variance used during forward and backward prop is biased, # i.e it is calculated as: V=sum(x(k)-mu)^2/N. For the moving average # calculation, the variance is corrected by the term N/N-1 (Bessel's # correction). The variance tensor read from FuseBatchNorm has bessel's # correction applied, so we undo it here. n = math_ops.cast( array_ops.size(bn_input_tensor) / array_ops.size(mean_tensor), dtypes.float32) variance_tensor = bn_op.outputs[2] * (n - 1) / n else: mean_tensor = match_result.get_tensor(mean_pattern) variance_tensor = match_result.get_tensor(variance_pattern) return (input_tensor, weight_tensor, gamma_tensor, beta_tensor, mean_tensor, variance_tensor) for match_result in conv_matcher.match_graph(graph): layer_op = match_result.get_op(conv_pattern) layer_tensor = match_result.get_tensor(conv_pattern) bn_op = match_result.get_op(conv_batch_norm_pattern) # In the case of convolution the output_tensor is the output of bn_op. output_tensor = bn_op.outputs[0] (input_tensor, weight_tensor, gamma_tensor, beta_tensor, mean_tensor, variance_tensor) = _GetCommonTensors(match_result, bn_op, layer_tensor) yield _FusedBatchNormMatch( layer_op=layer_op, bn_op=bn_op, output_tensor=output_tensor, input_tensor=input_tensor, weight_tensor=weight_tensor, gamma_tensor=gamma_tensor, beta_tensor=beta_tensor, mean_tensor=mean_tensor, variance_tensor=variance_tensor) for match_result in matmul_matcher.match_graph(graph): layer_op = match_result.get_op(matmul_pattern) layer_tensor = match_result.get_tensor(matmul_pattern) bn_op = match_result.get_op(matmul_batch_norm_pattern) # In the MatMul case, the output of batch norm is reshaped back into a # 2D tensor, so the output_tensor is the output of the Reshape op. output_reshape_op = match_result.get_op(matmul_bn_output_reshape_pattern) output_tensor = output_reshape_op.outputs[0] (input_tensor, weight_tensor, gamma_tensor, beta_tensor, mean_tensor, variance_tensor) = _GetCommonTensors(match_result, bn_op, layer_tensor) yield _FusedBatchNormMatch( layer_op=layer_op, bn_op=bn_op, output_tensor=output_tensor, input_tensor=input_tensor, weight_tensor=weight_tensor, gamma_tensor=gamma_tensor, beta_tensor=beta_tensor, mean_tensor=mean_tensor, variance_tensor=variance_tensor)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _FoldFusedBatchNorms(graph):\n for match in _FindFusedBatchNorms(graph):\n scope, sep, _ = match.layer_op.name.rpartition('/')\n # Make sure new ops are added to `graph` and put on the same device as\n # `bn_op`. The '/' (i.e. `sep`) ensures that we reuse the existing scope\n # named `scope`. Othe...
[ "0.68619853", "0.6494927", "0.60702705", "0.5982493", "0.5894786", "0.5847638", "0.57264715", "0.5440104", "0.5178902", "0.5135283", "0.5134985", "0.5104784", "0.5068771", "0.5065753", "0.5037282", "0.5032491", "0.50149405", "0.50096035", "0.5000106", "0.4991522", "0.49882165...
0.7717176
0
Gets tensors needed for FusedBatchNormMatch from match_result.
def _GetCommonTensors(match_result, bn_op, bn_input_tensor): input_tensor = match_result.get_tensor(input_pattern) weight_tensor = match_result.get_tensor(weight_pattern) gamma_tensor = match_result.get_tensor(gamma_pattern) beta_tensor = match_result.get_tensor(beta_pattern) # FusedBatchNorm in training is different from that in inference. It takes # empty 'mean' and empty 'variance', and produces the mean and the variance # of the batch. Therefore, when is_training is true, mean_tensor and # variance_tensor point to 1st and 2nd (0-based) output of bn_op, # respectively; when is_training is false, they point to bn_op's inputs. is_training = bn_op.get_attr('is_training') if is_training: # FusedBatchNormGrad doesn't compute gradients of the batch_mean and # batch_variance outputs, so we need to substitute our own custom # gradient. # TODO(suharshs, raghuramank): Find a way to avoid needing this hack. # pylint: disable=protected-access bn_op._set_attr( '_gradient_op_type', attr_value_pb2.AttrValue(s=compat.as_bytes('FoldFusedBatchNormGrad'))) # pylint: enable=protected-access mean_tensor = bn_op.outputs[1] # The batch variance used during forward and backward prop is biased, # i.e it is calculated as: V=sum(x(k)-mu)^2/N. For the moving average # calculation, the variance is corrected by the term N/N-1 (Bessel's # correction). The variance tensor read from FuseBatchNorm has bessel's # correction applied, so we undo it here. n = math_ops.cast( array_ops.size(bn_input_tensor) / array_ops.size(mean_tensor), dtypes.float32) variance_tensor = bn_op.outputs[2] * (n - 1) / n else: mean_tensor = match_result.get_tensor(mean_pattern) variance_tensor = match_result.get_tensor(variance_pattern) return (input_tensor, weight_tensor, gamma_tensor, beta_tensor, mean_tensor, variance_tensor)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _FindFusedBatchNorms(graph):\n input_pattern = graph_matcher.OpTypePattern('*')\n weight_pattern = graph_matcher.OpTypePattern('*')\n gamma_pattern = graph_matcher.OpTypePattern('*')\n beta_pattern = graph_matcher.OpTypePattern('*')\n mean_pattern = graph_matcher.OpTypePattern('*')\n variance_pattern = g...
[ "0.687296", "0.53285825", "0.52761436", "0.526731", "0.52641547", "0.52601016", "0.52112883", "0.5158161", "0.51153666", "0.51105905", "0.5093035", "0.5083832", "0.5050526", "0.50354075", "0.50354075", "0.50307226", "0.50050557", "0.49959216", "0.49791405", "0.49321866", "0.4...
0.6739167
1
Finds unfused batch norm layers and folds them into preceding layers.
def _FoldUnfusedBatchNorms(graph): input_to_ops_map = input_to_ops.InputToOps(graph) for bn in common.BatchNormGroups(graph): has_scaling = _HasScaling(graph, input_to_ops_map, bn) # The mangling code intimately depends on BatchNorm node's internals. original_op, folded_op = _CreateFoldedOp(graph, bn, has_scaling=has_scaling) activation = common.GetEndpointActivationOp(graph, bn) if activation: nodes_modified_count = graph_editor.reroute_ts([folded_op.outputs[0]], [original_op.outputs[0]], can_modify=[activation]) if nodes_modified_count != 1: raise ValueError('Unexpected inputs to op: %s' % activation.name) continue # Treat consumer ops in bypass modules differently since they have Add # operations instead of Relu* above. add_bypass_ctx = re.search(r'^(.*)/([^/]+)', bn).group(1) add_bypass = graph.get_operation_by_name(add_bypass_ctx + '/Add') nodes_modified_count = graph_editor.reroute_ts([folded_op.outputs[0]], [original_op.outputs[0]], can_modify=[add_bypass]) if nodes_modified_count != 1: raise ValueError('Unexpected inputs to op: %s' % add_bypass.name)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _FoldFusedBatchNorms(graph):\n for match in _FindFusedBatchNorms(graph):\n scope, sep, _ = match.layer_op.name.rpartition('/')\n # Make sure new ops are added to `graph` and put on the same device as\n # `bn_op`. The '/' (i.e. `sep`) ensures that we reuse the existing scope\n # named `scope`. Othe...
[ "0.77741086", "0.7156549", "0.7024513", "0.68224394", "0.63824594", "0.63595194", "0.6346714", "0.625679", "0.6225848", "0.6212077", "0.620075", "0.6187602", "0.617762", "0.6148358", "0.6089603", "0.60637486", "0.6047825", "0.6043735", "0.60115445", "0.60108745", "0.60100204"...
0.74272305
1
r"""Checks if batch norm has scaling enabled.
def _HasScaling(graph, input_to_ops_map, bn): rsqrt_op = graph.get_operation_by_name(bn + '/BatchNorm/batchnorm/Rsqrt') rsqrt_consumers = input_to_ops_map.ConsumerOperations(rsqrt_op) return sum(1 for op in rsqrt_consumers if op.type == 'Mul') == 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_scale_enabled(self) -> bool:\r\n ...", "def scaling_enabled(self):\n return False", "def isSetScale(self):\n return _libsbml.Unit_isSetScale(self)", "def param_scale_check(shape_x, shape_scale):\n\n length_x = len(shape_x)\n length_scale = len(shape_scale)\n\n if not(leng...
[ "0.73828375", "0.6997457", "0.6757541", "0.6416183", "0.6400106", "0.6291684", "0.626143", "0.6211953", "0.6028917", "0.6004665", "0.59074646", "0.5888298", "0.5888298", "0.5880715", "0.582264", "0.5821804", "0.57957906", "0.578953", "0.5759011", "0.57504267", "0.574466", "...
0.71985847
1
Folds in batch norm layer into preceding convolution or FC layer.
def _CreateFoldedOp(graph, context, has_scaling): mul_scale_name = 'mul_1' if has_scaling else 'mul' mul_scale = graph.get_operation_by_name(context + '/BatchNorm/batchnorm/' + mul_scale_name) op_below = mul_scale.inputs[0].op weights = op_below.inputs[1] # Special handling for weights of depthwise convolution. if op_below.type == 'DepthwiseConv2dNative': new_shape = [weights.get_shape().as_list()[2], weights.get_shape().as_list()[3]] scale_name = 'mul' if has_scaling else 'Rsqrt' scale = graph.get_operation_by_name(context + '/BatchNorm/batchnorm/' + scale_name) scale = array_ops.reshape(scale.outputs[0], new_shape, context + '/scale_reshape') mul_fold = _CloneOp(mul_scale, context + '/mul_fold', [(0, weights), (1, scale)]) elif op_below.type in ['Conv2D', 'MatMul']: mul_fold = _CloneOp(mul_scale, context + '/mul_fold', [(0, weights)]) else: raise ValueError('Cannot handle operation of type: %s' % op_below.op) _AssertShapesMatch('mul_fold', mul_fold.inputs[0], mul_fold.outputs[0]) conv_or_fc_folded = _CloneOp(op_below, op_below.name + '_Fold', [(1, mul_fold.outputs[0])]) add_shift = graph.get_operation_by_name(context + '/BatchNorm/batchnorm/add_1') add_fold = _CloneOp(add_shift, context + '/add_fold', [(0, conv_or_fc_folded.outputs[0])]) _AssertShapesMatch('add_fold', add_fold.inputs[0], add_fold.outputs[0]) return add_shift, add_fold
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _FoldFusedBatchNorms(graph):\n for match in _FindFusedBatchNorms(graph):\n scope, sep, _ = match.layer_op.name.rpartition('/')\n # Make sure new ops are added to `graph` and put on the same device as\n # `bn_op`. The '/' (i.e. `sep`) ensures that we reuse the existing scope\n # named `scope`. Othe...
[ "0.741322", "0.7192601", "0.7024944", "0.65865403", "0.6524311", "0.6433525", "0.64148235", "0.6409592", "0.63852406", "0.6368449", "0.6261133", "0.625201", "0.6227543", "0.62111515", "0.6099192", "0.605792", "0.6036166", "0.6032598", "0.60256046", "0.59939164", "0.59921294",...
0.56397575
76
Clones a given op, replaces its name and some of its inputs.
def _CloneOp(op, new_name, new_inputs): inputs = list(op.inputs) for new_input in new_inputs: inputs[new_input[0]] = new_input[1] return _OP_CLONER.Clone(op, inputs, new_name)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clone(self):\r\n cp = self.__class__(self.op, self.inputs, [output.clone() for output in self.outputs])\r\n cp.tag = copy(self.tag)\r\n return cp", "def _CloneWithNewOperands(layer_op, input_tensor, weight_tensor):\n new_layer_name = layer_op.name.split('/')[-1] + '_Fold'\n if layer_op...
[ "0.61716413", "0.6113947", "0.5992132", "0.5831337", "0.5507165", "0.5421506", "0.5408626", "0.5406843", "0.5405116", "0.5387802", "0.5377177", "0.53763574", "0.53390443", "0.5338112", "0.53215635", "0.5299693", "0.52697754", "0.5264059", "0.5250165", "0.5242738", "0.5225992"...
0.82067853
0
Makes sure that convolution inputs have compatible shapes.
def _AssertConvShapes(self, op_name, input_tensor, weights): input_shape = input_tensor.get_shape() weights_shape = weights.get_shape() if (len(input_shape) != 4 or len(weights_shape) != 4 or input_shape[3] != weights_shape[2]): raise ValueError('Incompatible shapes for op %s inputs: %s and %s' % (op_name, input_shape, weights_shape))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_convolve_input_dim_check(self, case, fn, x_shape, y_shape):\n x = torch.rand(*x_shape, dtype=self.dtype, device=self.device)\n y = torch.rand(*y_shape, dtype=self.dtype, device=self.device)\n\n message = [\n \"The operands must be the same dimension\",\n \"Leadin...
[ "0.70430326", "0.6984046", "0.67752093", "0.67076695", "0.6631883", "0.6590607", "0.65526205", "0.6539452", "0.65392506", "0.65136945", "0.6513212", "0.6502569", "0.64620143", "0.64320785", "0.6431594", "0.6411467", "0.64058405", "0.63952243", "0.63517404", "0.6339218", "0.63...
0.732145
0
Makes sure that FC layer inputs have compatible shapes.
def _AssertFCShapes(self, op_name, weights, input_tensor): weights_shape = weights.get_shape() input_shape = input_tensor.get_shape() if (len(weights_shape) != 2 or len(input_shape) != 2 or weights_shape[1] != input_shape[0]): raise ValueError('Incompatible shapes for op %s inputs: %s and %s' % (op_name, weights_shape, input_shape))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _AssertConvShapes(self, op_name, input_tensor, weights):\n input_shape = input_tensor.get_shape()\n weights_shape = weights.get_shape()\n if (len(input_shape) != 4 or len(weights_shape) != 4 or\n input_shape[3] != weights_shape[2]):\n raise ValueError('Incompatible shapes for op %s inputs:...
[ "0.7000613", "0.6832547", "0.6529788", "0.64534384", "0.63770324", "0.6370928", "0.6363974", "0.6346374", "0.633438", "0.63139635", "0.6271003", "0.6215813", "0.6161302", "0.6155026", "0.6152465", "0.614528", "0.61381274", "0.61302507", "0.61197114", "0.61083287", "0.6102161"...
0.7046982
0
Makes sure that shapes of input and output tensors are compatible.
def _AssertShapesMatch(op_name, in_tensor, out_tensor): in_shape = in_tensor.get_shape() out_shape = out_tensor.get_shape() if not in_shape.is_compatible_with(out_shape): raise ValueError('%s should not change tensor shape: input %s, ' 'output %s' % (op_name, in_shape, out_shape))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_compatible_with(self, inputs): # pylint:disable=useless-super-delegation\n if self.shape is None:\n return False\n if len(inputs) != len(self):\n raise ValueError('Expects ' +\n str(len(self)) + ' inputs, '\n ...
[ "0.69564956", "0.689856", "0.6888036", "0.6857275", "0.67998415", "0.67264485", "0.662843", "0.64965355", "0.6468758", "0.6395005", "0.63594204", "0.6335894", "0.6281145", "0.6273137", "0.6260043", "0.6223739", "0.6200478", "0.61994135", "0.61986095", "0.6178359", "0.6171779"...
0.71506196
0
FtsSftpSettings a model defined in Swagger
def __init__( self, server_enabled=None, port=None, authentication_method=None, keystore_file_path=None, keystore_file_password=None, ciphers=None, known_users_file_path=None, overridden_users_home_directories=None, _configuration=None, ): # noqa: E501 # noqa: E501 if _configuration is None: _configuration = Configuration() self._configuration = _configuration self._server_enabled = None self._port = None self._authentication_method = None self._keystore_file_path = None self._keystore_file_password = None self._ciphers = None self._known_users_file_path = None self._overridden_users_home_directories = None self.discriminator = None if server_enabled is not None: self.server_enabled = server_enabled if port is not None: self.port = port if authentication_method is not None: self.authentication_method = authentication_method if keystore_file_path is not None: self.keystore_file_path = keystore_file_path if keystore_file_password is not None: self.keystore_file_password = keystore_file_password if ciphers is not None: self.ciphers = ciphers if known_users_file_path is not None: self.known_users_file_path = known_users_file_path if overridden_users_home_directories is not None: self.overridden_users_home_directories = overridden_users_home_directories
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def settings_f(self, settings):\n\n self._set_list_field(\"settings\", settings)", "def settings(self) -> SchemaActionModel:\n from whyqd.models import SchemaActionModel\n\n action_settings = {\n \"name\": self.name,\n \"title\": self.title,\n \"description\"...
[ "0.5506861", "0.5433878", "0.5257615", "0.5172841", "0.5120341", "0.50570154", "0.5018799", "0.50135064", "0.49987316", "0.4978686", "0.48532736", "0.48511937", "0.48081392", "0.47605264", "0.47407997", "0.4732555", "0.47176045", "0.47113883", "0.47113824", "0.47100484", "0.4...
0.0
-1
Sets the server_enabled of this FtsSftpSettings.
def server_enabled(self, server_enabled): self._server_enabled = server_enabled
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def enable_server(self, server):\n log.info(\"Enabling %s in netscaler\", server)\n return self.post(\"server?action=enable\", {\"server\": {\"name\": server}}, content_type=self.content_type(\"server\"))", "def set_dhcpserver_enabled(self, bEnabled):\n\t\tcall_sdk_function('PrlVirtNet_SetDHCPServe...
[ "0.64041066", "0.62101185", "0.6115301", "0.57635754", "0.5666829", "0.560498", "0.5532448", "0.55312526", "0.55182683", "0.55100137", "0.54706293", "0.5436376", "0.53900456", "0.5380313", "0.5367764", "0.53609276", "0.5244654", "0.52353865", "0.5225218", "0.5225218", "0.5204...
0.7935785
0
Sets the port of this FtsSftpSettings.
def port(self, port): self._port = port
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setport(self, port):\n self.__port = port", "async def set_port(self, port: int) -> None:\n self.port = port\n _LOGGER.info(\"Setting port to %s\", port)\n if self._server:\n self._server.stop()\n await self._start_server()", "def setPort(self, port):\n ...
[ "0.73324144", "0.6641451", "0.6534417", "0.6477737", "0.63782763", "0.634139", "0.6179274", "0.60978943", "0.6081789", "0.601399", "0.5758358", "0.56853056", "0.56781864", "0.5621059", "0.5606282", "0.5590328", "0.5580774", "0.5580774", "0.5580774", "0.5580774", "0.5580774", ...
0.6902951
3
Sets the authentication_method of this FtsSftpSettings.
def authentication_method(self, authentication_method): self._authentication_method = authentication_method
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def authentication_methods(self, authentication_methods):\n\n self._authentication_methods = authentication_methods", "def auth_method(self):\n return self.settings[\"authMethod\"]", "def auth_method(self):\n return self[\"authMethod\"]", "def auth_method(self) -> Optional[pulumi.Input[s...
[ "0.62380636", "0.61203897", "0.5855358", "0.55694807", "0.5538085", "0.5522016", "0.5440951", "0.53794426", "0.53782594", "0.5377386", "0.5356047", "0.5349534", "0.52542967", "0.5180398", "0.5180398", "0.51782846", "0.5156288", "0.50967616", "0.5048462", "0.501886", "0.501095...
0.7283392
0
Sets the keystore_file_path of this FtsSftpSettings.
def keystore_file_path(self, keystore_file_path): self._keystore_file_path = keystore_file_path
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def keystore_file_password(self, keystore_file_password):\n\n self._keystore_file_password = keystore_file_password", "def _set_keystore_path(self) -> None:\n response = self.single_call(\"hmy keys location\").strip()\n if not os.path.exists(response):\n os.mkdir(response)\n ...
[ "0.7145288", "0.6014983", "0.58418983", "0.55596626", "0.5433482", "0.5313241", "0.51829666", "0.5103493", "0.5063631", "0.49352625", "0.49106106", "0.48667493", "0.48239157", "0.48141515", "0.4736292", "0.46992692", "0.4678572", "0.46774423", "0.4635615", "0.46148446", "0.46...
0.7703561
0
Sets the keystore_file_password of this FtsSftpSettings.
def keystore_file_password(self, keystore_file_password): self._keystore_file_password = keystore_file_password
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def org_apache_felix_https_keystore_key_password(self, org_apache_felix_https_keystore_key_password: ConfigNodePropertyString):\n\n self._org_apache_felix_https_keystore_key_password = org_apache_felix_https_keystore_key_password", "def org_apache_felix_https_keystore_password(self, org_apache_felix_https...
[ "0.697365", "0.6841448", "0.6515118", "0.6424852", "0.60550404", "0.5957332", "0.5679264", "0.56787336", "0.56772876", "0.56676793", "0.5628823", "0.55949026", "0.55878115", "0.5577493", "0.5540421", "0.551728", "0.5511115", "0.54981464", "0.54964054", "0.5444806", "0.5444743...
0.8196835
0
Sets the ciphers of this FtsSftpSettings.
def ciphers(self, ciphers): self._ciphers = ciphers
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ciphers(self) -> Sequence[str]:\n return pulumi.get(self, \"ciphers\")", "def ciphers(self) -> Sequence[str]:\n return pulumi.get(self, \"ciphers\")", "def ciphers(self):\n return self._ciphers", "def set_ssl(self):\n for params in self.config.get_ssl_params():\n se...
[ "0.63286173", "0.63286173", "0.6211777", "0.55823", "0.53944427", "0.52489173", "0.5057643", "0.49852008", "0.4932068", "0.4884324", "0.48747385", "0.48445147", "0.48318604", "0.48281583", "0.48003778", "0.47863695", "0.47562948", "0.47462425", "0.47110054", "0.46554583", "0....
0.7703951
0
Sets the known_users_file_path of this FtsSftpSettings.
def known_users_file_path(self, known_users_file_path): self._known_users_file_path = known_users_file_path
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __parse_user_keyfiles(self):\n\n user_sshdir = os.path.expanduser('~/.ssh')\n if not os.path.isdir(user_sshdir):\n return\n\n paths = []\n for filename in os.listdir(user_sshdir):\n if filename in SSH_CONFIG_FILES or os.path.splitext(filename)[1] != '.pub':\n ...
[ "0.57418454", "0.5557294", "0.54986745", "0.5214731", "0.5214731", "0.5180744", "0.5055465", "0.5035089", "0.50259876", "0.4974094", "0.496511", "0.49633723", "0.4950638", "0.49499902", "0.48848796", "0.48848796", "0.48848796", "0.4883349", "0.48802492", "0.4863774", "0.48286...
0.8051893
0
Sets the overridden_users_home_directories of this FtsSftpSettings.
def overridden_users_home_directories(self, overridden_users_home_directories): self._overridden_users_home_directories = overridden_users_home_directories
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_share_user_home_dir(self, bShareUserHomeDir):\n\t\tcall_sdk_function('PrlVmCfg_SetShareUserHomeDir', self.handle, bShareUserHomeDir)", "def set_user_home(self, path):\n os.environ['HOME'] = path", "def set_user_home(self, path):\n os.environ['HOME'] = path", "def homeDirectory(self, ign...
[ "0.6600052", "0.6430041", "0.6430041", "0.6197573", "0.57821155", "0.5754564", "0.57503104", "0.5628441", "0.5487617", "0.54494035", "0.54009694", "0.53437734", "0.53021526", "0.5258358", "0.5253186", "0.52394444", "0.5199579", "0.5132827", "0.5066063", "0.5064636", "0.506463...
0.8290534
0
Returns the model properties as a dict
def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list( map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) ) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items(), ) ) else: result[attr] = value if issubclass(FtsSftpSettings, dict): for key, value in self.items(): result[key] = value return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_dict(self):\n return self.properties", "def to_dict(self):\n return self.properties", "def get_properties(self):\n return self.properties", "def asdict(self):\n return self._prop_dict", "def json(self):\n rv = {\n prop: getattr(self, prop)\n f...
[ "0.7751993", "0.7751993", "0.73391134", "0.7334895", "0.7297356", "0.727818", "0.7159078", "0.71578115", "0.71494967", "0.71494967", "0.71283495", "0.71275014", "0.7122587", "0.71079814", "0.7060394", "0.7043251", "0.7034103", "0.70233124", "0.69635814", "0.69586295", "0.6900...
0.0
-1
Returns the string representation of the model
def to_str(self): return pprint.pformat(self.to_dict())
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __str__(self):\n return super().__str__() + self.model.__str__()", "def __str__(self) -> str:\n # noinspection PyUnresolvedReferences\n opts = self._meta\n if self.name_field:\n result = str(opts.get_field(self.name_field).value_from_object(self))\n else:\n ...
[ "0.85856134", "0.7814518", "0.77898884", "0.7751367", "0.7751367", "0.7712228", "0.76981676", "0.76700574", "0.7651133", "0.7597206", "0.75800353", "0.7568254", "0.7538184", "0.75228703", "0.7515832", "0.7498764", "0.74850684", "0.74850684", "0.7467648", "0.74488163", "0.7442...
0.0
-1
For `print` and `pprint`
def __repr__(self): return self.to_str()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pprint(*args, **kwargs):\n if PRINTING:\n print(*args, **kwargs)", "def print_out():\n pass", "def custom_print(*objects):\n print(*objects, sep=OFS, end=ORS)", "def _print(self, *args):\n return _ida_hexrays.vd_printer_t__print(self, *args)", "def _printable(self):\n ...
[ "0.75577617", "0.73375154", "0.6986672", "0.698475", "0.6944995", "0.692333", "0.6899106", "0.6898902", "0.68146646", "0.6806209", "0.6753795", "0.67497987", "0.6744008", "0.6700308", "0.6691256", "0.6674591", "0.6658083", "0.66091245", "0.6606931", "0.6601862", "0.6563738", ...
0.0
-1
Returns true if both objects are equal
def __eq__(self, other): if not isinstance(other, FtsSftpSettings): return False return self.to_dict() == other.to_dict()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __eq__(self, other):\n return are_equal(self, other)", "def __eq__(self, other):\n return are_equal(self, other)", "def __eq__(self,other):\n try: return self.object==other.object and isinstance(self,type(other))\n except: return False", "def __eq__(self, other):\n if i...
[ "0.8088132", "0.8088132", "0.8054589", "0.7982687", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", "0.79670393", ...
0.0
-1
Returns true if both objects are not equal
def __ne__(self, other): if not isinstance(other, FtsSftpSettings): return True return self.to_dict() != other.to_dict()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __ne__(self, other: object) -> bool:\n if self.__eq__(other):\n return False\n return True", "def __ne__(self, other: object) -> bool:\n return not self.__eq__(other)", "def __ne__(self, other) -> bool:\n return not self.__eq__(other)", "def __eq__(self, other):\n ...
[ "0.845611", "0.8391477", "0.8144138", "0.81410587", "0.8132492", "0.8093973", "0.80920255", "0.80920255", "0.80920255", "0.8085325", "0.8085325", "0.8076365", "0.8076365", "0.8065748", "0.8042487", "0.8042487", "0.8042487", "0.8042487", "0.8042487", "0.8042487", "0.8042487", ...
0.0
-1
article is initialized with xml text contained inside tags
def __init__(self, article_xml): self.article_xml = article_xml self.links = self.grab_links() self.first_link = self.parse_first_link()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, txt='', unicodeEncoding='utf-8'):\n # __document capture the document level structure\n # for each sentence and then put in the archives when the next sentence\n # is processed\n super(ConTextMarkup, self).__init__(__txt=None,\n ...
[ "0.6530297", "0.6436172", "0.631786", "0.62645775", "0.61489284", "0.61476105", "0.61120623", "0.6110277", "0.6025093", "0.5990031", "0.59805065", "0.59666455", "0.5903457", "0.5874341", "0.58594066", "0.5852814", "0.5852356", "0.5843398", "0.58399487", "0.58204275", "0.58045...
0.6952109
0
checks whether inside char such as parentheses or wiki_template handles nested tags and parenthesis
def inside_char(self, char, marker, tracker, i): if char == marker[0]: tracker.append(i) elif char == marker[1]: try: tracker.pop() except IndexError: pass return tracker
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def should_lex(cls, char):\n return char == '{' or char == '}'", "def bracketed (phrase,bracketing='()'):\r\n\r\n level = 0\r\n left_point = None\r\n right_point = None\r\n \r\n\r\n for count,char in enumerate(phrase):\r\n\r\n ...
[ "0.6666362", "0.6587422", "0.6509962", "0.62256867", "0.6221628", "0.6045276", "0.6035796", "0.6013747", "0.5975426", "0.5962291", "0.5932169", "0.59234065", "0.5919558", "0.5899327", "0.58970016", "0.5894412", "0.586094", "0.5844774", "0.5832094", "0.5824058", "0.5822532", ...
0.0
-1
returns a list of the outermost links not in parenthesis a tempalte, or a tag
def grab_links(self): links = [] link_char = [] w_temp = [] #in template? par = [] #in parentheses? rtag = [] #in <ref> tag? dtag = [] #in <div> tag? skip_char = [] for i, c in enumerate(self.article_xml): if i in skip_char: continue #eliminates double counting char = self.article_xml[i:i+2] tag = self.article_xml[i:i+4] #wiki template w_temp = self.inside_char(char, Article.w_marker, w_temp, i) if char in Article.w_marker: skip_char.append(i+1) if w_temp: continue #doesn't process if inside wiki template #parentheses par = self.inside_char(c, Article.par_marker, par, i) if par: continue #<ref> or <div> rtag = self.inside_char(tag, Article.rtag_marker, rtag, i) dtag = self.inside_char(tag, Article.dtag_marker, dtag, i) if rtag or dtag: continue #clear to add outer-most link if char == '[[': link_char.append(i) elif char == ']]' and len(link_char) == 1: links.append( self.article_xml[link_char[0]:i+2]) link_char.pop() elif char == ']]' and len(link_char) > 1: link_char.pop() return links
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def filter_substitution_image_links(links):\n return [link for link in links if '{' not in link]", "def getExpandedLinks():", "def removeHtmlTags(self, text):\n sb = []\n text = self.removeHtmlComments(text)\n bits = text.split(u'<')\n sb.append(bits.pop(0))\n tagstack = [...
[ "0.6023677", "0.592088", "0.57580185", "0.5751759", "0.5707651", "0.56727266", "0.55507445", "0.55107826", "0.5486449", "0.5462063", "0.5458863", "0.54393977", "0.5430559", "0.5428695", "0.54271686", "0.5418311", "0.538971", "0.53824365", "0.5366302", "0.5362929", "0.52836615...
0.67386085
0
filters links to images, files, or other Wikimedia projects returns false if it's an invalid link (including links with a colon)
def check_link(self, link): false_links = ["wikipedia:", "w:", "wikitionary:", "wikt:", "wikinews:", "n:", "wikibooks:", "b:", "wikiquote:", "q:", "wikisource:", "s:", "wikispecies:", "species:", "wikiversity", "v:", "wikivoyage:", "voy:", "wikimedia:", "foundation:", "wmf:", "commonds:", "c:", "chapter:", "metawikipedia:", "meta:", "m:", "incubator:", "outreach:", "mw:", "mediazilla:", "bugzilla:", "testwiki:", "wikitech:", "wikidata:", "d:", "phabricator:", "phab:", "talk:", "user talk:", "file:", "user:", "template:", "category:", "file talk:", "category talk:", "image:", "media:", "special:", "help:", "portal:", "portal talk:", "\#"] is_bad = any(false_link in link.lower() for false_link in false_links) if is_bad or link[0] == ":": return False else: return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_link(self, link, links_para):\n href = link['href']\n if not href.startswith('/wiki/') or href == '/wiki/Latin' or href.startswith('#'):\n return False\n if \"<i>\" in link or href in links_para:\n return False\n title = href[6:]\n if title.starts...
[ "0.68379533", "0.67308575", "0.6564884", "0.6558733", "0.6462883", "0.6375301", "0.6374791", "0.6300895", "0.62788117", "0.6265837", "0.62631965", "0.62593323", "0.622585", "0.62170655", "0.6212652", "0.6198974", "0.6183221", "0.61607987", "0.61497504", "0.6100527", "0.607530...
0.67699367
1
strips brackets, returns link destination (not display name)
def clean_link(self, link): link = link.strip("[]") if "|" in link: link = link.split("|",1)[0] link = link.strip() #remove trailing white space return link
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def format_link(self, link):\n new_link = \"/\".join(link.split(\"/\")[0:3])\n return \"http://www.imdb.com\" + new_link", "def remove_links(str):\n stripped_str = re.sub(\"\\[.*\\]\",\"\", str)\n str_list = filter(None, stripped_str.split(\" \"))\n built_string = \" \".join(str_list)\n ...
[ "0.6074059", "0.6058749", "0.5964363", "0.59119755", "0.58833617", "0.5830744", "0.57996374", "0.57897335", "0.57738227", "0.5760817", "0.5757934", "0.5745697", "0.5745697", "0.5744635", "0.57165736", "0.57104677", "0.57055384", "0.5694247", "0.5692231", "0.5687585", "0.56484...
0.6704387
0
returns the first link not in parenthesis or side bar linking to another Wikipedia article
def parse_first_link(self): for link in self.links: if self.check_link(link): return self.clean_link(link) return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_first_link(self, article):\n #Hit the article Wikipeadia URL\n page = urllib.request.urlopen(article)\n html = page.read()\n soup = BeautifulSoup(html, 'lxml')\n\n #Iterate over all the paragraphs on that page to find the first valid link\n for child_para in soup.f...
[ "0.6734185", "0.60958993", "0.59966624", "0.59682524", "0.5811541", "0.57882994", "0.57841915", "0.5728055", "0.5717133", "0.5638308", "0.5562975", "0.55171794", "0.5489789", "0.5458334", "0.54468036", "0.5370557", "0.5341832", "0.5329611", "0.52882546", "0.5273016", "0.52512...
0.5563361
10
Initialize data fields that are privately accessed by methods.
def __init__(self): #: Dict[str, Any]: Experiment metadata self.__experiment_metadata = None #: List[CurveData]: Processed experiment data set. self.__processed_data_set = list() #: Backend: backend object used for experimentation self.__backend = None # Add expected options to instance variable so that every method can access to. for key in self._default_options().__dict__: setattr(self, f"__{key}", None) # Add fixed parameters to instance variable so that every method can access to. for key in self.__fixed_parameters__: setattr(self, f"__{key}", None)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _initFields(self):\n pass", "def _initialize_data(self):\n self.reset_count = 0\n self._idn_no_firmware = \"KEPCO,BOP 50-20,E1234,\"\n self._firmware = 2.6\n self._init_data()", "def _initialize_data(self):\n self.unique_id = 123\n\n self.gas_valve_open = Fa...
[ "0.76582444", "0.74731344", "0.7425868", "0.73784906", "0.7361675", "0.7292158", "0.72656184", "0.7225879", "0.71781945", "0.7178042", "0.7178042", "0.7178042", "0.7178042", "0.71680367", "0.71609104", "0.7134724", "0.71275795", "0.7106942", "0.7106942", "0.7106942", "0.71069...
0.0
-1
Return a list of fitting parameters.
def _fit_params(cls) -> List[str]: fsigs = set() for series_def in cls.__series__: fsigs.add(inspect.signature(series_def.fit_func)) if len(fsigs) > 1: raise AnalysisError( "Fit functions specified in the series definition have " "different function signature. They should receive " "the same parameter set for multi-objective function fit." ) # remove the first function argument. this is usually x, i.e. not a fit parameter. fit_params = list(list(fsigs)[0].parameters.keys())[1:] # remove fixed parameters if cls.__fixed_parameters__ is not None: for fixed_param in cls.__fixed_parameters__: try: fit_params.remove(fixed_param) except ValueError as ex: raise AnalysisError( f"Defined fixed parameter {fixed_param} is not a fit function argument." "Update series definition to ensure the parameter name is defined with " f"fit functions. Currently available parameters are {fit_params}." ) from ex return fit_params
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_fitted_params(self):\n self.check_is_fitted()\n return {\n name: self._fitted_forecaster.params.get(name)\n for name in self._get_fitted_param_names()\n }", "def _get_fitted_param_names(self):\n return self._fitted_param_names", "def get_random_fit_para...
[ "0.7828273", "0.77081746", "0.76167715", "0.7338232", "0.7242317", "0.7235081", "0.7188947", "0.71217304", "0.70609885", "0.7037319", "0.70190436", "0.69019854", "0.68696225", "0.68649846", "0.68517315", "0.6831097", "0.68142086", "0.6786738", "0.6786738", "0.67717886", "0.67...
0.76450473
2
Return default analysis options.
def _default_options(cls) -> Options: options = super()._default_options() options.curve_fitter = multi_curve_fit options.data_processor = None options.normalization = False options.x_key = "xval" options.plot = True options.axis = None options.xlabel = None options.ylabel = None options.xlim = None options.ylim = None options.xval_unit = None options.yval_unit = None options.result_parameters = None options.return_data_points = False options.curve_plotter = "mpl_single_canvas" options.style = PlotterStyle() # automatically populate initial guess and boundary fit_params = cls._fit_params() options.p0 = {par_name: None for par_name in fit_params} options.bounds = {par_name: None for par_name in fit_params} return options
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_default_options():\n return {\n \"library_folders\": [],\n \"verbose\": False,\n \"check_balanced\": True,\n \"mtime_check\": True,\n \"cache\": False,\n \"codegen\": False,\n \"expand_mx\": False,\n \"unroll_loops\": True,\n \"inline_funct...
[ "0.7549235", "0.719861", "0.69945633", "0.6927882", "0.69001687", "0.6894544", "0.66589355", "0.66432", "0.6590571", "0.6562118", "0.65403587", "0.652091", "0.6491698", "0.64637583", "0.63624984", "0.63468444", "0.63431454", "0.63394517", "0.63120544", "0.630802", "0.62956554...
0.6501929
12
Create algorithmic guess with analysis options and curve data. Subclasses can override this method. Subclass can access to the curve data with ``self._data()`` method. If there are multiple series, you can get a specific series by specifying ``series_name``. This method returns a ``CurveData`` instance, which is the `dataclass` containing x values `.x`, y values `.y`, and sigma values `.y_err`. Subclasses can also access the defined analysis options with the ``self._get_option``.
def _generate_fit_guesses(self, user_opt: FitOptions) -> Union[FitOptions, List[FitOptions]]: return user_opt
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _data(\n self,\n series_name: Optional[str] = None,\n label: Optional[str] = \"fit_ready\",\n ) -> CurveData:\n # pylint: disable = undefined-loop-variable\n for data in self.__processed_data_set:\n if data.label == label:\n break\n else:\n...
[ "0.5883084", "0.54168564", "0.53361595", "0.5319225", "0.52603143", "0.5193059", "0.5182683", "0.51758766", "0.49965793", "0.49939272", "0.4931551", "0.48864993", "0.48791257", "0.48548958", "0.48361152", "0.48181638", "0.4806349", "0.4798925", "0.47625017", "0.4762404", "0.4...
0.0
-1
An optional subroutine to perform data preprocessing. Subclasses can override this method to apply preprecessing to data values to fit. For example, Apply smoothing to y values to deal with noisy observed values Remove redundant data points (outlier) Apply frequency filter function etc... By default, the analysis just takes average over the same x values and sort data index by the x values in ascending order.
def _format_data(self, data: CurveData) -> CurveData: # take average over the same x value by keeping sigma series, xdata, ydata, sigma, shots = multi_mean_xy_data( series=data.data_index, xdata=data.x, ydata=data.y, sigma=data.y_err, shots=data.shots, method="shots_weighted", ) # sort by x value in ascending order series, xdata, ydata, sigma, shots = data_sort( series=series, xdata=xdata, ydata=ydata, sigma=sigma, shots=shots, ) return CurveData( label="fit_ready", x=xdata, y=ydata, y_err=sigma, shots=shots, data_index=series, )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def data_preprocessing_TA(X):\n \n #Removing the mean and scaling the data\n X_prep=StandardScaler().fit_transform(X)\n #do here your preprocessing\n return X_prep", "def preprocess_data(self):\n\n self._preprocess_train_data()\n self._preprocess_test_data()", "def _preprocess(self...
[ "0.6810427", "0.6516489", "0.64986575", "0.6411439", "0.63673955", "0.6354587", "0.62562776", "0.62349963", "0.6196094", "0.61521447", "0.6125845", "0.6114392", "0.60915864", "0.60897946", "0.6052889", "0.6036394", "0.60005444", "0.59890485", "0.59801954", "0.59771967", "0.59...
0.0
-1
Calculate new quantity from the fit result. Subclasses can override this method to do post analysis.
def _extra_database_entry(self, fit_data: FitData) -> List[AnalysisResultData]: return []
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def produce(self, quantitiy):\n self._newly = self._newly + quantitiy", "def calculate(self):\n pass", "def calculate(self):\r\n pass", "def calculate(self):\r\n\r\n pass", "def calculate(self):", "def calculate_profit(self):", "def calculate(self) -> float:", "def _comput...
[ "0.6846123", "0.62927526", "0.62778115", "0.6193843", "0.6191502", "0.61145157", "0.6083223", "0.6076098", "0.58801895", "0.586378", "0.5855786", "0.5849116", "0.5840168", "0.5801364", "0.5797429", "0.5791977", "0.57748055", "0.5772653", "0.5755219", "0.5754523", "0.5725244",...
0.0
-1
Evaluate quality of the fit result. Subclasses can override this method to do post analysis.
def _evaluate_quality(self, fit_data: FitData) -> Union[str, None]: return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None]:\n freq_increment = np.mean(np.diff(fit_data.x_data))\n\n fit_a = fit_data.ufloat_params[\"a\"]\n fit_b = fit_data.ufloat_params[\"b\"]\n fit_freq = fit_data.ufloat_params[\"freq\"]\n fit_kappa = fit_...
[ "0.7156114", "0.684477", "0.657213", "0.65535766", "0.64372116", "0.63338166", "0.6271525", "0.62638944", "0.62541264", "0.62117773", "0.6151621", "0.606927", "0.60639936", "0.60630333", "0.60455346", "0.6035397", "0.59774005", "0.5925373", "0.59253347", "0.59226096", "0.5920...
0.7637929
0
Extract curve data from experiment data. This method internally populates two types of curve data.
def _extract_curves( self, experiment_data: ExperimentData, data_processor: Union[Callable, DataProcessor] ): self.__processed_data_set = list() def _is_target_series(datum, **filters): try: return all(datum["metadata"][key] == val for key, val in filters.items()) except KeyError: return False # Extract X, Y, Y_sigma data data = experiment_data.data() x_key = self._get_option("x_key") try: x_values = [datum["metadata"][x_key] for datum in data] except KeyError as ex: raise DataProcessorError( f"X value key {x_key} is not defined in circuit metadata." ) from ex if isinstance(data_processor, DataProcessor): y_values, y_sigmas = data_processor(data) if y_sigmas is None: y_sigmas = np.full(y_values.shape, np.nan) else: y_values, y_sigmas = zip(*map(data_processor, data)) # Store metadata metadata = np.asarray([datum["metadata"] for datum in data], dtype=object) # Store shots shots = np.asarray([datum.get("shots", np.nan) for datum in data]) # Format data x_values = np.asarray(x_values, dtype=float) y_values = np.asarray(y_values, dtype=float) y_sigmas = np.asarray(y_sigmas, dtype=float) # Find series (invalid data is labeled as -1) data_index = np.full(x_values.size, -1, dtype=int) for idx, series_def in enumerate(self.__series__): data_matched = np.asarray( [_is_target_series(datum, **series_def.filter_kwargs) for datum in data], dtype=bool ) data_index[data_matched] = idx # Store raw data raw_data = CurveData( label="raw_data", x=x_values, y=y_values, y_err=y_sigmas, shots=shots, data_index=data_index, metadata=metadata, ) self.__processed_data_set.append(raw_data) # Format raw data formatted_data = self._format_data(raw_data) if formatted_data.label != "fit_ready": raise AnalysisError(f"Not expected data label {formatted_data.label} != fit_ready.") self.__processed_data_set.append(formatted_data)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ex_curve(data):\n rv = []\n try:\n ef = autocomplete_curve_function(data[0])\n ed = autocomplete_curve_direction(data[1])\n period = 2\n try:\n period = max(int(data[2]), 2)\n except ValueError:\n pass\n data = data[3:]\n if not data:...
[ "0.6097595", "0.59153706", "0.5720998", "0.56816626", "0.55583704", "0.5506386", "0.5458484", "0.54564375", "0.5437237", "0.5421108", "0.54172045", "0.54148316", "0.54103583", "0.53691983", "0.5329527", "0.52916807", "0.5291498", "0.52747667", "0.5228793", "0.5213298", "0.520...
0.6852174
0
Return type of experiment.
def _experiment_type(self) -> str: try: return self.__experiment_metadata["experiment_type"] except (TypeError, KeyError): # Ignore experiment metadata is not set or key is not found return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def experiment_type(filename):\n assert(isinstance(filename, str))\n exp_type = filename.split('/')[-1].split('.')[-2].split('_')[1:-1]\n exp_type = '_'.join(exp_type)\n logger.debug('{} is of type {}'.format(filename, exp_type))\n return exp_type", "def get_test_type(self):\n return self.t...
[ "0.701162", "0.69926196", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "0.6970925", "...
0.8181823
0
Getter for qubit number.
def _num_qubits(self) -> int: try: return self.__experiment_metadata["num_qubits"] except (TypeError, KeyError): # Ignore experiment metadata is not set or key is not found return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __int__(self):\n return int(self.q[0])", "def quantity(self) -> str:\n return self.__quantity", "def q0(self):\n charge = self.get('q0')\n if charge is not None:\n charge = charge[0]\n return charge", "def __float__(self):\n return self.q[0]", "def g...
[ "0.6964956", "0.6374862", "0.63433015", "0.6280601", "0.6269734", "0.62318814", "0.61975247", "0.61747855", "0.61747855", "0.61747855", "0.61707705", "0.612971", "0.6113343", "0.60924786", "0.6048749", "0.60435194", "0.60197186", "0.60107774", "0.5947766", "0.59348696", "0.59...
0.58175623
27
Getter for physical qubit indices.
def _physical_qubits(self) -> List[int]: try: return list(self.__experiment_metadata["physical_qubits"]) except (TypeError, KeyError): # Ignore experiment metadata is not set or key is not found return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def indices(self):\n return self._kbounded_partitions", "def get_indices(self):\r\n return self._indices", "def indices(self) -> np.ndarray:\n return self.impl.indices", "def jw_number_indices(n_electrons, n_qubits):\n occupations = itertools.combinations(range(n_qubits), n_electr...
[ "0.66136235", "0.63095975", "0.6267602", "0.62219816", "0.6181241", "0.6174731", "0.6135461", "0.5949904", "0.5915764", "0.58870023", "0.58162713", "0.58161235", "0.5783942", "0.5758474", "0.57396424", "0.56639326", "0.5659677", "0.5655574", "0.56555057", "0.5643877", "0.5641...
0.6819982
0
Getter for backend object.
def _backend(self) -> Backend: return self.__backend
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def backend(self):\n # This never changes (so no read locking needed).\n return self._backend", "def get_backend():\n return _BACKEND", "def get_backend():\n return Connection()", "def get_backend():\n return __SETTINGS__._BACKEND", "def backend_object(self, id):\n return self.m...
[ "0.79623115", "0.76062316", "0.7487151", "0.7388517", "0.72666264", "0.7238288", "0.71368957", "0.7134815", "0.7086919", "0.7014857", "0.6954881", "0.6920183", "0.6918006", "0.6918006", "0.6909595", "0.690837", "0.690837", "0.67804307", "0.6756487", "0.6732792", "0.66931", ...
0.8183749
0
Return the experiment options of given job index.
def _experiment_options(self, index: int = -1) -> Dict[str, Any]: try: return self.__experiment_metadata["job_metadata"][index]["experiment_options"] except (TypeError, KeyError, IndexError): # Ignore experiment metadata or job metadata is not set or key is not found return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _run_options(self, index: int = -1) -> Dict[str, Any]:\n try:\n return self.__experiment_metadata[\"job_metadata\"][index][\"run_options\"]\n except (TypeError, KeyError, IndexError):\n # Ignore experiment metadata or job metadata is not set or key is not found\n ...
[ "0.71390533", "0.6975858", "0.6919278", "0.621385", "0.59916735", "0.580255", "0.5618967", "0.549171", "0.54512733", "0.5414998", "0.53518206", "0.5308031", "0.5284357", "0.5283639", "0.5231703", "0.5185954", "0.5171701", "0.51661193", "0.50663817", "0.50663465", "0.50529015"...
0.80677307
0
Returns the analysis options of given job index.
def _analysis_options(self, index: int = -1) -> Dict[str, Any]: try: return self.__experiment_metadata["job_metadata"][index]["analysis_options"] except (TypeError, KeyError, IndexError): # Ignore experiment metadata or job metadata is not set or key is not found return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _experiment_options(self, index: int = -1) -> Dict[str, Any]:\n try:\n return self.__experiment_metadata[\"job_metadata\"][index][\"experiment_options\"]\n except (TypeError, KeyError, IndexError):\n # Ignore experiment metadata or job metadata is not set or key is not found...
[ "0.6743674", "0.6663001", "0.6280733", "0.6069232", "0.60599047", "0.565759", "0.54964", "0.5447708", "0.54197335", "0.53915113", "0.53473103", "0.53200793", "0.52881956", "0.52273625", "0.51928836", "0.5185036", "0.5124009", "0.51195866", "0.5102956", "0.5085236", "0.5047777...
0.7922862
0
Returns the run options of given job index.
def _run_options(self, index: int = -1) -> Dict[str, Any]: try: return self.__experiment_metadata["job_metadata"][index]["run_options"] except (TypeError, KeyError, IndexError): # Ignore experiment metadata or job metadata is not set or key is not found return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _experiment_options(self, index: int = -1) -> Dict[str, Any]:\n try:\n return self.__experiment_metadata[\"job_metadata\"][index][\"experiment_options\"]\n except (TypeError, KeyError, IndexError):\n # Ignore experiment metadata or job metadata is not set or key is not found...
[ "0.64497", "0.6384364", "0.62348664", "0.61879486", "0.6184877", "0.59024817", "0.5853503", "0.56605256", "0.5530498", "0.5475739", "0.54434043", "0.53275234", "0.5277181", "0.5277181", "0.5277181", "0.5276527", "0.5255759", "0.5234088", "0.523196", "0.522801", "0.52041173", ...
0.79151005
0
Returns the transpile options of given job index.
def _transpile_options(self, index: int = -1) -> Dict[str, Any]: try: return self.__experiment_metadata["job_metadata"][index]["transpile_options"] except (TypeError, KeyError, IndexError): # Ignore experiment metadata or job metadata is not set or key is not found return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_job_options(self):\n argument = [string.Template(self.queue.template[key]).substitute(\n {key : value}) for key, value in self.options.items()]\n\n if len(self.custom_options) > 0:\n argument += self.custom_options\n\n return argument", "def _experiment_...
[ "0.58368", "0.56201595", "0.54462826", "0.5405374", "0.5268604", "0.51483375", "0.514388", "0.5095438", "0.48473778", "0.48377272", "0.476263", "0.47249606", "0.47134674", "0.46772844", "0.46634972", "0.465322", "0.46220458", "0.46066916", "0.45873234", "0.4573063", "0.455892...
0.7755575
0
Getter for experiment data set.
def _data( self, series_name: Optional[str] = None, label: Optional[str] = "fit_ready", ) -> CurveData: # pylint: disable = undefined-loop-variable for data in self.__processed_data_set: if data.label == label: break else: raise AnalysisError(f"Requested data with label {label} does not exist.") if series_name is None: return data for idx, series_def in enumerate(self.__series__): if series_def.name == series_name: locs = data.data_index == idx return CurveData( label=label, x=data.x[locs], y=data.y[locs], y_err=data.y_err[locs], shots=data.shots[locs], data_index=idx, metadata=data.metadata[locs] if data.metadata is not None else None, ) raise AnalysisError(f"Specified series {series_name} is not defined in this analysis.")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_data_set(self):\n raise exceptions.NotImplemented", "def get_dataset(self):\n return", "def getData(self):\n import labstep.entities.experimentDataField.repository as experimentDataFieldRepository\n\n return experimentDataFieldRepository.getDataFields(self)", "def _getData...
[ "0.73165673", "0.7052748", "0.6754608", "0.6651235", "0.66467166", "0.6585998", "0.65527946", "0.6204858", "0.62044996", "0.6169423", "0.6161288", "0.6150837", "0.6140225", "0.6097636", "0.6096406", "0.6089341", "0.6074704", "0.60708326", "0.60613275", "0.6054039", "0.6027216...
0.0
-1
Parse input kwargs with predicted input. Class attributes will be updated according to the ``options``. For example, if ``options`` has a key ``p0``, and the class has an attribute named ``__p0``, then the attribute ``__0p`` will be updated to ``options["p0"]``. Options that don't have matching attributes will be included in the returned dictionary.
def _arg_parse(self, **options) -> Dict[str, Any]: extra_options = dict() for key, value in options.items(): private_key = f"__{key}" if hasattr(self, private_key): setattr(self, private_key, value) else: extra_options[key] = value return extra_options
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _parse_options(options):\n opts = dict()\n for attr in dir(options):\n if attr.startswith(\"__\"):\n continue\n opts[attr] = getattr(options, attr)\n return opts", "def extract_kwargs_from_options(options):\n return modulation_utils.extract_kwargs_from_options(dqpsk_m...
[ "0.6199073", "0.6011524", "0.6008918", "0.5943669", "0.59151167", "0.5756908", "0.5742022", "0.56702465", "0.5639711", "0.5626554", "0.55926645", "0.5560618", "0.55327994", "0.54897285", "0.54338837", "0.54048324", "0.5363454", "0.52499473", "0.5185636", "0.5124794", "0.50433...
0.63792646
0
A helper function to get specified field from the input analysis options.
def _get_option(self, arg_name: str) -> Any: try: return getattr(self, f"__{arg_name}") except AttributeError as ex: raise AnalysisError( f"The argument {arg_name} is selected but not defined. " "This key-value pair should be defined in the analysis option." ) from ex
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_field(self, field):\n return self.extra_fields[field]", "def _get_field(self, section, field):\n if not self._configparser.has_option(section, field):\n return None\n return self._configparser.get(section, field).strip()", "def getfield(value, arg):\n #import pdb; pdb...
[ "0.7381745", "0.7185751", "0.68803525", "0.67426527", "0.67239267", "0.66201144", "0.6597977", "0.6535103", "0.6499053", "0.6402019", "0.63318866", "0.63269514", "0.62780046", "0.6272967", "0.6267418", "0.6213745", "0.62035835", "0.62024516", "0.61439806", "0.6094945", "0.608...
0.58981884
40
Run analysis on circuit data.
def _run_analysis( self, experiment_data: ExperimentData, **options ) -> Tuple[List[AnalysisResultData], List["pyplot.Figure"]]: # # 1. Parse arguments # # Pop arguments that are not given to the fitter, # and update class attributes with the arguments that are given to the fitter # (arguments that have matching attributes in the class) extra_options = self._arg_parse(**options) # Update all fit functions in the series definitions if fixed parameter is defined. # Fixed parameters should be provided by the analysis options. if self.__fixed_parameters__: assigned_params = {k: self._get_option(k) for k in self.__fixed_parameters__} # Check if all parameters are assigned. if any(v is None for v in assigned_params.values()): raise AnalysisError( f"Unassigned fixed-value parameters for the fit " f"function {self.__class__.__name__}." f"All values of fixed-parameters, i.e. {self.__fixed_parameters__}, " "must be provided by the analysis options to run this analysis." ) # Override series definition with assigned fit functions. assigned_series = [] for series_def in self.__series__: dict_def = dataclasses.asdict(series_def) dict_def["fit_func"] = functools.partial(series_def.fit_func, **assigned_params) assigned_series.append(SeriesDef(**dict_def)) self.__series__ = assigned_series # get experiment metadata try: self.__experiment_metadata = experiment_data.metadata except AttributeError: pass # get backend try: self.__backend = experiment_data.backend except AttributeError: pass # # 2. Setup data processor # # No data processor has been provided at run-time we infer one from the job # metadata and default to the data processor for averaged classified data. data_processor = self._get_option("data_processor") if not data_processor: run_options = self._run_options() or dict() try: meas_level = run_options["meas_level"] except KeyError as ex: raise DataProcessorError( f"Cannot process data without knowing the measurement level: {str(ex)}." ) from ex meas_return = run_options.get("meas_return", None) normalization = self._get_option("normalization") data_processor = get_processor(meas_level, meas_return, normalization) if isinstance(data_processor, DataProcessor) and not data_processor.is_trained: # Qiskit DataProcessor instance. May need calibration. data_processor.train(data=experiment_data.data()) # # 3. Extract curve entries from experiment data # self._extract_curves(experiment_data=experiment_data, data_processor=data_processor) # # 4. Run fitting # curve_fitter = self._get_option("curve_fitter") formatted_data = self._data(label="fit_ready") # Generate algorithmic initial guesses and boundaries default_fit_opt = FitOptions( parameters=self._fit_params(), default_p0=self._get_option("p0"), default_bounds=self._get_option("bounds"), **extra_options, ) fit_options = self._generate_fit_guesses(default_fit_opt) if isinstance(fit_options, FitOptions): fit_options = [fit_options] # Run fit for each configuration fit_results = [] for fit_opt in set(fit_options): try: fit_result = curve_fitter( funcs=[series_def.fit_func for series_def in self.__series__], series=formatted_data.data_index, xdata=formatted_data.x, ydata=formatted_data.y, sigma=formatted_data.y_err, **fit_opt.options, ) fit_results.append(fit_result) except AnalysisError: # Some guesses might be too far from the true parameters and may thus fail. # We ignore initial guesses that fail and continue with the next fit candidate. pass # Find best value with chi-squared value if len(fit_results) == 0: warnings.warn( "All initial guesses and parameter boundaries failed to fit the data. " "Please provide better initial guesses or fit parameter boundaries.", UserWarning, ) # at least return raw data points rather than terminating fit_result = None else: fit_result = sorted(fit_results, key=lambda r: r.reduced_chisq)[0] # # 5. Create database entry # analysis_results = [] if fit_result: # pylint: disable=assignment-from-none quality = self._evaluate_quality(fit_data=fit_result) fit_models = { series_def.name: series_def.model_description or "no description" for series_def in self.__series__ } # overview entry analysis_results.append( AnalysisResultData( name=PARAMS_ENTRY_PREFIX + self.__class__.__name__, value=FitVal(fit_result.popt, fit_result.popt_err), chisq=fit_result.reduced_chisq, quality=quality, extra={ "popt_keys": fit_result.popt_keys, "dof": fit_result.dof, "covariance_mat": fit_result.pcov, "fit_models": fit_models, }, ) ) # output special parameters result_parameters = self._get_option("result_parameters") if result_parameters: for param_repr in result_parameters: if isinstance(param_repr, ParameterRepr): p_name = param_repr.name p_repr = param_repr.repr or param_repr.name unit = param_repr.unit else: p_name = param_repr p_repr = param_repr unit = None result_entry = AnalysisResultData( name=p_repr, value=fit_result.fitval(p_name, unit), chisq=fit_result.reduced_chisq, quality=quality, ) analysis_results.append(result_entry) # add extra database entries analysis_results.extend(self._extra_database_entry(fit_result)) if self._get_option("return_data_points"): # save raw data points in the data base if option is set (default to false) raw_data_dict = dict() for series_def in self.__series__: series_data = self._data(series_name=series_def.name, label="raw_data") raw_data_dict[series_def.name] = { "xdata": series_data.x, "ydata": series_data.y, "sigma": series_data.y_err, } raw_data_entry = AnalysisResultData( name=DATA_ENTRY_PREFIX + self.__class__.__name__, value=raw_data_dict, extra={ "x-unit": self._get_option("xval_unit"), "y-unit": self._get_option("yval_unit"), }, ) analysis_results.append(raw_data_entry) # # 6. Create figures # if self._get_option("plot"): fit_figure = FitResultPlotters[self._get_option("curve_plotter")].value.draw( series_defs=self.__series__, raw_samples=[self._data(ser.name, "raw_data") for ser in self.__series__], fit_samples=[self._data(ser.name, "fit_ready") for ser in self.__series__], tick_labels={ "xval_unit": self._get_option("xval_unit"), "yval_unit": self._get_option("yval_unit"), "xlabel": self._get_option("xlabel"), "ylabel": self._get_option("ylabel"), "xlim": self._get_option("xlim"), "ylim": self._get_option("ylim"), }, fit_data=fit_result, result_entries=analysis_results, style=self._get_option("style"), axis=self._get_option("axis"), ) figures = [fit_figure] else: figures = [] return analysis_results, figures
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def analyze(self):\n # turn off all indicator lights\n self._stop_all()\n \n # run, but catch exceptions and abort if necessary\n try:\n # setup\n self.analysis_led[1].blink\n ims_left = self.num_images\n fluid_left = True\n ...
[ "0.69162107", "0.65155345", "0.6410257", "0.6370625", "0.6360335", "0.62594646", "0.6259212", "0.6210015", "0.6194382", "0.6162395", "0.61607206", "0.6143942", "0.6135079", "0.6115741", "0.60923856", "0.6073705", "0.6056743", "0.6019407", "0.60120445", "0.60077256", "0.596112...
0.0
-1
Interface to Dark Sky API. Requests data from Boston Airport for a specific time.
def ping_darksky(time, key): boston = forecast(key, *BOSTON, time=time.isoformat()) fetch = { 'day': time, 'tempMin': boston["daily"]["data"][0].get('temperatureMin', np.nan), 'tempMax': boston["daily"]["data"][0].get('temperatureMax', np.nan), 'summary': boston["daily"]["data"][0].get('summary', np.nan), 'desc': boston["daily"]["data"][0].get('icon', np.nan), 'cloudCover': boston["daily"]["data"][0].get('cloudCover', np.nan)} return fetch
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def download_flights(self, time_start, time_end, limit=None):\n\n t_start = parser.parse(str(time_start))\n t_end = parser.parse(str(time_end))\n string_start = t_start.strftime(timestring_traffic)\n string_end = t_end.strftime(timestring_traffic)\n\n logger.info(\"Downloading fl...
[ "0.62457645", "0.59939075", "0.58592993", "0.5772396", "0.5735043", "0.5696683", "0.5681655", "0.562768", "0.5607731", "0.55556893", "0.5517979", "0.54691505", "0.54423225", "0.53862786", "0.5370203", "0.5335187", "0.53251284", "0.5310476", "0.52809924", "0.5272097", "0.52525...
0.59688425
2
Key generator that allows to switch between keys that are provided in the `secret_key.txt` file.
def switch_key(): with open("secret_key.txt", 'r') as key_file: api_keys = key_file.read().splitlines() for api_key in api_keys: yield api_key
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_key():\n key = Fernet.generate_key()\n with open(\"secret.key\", \"wb\") as key_file:\n key_file.write(key)", "def generate_key():\n key = Fernet.generate_key()\n with open(\"Secret.key\",\"wb\")as key_file:\n key_file.write(key)", "def setup_keys():\n if os.path.isfil...
[ "0.7030336", "0.6970633", "0.69157135", "0.6851234", "0.665555", "0.6652344", "0.6556344", "0.64819336", "0.64733076", "0.64401174", "0.6436973", "0.64132476", "0.64103454", "0.63922274", "0.6378862", "0.6355134", "0.63407135", "0.6338451", "0.6336893", "0.6334349", "0.627503...
0.75049704
0
High level hook called when a SIP has been deposited in a landing zone
def ingestPostProcSipDepositInLandingZone(dataObjectPath, user, zone): logger.info("ingestPostProcSipDepositInLandingZone()") logger.info("dataObjectPath: %s" % dataObjectPath) logger.info("user:%s" % user) logger.info("zone:%s" % zone)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def place_call_offhold(self) -> None:", "def place_call_onhold(self) -> None:", "def _extract_kiss_destination(self):\n self.destination = aprs.Callsign(self.frame)", "def ring_zone(self, tissue):\n print(\"controller - ring_zone!\")\n self.view.processing_gui.ask_ring_out(tissue)", "d...
[ "0.5777385", "0.5624411", "0.5509368", "0.54877645", "0.5309101", "0.52809733", "0.5173685", "0.514805", "0.50955397", "0.50581396", "0.50581396", "0.5057988", "0.5046991", "0.50424355", "0.4994274", "0.49913985", "0.49630877", "0.49369216", "0.49329975", "0.49219167", "0.492...
0.5720877
1
Determines if the cache file has expired, or if it is still valid.
def is_cache_valid(self): if os.path.isfile(self.cache_path_cache): mod_time = os.path.getmtime(self.cache_path_cache) current_time = time() if (mod_time + self.cache_max_age) > current_time: if os.path.isfile(self.cache_path_index): return True return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_cache_valid(self):\n if os.path.isfile(self.cache_filename):\n mod_time = os.path.getmtime(self.cache_filename)\n current_time = time()\n if (mod_time + self.cache_max_age) > current_time:\n return True\n return False", "def _has_expired(self):...
[ "0.8303035", "0.81870496", "0.81366026", "0.7783219", "0.7776521", "0.74953747", "0.74173236", "0.7377239", "0.73766756", "0.7369789", "0.7367112", "0.7316954", "0.7301829", "0.7263233", "0.72622615", "0.7256245", "0.7229072", "0.7212795", "0.71875364", "0.71544033", "0.71081...
0.81022
3
Reads the settings from the .ini file.
def read_settings(self): config = ConfigParser.SafeConfigParser() config.read(os.path.dirname(os.path.realpath(__file__)) + '/linode.ini') # Cache related cache_path = config.get('linode', 'cache_path') self.cache_path_cache = cache_path + "/ansible-linode.cache" self.cache_path_index = cache_path + "/ansible-linode.index" self.cache_max_age = config.getint('linode', 'cache_max_age')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read_ini_file (path):\n # TODO write a code to read data from ini-file to dictionary\n\n\n pass", "def read_settings():\n settings_path = join(dirname(dirname(__file__)), '.settings')\n filename = settings_path\n settings = configparser.ConfigParser()\n settings.read(filenam...
[ "0.78161585", "0.75787467", "0.7542528", "0.75028604", "0.7157366", "0.7131641", "0.7130143", "0.70960146", "0.7094251", "0.70651275", "0.7060127", "0.70441425", "0.69870484", "0.69269586", "0.6910985", "0.6874622", "0.6770381", "0.67605144", "0.67298234", "0.67260176", "0.67...
0.74082285
4
Command line argument processing
def parse_cli_args(self): parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on Linode') parser.add_argument('--list', action='store_true', default=True, help='List nodes (default: True)') parser.add_argument('--host', action='store', help='Get all the variables about a specific node') parser.add_argument('--refresh-cache', action='store_true', default=False, help='Force refresh of cache by making API requests to Linode (default: False - use cache files)') self.args = parser.parse_args()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_arguments(args):", "def main():\n args = parse_args()\n process_args(args)", "def main(args):", "def main(args):", "def handle_cmdline_args():\n\n parser = argparse.ArgumentParser(\n description='Generate synthetic data from a specification in a json '\n 'file using the \"s...
[ "0.79806894", "0.7410795", "0.7347014", "0.7347014", "0.732627", "0.7314383", "0.7243857", "0.7243857", "0.7172061", "0.71507037", "0.71507037", "0.7083144", "0.7063987", "0.7059328", "0.7023228", "0.7022323", "0.6996324", "0.69877625", "0.6986569", "0.6975588", "0.69686943",...
0.0
-1
Do API calls, and save data in cache files.
def do_api_calls_update_cache(self): self.get_nodes() self.write_to_cache(self.inventory, self.cache_path_cache) self.write_to_cache(self.index, self.cache_path_index)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __call__(self, *args, **kw):\n cachepath = self.cachepath(*args, **kw)\n try:\n # try returning from cache first\n return self.loadcache(cachepath)\n except IOError:\n # not found, so run api query\n self._sleep()\n self.lastcall = tim...
[ "0.6925335", "0.6491691", "0.6327244", "0.6154643", "0.60999835", "0.60896784", "0.60562545", "0.6047197", "0.5878853", "0.5847318", "0.57860565", "0.5767712", "0.5724594", "0.57162315", "0.57134306", "0.56965476", "0.565406", "0.56492305", "0.5622184", "0.56044537", "0.56002...
0.71164197
0
Makes an Linode API call to get the list of nodes.
def get_nodes(self): try: for node in Linode.search(status=Linode.STATUS_RUNNING): self.add_node(node) except chube_api.linode_api.ApiError, e: print "Looks like Linode's API is down:" print print e sys.exit(1)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_nodes(self):\n return requests.get(self.__url + 'nodes').json()", "def get_nodes(self):\n _url = f\"{self.connector.base_url}/projects/{self.project_id}/nodes\"\n\n _response = self.connector.http_call(\"get\", _url)\n\n # Create the Nodes array but cleanup cache if there is o...
[ "0.7121502", "0.6617446", "0.65728307", "0.6527529", "0.64565825", "0.6433634", "0.6416782", "0.6389691", "0.6355934", "0.6353988", "0.6350259", "0.6307714", "0.62806284", "0.62762433", "0.6274298", "0.6197774", "0.61561686", "0.60973465", "0.6084577", "0.60462004", "0.604404...
0.71513474
0
Gets details about a specific node.
def get_node(self, linode_id): try: print "LI %s" % linode_id return Linode.find(api_id=linode_id) except chube_api.linode_api.ApiError, e: print "Looks like Linode's API is down:" print print e sys.exit(1)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def node_show(self, node):\n if node.instance_uuid:\n n = self.ironic_client.node.get_by_instance_uuid(\n node.instance_uuid)\n else:\n n = self.ironic_client.node.get(node.uuid)\n return n", "def get_node_details(self, node):\n node_details = self...
[ "0.72397673", "0.7213035", "0.7093766", "0.70038104", "0.6988307", "0.69717085", "0.691202", "0.6856567", "0.68082803", "0.6648218", "0.6574323", "0.65702695", "0.64131516", "0.6382399", "0.6349754", "0.6327587", "0.6295838", "0.62867105", "0.6261446", "0.62473834", "0.621963...
0.5726441
75
Creates self._datacenter_cache, containing all Datacenters indexed by ID.
def populate_datacenter_cache(self): self._datacenter_cache = {} dcs = Datacenter.search() for dc in dcs: self._datacenter_cache[dc.api_id] = dc
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def Datacenters(self):\n if not self._datacenters:\n dcs = self._get_objects(vim.Datacenter)\n for dc in dcs:\n self._datacenters[dc.name] = dc\n return self._datacenters", "def get_datacenters_by(self, datacenter=None, tenant=None, **kwargs):\n if tenant...
[ "0.6505794", "0.53940344", "0.5058107", "0.49381578", "0.49252507", "0.48534706", "0.4819115", "0.48064002", "0.47601", "0.47519144", "0.4742259", "0.4740057", "0.4727511", "0.47176874", "0.47031915", "0.4700527", "0.4698371", "0.46855637", "0.4634698", "0.46332663", "0.46316...
0.80962306
0
Returns a the lowercase city name of the node's data center.
def get_datacenter_city(self, node): if self._datacenter_cache is None: self.populate_datacenter_cache() location = self._datacenter_cache[node.datacenter_id].location location = location.lower() location = location.split(",")[0] return location
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def data_center_name(self) -> str:\n return pulumi.get(self, \"data_center_name\")", "def data_center_name(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"data_center_name\")", "def data_center_name(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"data_c...
[ "0.74766445", "0.7180771", "0.69038516", "0.69038516", "0.66939473", "0.6678729", "0.6621979", "0.6542636", "0.64575845", "0.6278695", "0.6257993", "0.6257993", "0.6257993", "0.6257993", "0.6257993", "0.6226151", "0.6226151", "0.61920005", "0.614394", "0.614394", "0.6131929",...
0.7814764
0
Adds an node to the inventory and index.
def add_node(self, node): public_ip = [addr.address for addr in node.ipaddresses if addr.is_public][0] dest = public_ip # Add to index self.index[dest] = node.api_id # Inventory: Group by node ID (always a group of 1) self.inventory[node.label] = [dest] # Inventory: Group by datacenter city self.push(self.inventory, self.get_datacenter_city(node), dest) # Inventory: Group by dipslay group self.push(self.inventory, node.display_group, dest)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _add_node(self, node: int) -> None:\r\n self.nodes.add(node)", "def add_node(self, node):", "def add_node(self, node):\n self.nodes.append(node)", "def add_node(self, node):\n self.nodes[node.name] = node\n self.dirty = True", "def add_node(self, node):\n self.nodes.a...
[ "0.7500117", "0.73828864", "0.7321843", "0.7307978", "0.72790575", "0.72646934", "0.72339076", "0.7178008", "0.71437955", "0.71437955", "0.7089215", "0.7021807", "0.6995974", "0.69755816", "0.69561344", "0.69527453", "0.69520944", "0.6948566", "0.69292915", "0.68842506", "0.6...
0.7719779
0
Get variables about a specific host.
def get_host_info(self): if len(self.index) == 0: # Need to load index from cache self.load_index_from_cache() if not self.args.host in self.index: # try updating the cache self.do_api_calls_update_cache() if not self.args.host in self.index: # host might not exist anymore return self.json_format_dict({}, True) node_id = self.index[self.args.host] print "NODE ID %s" % node_id print "INDEX: %s" % self.index node = self.get_node(node_id) node_vars = {} for direct_attr in [ "api_id", "datacenter_id", "label", "display_group", "create_dt", "total_hd", "total_xfer", "total_ram", "status", "alert_cpu_enabled", "alert_cpu_threshold", "alert_diskio_enabled", "alert_diskio_threshold", "alert_bwin_enabled", "alert_bwin_threshold", "alert_bwout_enabled", "alert_bwout_threshold", "alert_bwquota_enabled", "alert_bwquota_threshold", "backup_weekly_daily", "backup_window", "watchdog" ]: node_vars[direct_attr] = getattr(node, direct_attr) node_vars["datacenter_city"] = self.get_datacenter_city(node) node_vars["public_ip"] = [addr.address for addr in node.ipaddresses if addr.is_public][0] return self.json_format_dict(node_vars, True)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_host_variables(self, host):\n vars = {}\n for i in self.parsers:\n vars.update(i.get_host_variables(host))\n return vars", "def get_host_vars(self, hostname, strict=False):\n _host = self.get_inv_host(hostname, strict=strict)\n if not _host:\n retu...
[ "0.79181975", "0.7533325", "0.72101927", "0.7127541", "0.7012544", "0.69147193", "0.6852493", "0.67969316", "0.673507", "0.66360784", "0.65889317", "0.6504869", "0.6504869", "0.64191145", "0.6222618", "0.6220668", "0.6189348", "0.6180824", "0.61642885", "0.6158179", "0.615659...
0.61506575
21
Pushed an element onto an array that may not have been defined in the dict.
def push(self, my_dict, key, element): if key in my_dict: my_dict[key].append(element); else: my_dict[key] = [element]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def push(self, elem):\n pass", "def push(self, new_element):\n self.array.append(new_element)", "def push(self, new_element):\n self.arr.append(new_element)\n self.size += 1", "def __setitem__(self, index, value):\n assert 0 <= index < len(self), \"Array subscript out of ra...
[ "0.61763823", "0.60454845", "0.60098", "0.5906978", "0.5880794", "0.5880467", "0.5862668", "0.58508754", "0.5771033", "0.5766721", "0.5749718", "0.5748016", "0.5746526", "0.57447404", "0.5734783", "0.5690246", "0.5680334", "0.5669741", "0.56696004", "0.5660492", "0.56445444",...
0.6287549
0
Reads the inventory from the cache file and returns it as a JSON object.
def get_inventory_from_cache(self): cache = open(self.cache_path_cache, 'r') json_inventory = cache.read() return json_inventory
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_from_cache(self):\n try:\n with open(self.cache_filename, 'r') as cache:\n json_data = cache.read()\n data = json.loads(json_data)\n except IOError:\n data = {'data': {}, 'inventory': {}}\n\n self.data = data['data']\n self.invent...
[ "0.7557402", "0.7366649", "0.7024034", "0.6800572", "0.6741193", "0.64853036", "0.62057525", "0.6125807", "0.61111367", "0.60826665", "0.60408515", "0.603484", "0.6020536", "0.60187274", "0.6007673", "0.598478", "0.5969202", "0.59221053", "0.5900663", "0.58964336", "0.5871589...
0.88659257
0