query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Sets zero mode parameters
def setZeroModeParameters(self, zmp): if not len(zmp) == len(self.bins): raise IndexError("Mismatch in number of t' bins") for i,pp in enumerate(zmp): self.bins[i].setZeroModeParameters(pp)
[ "def set_model_parameters_to_zero(self):\n\n p = self.get_model_parameters()\n if p is not None:\n for key in p:\n val = p[key]\n if torch.is_tensor(val):\n val.zero_()\n elif type(val) == torch.nn.parameter.Parameter or type(v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize every role in roles and at it to the database
def insert_roles(): roles = { 'Author' : [Permission.WRITE_ARTICLES], 'Admin' : [Permission.WRITE_ARTICLES, Permission.MODIFY_ACCOUNTS, Permission.SEND_INVITATIONS], } default_role = 'Author' for r in roles: role = Role.query.filter_by(name=r).first() if role is None: role = Role(name=r) role.reset_permissions() for perm in roles[r]: role.add_permission(perm) role.default = (role.name == default_role) db.session.add(role) db.session.commit()
[ "def setup_roles(self):\n\t\tif self.data.restricted_roles:\n\t\t\tuser = frappe.get_doc(\"User\", frappe.session.user)\n\t\t\tfor role_name in self.data.restricted_roles:\n\t\t\t\tuser.append(\"roles\", {\"role\": role_name})\n\t\t\t\tif not frappe.db.get_value(\"Role\", role_name):\n\t\t\t\t\tfrappe.get_doc(dict(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates that the VPC connector can be safely removed. Does nothing if 'clear_vpc_connector' is not present in args with value True.
def ValidateClearVpcConnector(service, args): if (service is None or not flags.FlagIsExplicitlySet(args, 'clear_vpc_connector') or not args.clear_vpc_connector): return if flags.FlagIsExplicitlySet(args, 'vpc_egress'): egress = args.vpc_egress elif container_resource.EGRESS_SETTINGS_ANNOTATION in service.template_annotations: egress = service.template_annotations[ container_resource.EGRESS_SETTINGS_ANNOTATION] else: # --vpc-egress flag not specified and egress settings not set on service. return if (egress != container_resource.EGRESS_SETTINGS_ALL and egress != container_resource.EGRESS_SETTINGS_ALL_TRAFFIC): return if console_io.CanPrompt(): console_io.PromptContinue( message='Removing the VPC connector from this service will clear the ' 'VPC egress setting and route outbound traffic to the public internet.', default=False, cancel_on_no=True) else: raise exceptions.ConfigurationError( 'Cannot remove VPC connector with VPC egress set to "{}". Set' ' `--vpc-egress=private-ranges-only` or run this command ' 'interactively and provide confirmation to continue.'.format(egress))
[ "def AddClearVpcNetworkFlags(parser, resource_kind='service'):\n parser.add_argument(\n '--clear-network',\n action='store_true',\n help=(\n 'Disconnect this Cloud Run {kind} from the VPC network it is'\n ' connected to.'.format(kind=resource_kind)\n ),\n )", "def remove_in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function accepts a filename, a data dictionary and lists of prefractions and strains, and writes a file with prefraction rows and strain columns with the value in the corresponding row/column.
def write_heatmap(filename, data, prefractions, strains): with open(filename, 'w') as f: f.write("Genes\t{}\n".format("\t".join(strains))) for pref in prefractions: f.write("{}\t{}\n".format(pref, "\t".join([str(data[pref][strn]) for strn in strains]))) return
[ "def write_data(num, data):\n file_num = \"%05d\" % num\n filename = data_file_statistics + file_num + \".dat\"\n fh = open(filename, mode='w')\n i = 0\n while i < 5:\n j = 0\n while j < 34:\n fh.write(\"%13.5f\" % 0.0)\n j += 1\n i += 1\n fh.write('\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run 'runtimeconfigs waiters create'.
def Run(self, args): waiter_client = util.WaiterClient() messages = util.Messages() waiter_resource = util.ParseWaiterName(args.name, args) project = waiter_resource.projectsId config = waiter_resource.configsId success = messages.EndCondition( cardinality=messages.Cardinality( path=args.success_cardinality_path, number=args.success_cardinality_number, ) ) if args.failure_cardinality_path: failure = messages.EndCondition( cardinality=messages.Cardinality( path=args.failure_cardinality_path, number=args.failure_cardinality_number, ) ) else: failure = None result = waiter_client.Create( messages.RuntimeconfigProjectsConfigsWaitersCreateRequest( parent=util.ConfigPath(project, config), waiter=messages.Waiter( name=waiter_resource.RelativeName(), timeout='{0}s'.format(args.timeout), success=success, failure=failure, ) ) ) log.CreatedResource(waiter_resource) if args.async: # In async mode, we return the current waiter representation. # The waiter resource exists immediately after creation; the # operation resource returned from CreateWaiter only tracks the # waiting process. self._async_resource = waiter_resource request = (waiter_client.client.MESSAGES_MODULE .RuntimeconfigProjectsConfigsWaitersGetRequest( name=waiter_resource.RelativeName())) result = waiter_client.Get(request) else: self._async_resource = None result = util.WaitForWaiter(waiter_resource) if util.IsFailedWaiter(result): self.exit_code = 2 # exit with code 2 if the result waiter failed. return util.FormatWaiter(result)
[ "def generate_runtime_container(self):\n for version in self.versions:\n self.display('docker build -f {}/dockerfiles/{}_{}.d -t {} {}'.format(\n self.tmp, self.runtime, version, 'continuous:{}_{}'.format(self.runtime, version), self.tmp), \"yellow\")\n self.exec('docker ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of people in this classification, filtered by the current context
def getPeople(self): secman = getSecurityManager() #There *has* to be a better way to do this... localPeople = self.getReferences(relationship='classifications_people') #Get the intersection of people referenced to this classification and people within/referenced to the parent classificationPeople = list(set(localPeople) & set(self.aq_parent.getPeople())) #Determine the valid people to show visiblePeople = [] currentDateTime = DateTime() for person in classificationPeople: if currentDateTime >= person.getEffectiveDate() and (currentDateTime < person.getExpirationDate() or person.getExpirationDate() is None): if secman.checkPermission(View, person): visiblePeople.append(person) #Return only the visible people return visiblePeople
[ "def people(self):\n\n if not self.content.get('people'):\n return None\n\n people = OrderedDict(self.content['people'])\n\n query = PersonCollection(object_session(self)).query()\n query = query.filter(Person.id.in_(people.keys()))\n\n result = []\n\n for person...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of people, sorted by SortableName
def getSortedPeople(self): people = self.getPeople() return sorted(people, cmp=lambda x,y: cmp(x.getSortableName(), y.getSortableName()))
[ "def sort_by_name(people):\n return sorted(people, key=get_name)", "def print_by_names():\n print \"\\nSorted by names:\"\n new_contacts = sorted(contacts)\n for i in new_contacts:\n print i + \" : \" + contacts[i]", "def sort_by_name(fathers_of_the_founders):\n sorting = sorted(fathers_of...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve a message from IMAP and return it as an email object
def fetch_message(imap, imap_msg_id): typ, msgdata = imap.fetch(imap_msg_id, '(RFC822)') encoded_msg = msgdata[0][1] return email.message_from_string(encoded_msg)
[ "def email_fetch(imap, uid):\n message = None\n status, response = imap.fetch(str(uid), '(BODY.PEEK[])')\n\n if status != 'OK':\n return status, response\n\n for i in response:\n if isinstance(i, tuple):\n s = i[1]\n if isinstance(s, bytes):\n s = s.dec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display content of a single Note (specified by IMAP message ID)
def show_note(args): imap = connect_to_imap_server(args) msg = fetch_message(imap, args.messageId) print(msg.as_string())
[ "def get_note(self, note_id):\n return self.__get_object('notes', None, note_id)", "def get_note(self, id):\n response = requests.get(self.notes_url, params = {'id':id}, headers = self.headers)\n response = self.__handle_response(response)\n n = response.json()['notes'][0]\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets tgt[key] to src[key] if key in src and is nonempty, else sets it to default
def _set_header(src, tgt, key, default): if key in src and src[key]: tgt[key] = src[key] else: tgt[key] = default
[ "def _remember_source(self, src_key: str, dest_key: str) -> None:\n\n src_map = self.source_map.setdefault(src_key, {})\n src_map[dest_key] = True", "def deepupdate(target, src):\n print(\"Target:\",target)\n print(\"SRC:\",src)\n for k, v in src.items():\n if type(v) == list:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open $EDITOR to edit note_msg
def _edit_note(username, note_msg): # write out a temporary file containing the subject and body # of note_msg filename = "" with tempfile.NamedTemporaryFile(delete=False) as f: temp_note = email.message.Message() temp_note['Subject'] = note_msg['Subject'] temp_note.set_payload(note_msg.get_payload()) f.write(temp_note.as_string()) filename = f.name if len(filename) == 0: exit("Couldn't create temporary file") # launch $EDITOR against temporary file edit_cmd = "vi" if 'EDITOR' in os.environ: edit_cmd = os.environ['EDITOR'] os.system("%s %s" % (edit_cmd, filename)) # read the edited message and remove the temporary file edited_message = "" with open(filename) as f: edited_message = f.read() os.remove(filename) if len(edited_message.strip()) == 0: exit("The edited note was empty - nothing to do!") # return a new message consisting of the edited message merged # with headers from the input message now = now_in_rfc_format() msg = email.message_from_string(edited_message) if 'Subject' not in msg or not msg['Subject']: msg['Subject'] = "Note" msg['From'] = username msg['To'] = username msg['Content-Type'] = "text/html; charset=utf-8" msg['Date'] = now _set_header(note_msg, msg, 'X-Uniform-Type-Identifier', 'com.apple.mail-note') _set_header(note_msg, msg, 'X-Mail-Created-Date', now) _set_header(note_msg, msg, 'X-Universally-Unique-Identifier', str(uuid.uuid4()).upper()) return msg
[ "def open(ctx, note):\n directory = ctx.obj[\"config\"][\"owner\"][\"dir\"]\n note = Note(directory, note)\n click.edit(filename=note.path)", "def _open_note(notes_dir, notes_file, editor):\n _makedir(notes_dir)\n\n editor_cmd = editor + [notes_file]\n try:\n subprocess.run(editor_cmd)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the Manhattan distance + any turn moves needed to put target ahead of current heading
def manhattan_distance_with_heading(current, target): md = abs(current[0] - target[0]) + abs(current[1] - target[1]) if current[2] == 0: # heading north # Since the agent is facing north, "side" here means # whether the target is in a row above or below (or # the same) as the agent. # (Same idea is used if agent is heading south) side = (current[1] - target[1]) if side > 0: md += 2 # target is behind: need to turns to turn around elif side <= 0 and current[0] != target[0]: md += 1 # target is ahead but not directly: just need to turn once # note: if target straight ahead (curr.x == tar.x), no turning required elif current[2] == 1: # heading west # Now the agent is heading west, so "side" means # whether the target is in a column to the left or right # (or the same) as the agent. # (Same idea is used if agent is heading east) side = (current[0] - target[0]) if side < 0: md += 2 # target is behind elif side >= 0 and current[1] != target[1]: md += 1 # target is ahead but not directly elif current[2] == 2: # heading south side = (current[1] - target[1]) if side < 0: md += 2 # target is behind elif side >= 0 and current[0] != target[0]: md += 1 # target is ahead but not directly elif current[2] == 3: # heading east side = (current[0] - target[0]) if side > 0: md += 2 # target is behind elif side <= 0 and current[1] != target[1]: md += 1 # target is ahead but not directly return md
[ "def manhattan_heuristic(pos, problem):\n # print(\"mahattan\")\n return abs(pos[0] - problem.goal_pos[0]) + abs(pos[1] - problem.goal_pos[1])", "def manhattan_distance_to(self, x: int, y: int) -> int:\n return abs(self.location[0] - x) + abs(self.location[1] - y)", "def manhattan_distance_heuristic(no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The 'expected initial states and solution pairs' below are provided as a sanity check, showing what the PlanRouteProblem soluton is expected to produce. Provide the 'initial state' tuple as the argument to test_PRP, and the associate solution list of actions is expected as the result. The test assumes the goals are [(2,3),(3,2)], that the heuristic fn defined in PlanRouteProblem uses the manhattan_distance_with_heading()
def test_PRP(initial): return plan_route((initial[0],initial[1]), initial[2], # Goals: [(2,3),(3,2)], # Allowed locations: [(0,0),(0,1),(0,2),(0,3), (1,0),(1,1),(1,2),(1,3), (2,0), (2,3), (3,0),(3,1),(3,2),(3,3)])
[ "def more_pour_problem(capacities, goal, start=None):\n # your code here\n def pp_is_goal(state):\n return goal in state\n\n def psuccessors(state):\n items = []\n for i in range(0, len(state)):\n if state[i] < capacities[i]:\n tpl = update_tuple(state, i, cap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plan route to nearest location with heading directed toward one of the possible wumpus locations (in goals), then append shoot action.
def plan_shot(current, heading, goals, allowed): if goals and allowed: psp = PlanShotProblem((current[0], current[1], heading), goals, allowed) node = search.astar_search(psp) if node: plan = node.solution() plan.append(action_shoot_str(None)) # HACK: # since the wumpus_alive axiom asserts that a wumpus is no longer alive # when on the previous round we perceived a scream, we # need to enforce waiting so that itme elapses and knowledge of # "dead wumpus" can then be inferred... plan.append(action_wait_str(None)) return plan # no route can be found, return empty list return []
[ "def move_arm_a_to_b(goal): #move very short distance\n\n rospy.loginfo('goal')\n\n waypoints = []\n wpose = group.get_current_pose().pose\n wpose.position.x += 0.0001\n waypoints.append(copy.deepcopy(wpose))\n wpose.position.x = goal[0]\n wpose.position.y = goal[1] # First move up (z)\n wp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The 'expected initial states and solution pairs' below are provided as a sanity check, showing what the PlanShotProblem soluton is expected to produce. Provide the 'initial state' tuple as the argumetn to test_PRP, and the associate solution list of actions is expected as the result. The test assumes the goals are [(2,3),(3,2)], that the heuristic fn defined in PlanShotProblem uses the manhattan_distance_with_heading()
def test_PSP(initial = (0,0,3)): return plan_shot((initial[0],initial[1]), initial[2], # Goals: [(2,3),(3,2)], # Allowed locations: [(0,0),(0,1),(0,2),(0,3), (1,0),(1,1),(1,2),(1,3), (2,0), (2,3), (3,0),(3,1),(3,2),(3,3)])
[ "def more_pour_problem(capacities, goal, start=None):\n # your code here\n def pp_is_goal(state):\n return goal in state\n\n def psuccessors(state):\n items = []\n for i in range(0, len(state)):\n if state[i] < capacities[i]:\n tpl = update_tuple(state, i, cap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates pandas dataframe with information about libraries from specified platform from Libraries.io.
def get_lib_info(self, libraries, platform, save_to=None): libs_info = pd.DataFrame() projects_path = os.path.join(self._librariesio_path, projects_filename) self._log.info("Looking for libraries info...") for chunk in pd.read_csv(projects_path, chunksize=LibrariesIOFetcher.CHUNKSIZE, index_col=False, dtype=object): for lib_name in libraries: indexes = (chunk["Name"] == lib_name) if platform != "": indexes = indexes & (chunk["Platform"] == platform) if libraries[lib_name] != "": indexes = indexes & ((chunk["Repository URL"] == libraries[lib_name]) | pd.isnull(chunk["Repository URL"])) res = chunk[indexes] if len(res) > 0: self._log.info("%s library entry is found!", lib_name) libs_info = pd.concat([libs_info, res]) if save_to: libs_info.to_csv(save_to, index=False) return libs_info
[ "def createLibraryImportMenu(self):\n from . import Tools\n\n sel_env = Tools.getEnvironment()\n\n file = \"platformio_boards.json\"\n data = self.getTemplateMenu(file_name=file, user_path=True)\n data = json.loads(data)\n\n # check current platform\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates pandas dataframe with all information about dependent repositories from libraries.
def get_dependent_reps(self, libs_info, save_to=None): self._log.info("Creating list of dependent repos...") if hasattr(libs_info["ID"], "tolist"): lib_id2name = dict(zip(libs_info["ID"].tolist(), libs_info["Name"].tolist())) else: lib_id2name = {libs_info["ID"]: libs_info["Name"]} pd_result = [] dependencies_path = os.path.join(self._librariesio_path, dependencies_filename) for chunk in progress_bar(pd.read_csv(dependencies_path, chunksize=LibrariesIOFetcher.CHUNKSIZE, index_col=False), self._log, expected_size=100): for lib_id in lib_id2name: res = chunk[chunk["Dependency Project ID"] == int(lib_id)] if len(res) > 0: pd_result.append(res) pd_result = pd.concat(pd_result) pd_result["url"] = "https://" + \ pd_result["Host Type"].map(LibrariesIOFetcher.HOST2LINK) + \ pd_result["Repository Name with Owner"] if save_to: pd_result.to_csv(save_to, index=False) return pd_result
[ "def repo_information(self):\n\n data = [[repo.git_dir,\n repo.repo.branches,\n repo.repo.bare,\n repo.repo.remotes,\n repo.repo.description,\n repo.repo.references,\n repo.repo.heads,\n repo.repo....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract and save dependent urls of dependent repositories.
def get_dependent_rep_urls(self, libraries, platform, output): libraries_info = self.get_lib_info(libraries, platform) dependent_reps = self.get_dependent_reps(libraries_info) self.save_urls_only(dependent_reps, libraries_info, save_to=output)
[ "def get_dependent_reps(self, libs_info, save_to=None):\n self._log.info(\"Creating list of dependent repos...\")\n if hasattr(libs_info[\"ID\"], \"tolist\"):\n lib_id2name = dict(zip(libs_info[\"ID\"].tolist(), libs_info[\"Name\"].tolist()))\n else:\n lib_id2name = {libs_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From uvmodel.py for binning velocity field vector data (for both u and v components of velocity) given xyz position and the x and y bins, return the location (xb,yb) and the new component of velocity data (zb_mean)
def sh_bindata(x, y, z, xbins, ybins): ix=np.digitize(x,xbins) iy=np.digitize(y,ybins) xb=0.5*(xbins[:-1]+xbins[1:]) # bin x centers yb=0.5*(ybins[:-1]+ybins[1:]) # bin y centers zb_mean=np.empty((len(xbins)-1,len(ybins)-1),dtype=z.dtype) for iix in range(1,len(xbins)): for iiy in range(1,len(ybins)): k,=np.where((ix==iix) & (iy==iiy)) zb_mean[iix-1,iiy-1]=np.mean(z[k]) return xb,yb,zb_mean
[ "def bin_YbyX (Vy,Vx,bins=[],bin_min=0,bin_max=1,bin_spc=1,wgt=[],keep_time=False):\n #----------------------------------------------------------------------------\n # use min, max, and spc (i.e. stride) to define bins \n nbin = np.round( ( bin_max - bin_min + bin_spc )/bin_spc ).astype(np.int)\n bins ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return array shrunk to fit a specified shape by triming or averaging. a = shrink(array, shape) array is an numpy ndarray, and shape is a tuple (e.g., from array.shape). a is the input array shrunk such that its maximum dimensions are given by shape. If shape has more dimensions than array, the last dimensions of shape are fit. as, bs = shrink(a, b) If the second argument is also an array, both a and b are shrunk to the dimensions of each other. The input arrays must have the same number of dimensions, and the resulting arrays will have the same shape.
def shrink(a,b): if isinstance(b, np.ndarray): if not len(a.shape) == len(b.shape): raise Exception() 'input arrays must have the same number of dimensions' a = shrink(a,b.shape) b = shrink(b,a.shape) return (a, b) if isinstance(b, int): b = (b,) if len(a.shape) == 1: # 1D array is a special case dim = b[-1] while a.shape[0] > dim: # only shrink a if (dim - a.shape[0]) >= 2: # trim off edges evenly a = a[1:-1] else: # or average adjacent cells a = 0.5*(a[1:] + a[:-1]) else: for dim_idx in range(-(len(a.shape)),0): dim = b[dim_idx] a = a.swapaxes(0,dim_idx) # put working dim first while a.shape[0] > dim: # only shrink a if (a.shape[0] - dim) >= 2: # trim off edges evenly a = a[1:-1,:] if (a.shape[0] - dim) == 1: # or average adjacent cells a = 0.5*(a[1:,:] + a[:-1,:]) a = a.swapaxes(0,dim_idx) # swap working dim back return a
[ "def _get_shrunk_array(self, f, ind, shrink_size=(1.0, 1.0, 1.0)):\n dim = f[ind].shape\n if (f[ind].ndim == 2):\n return np.array(f[ind][:int(round(shrink_size[0] * dim[0])),\n :int(round(shrink_size[1] * dim[1]))])\n elif (f[ind].ndim == 3):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From Rich Signell's blog, plots ROMS velocity field for a single timepoint
def plot_ROMS_velocity_field(): url='http://tds.marine.rutgers.edu/thredds/dodsC/roms/doppio/2017_da/his/runs/History_RUN_2018-05-15T00:00:00Z' nc = netCDF4.Dataset(url) lon_rho = nc.variables['lon_rho'][:] lat_rho = nc.variables['lat_rho'][:] #bbox = [-71., -63.0, 41., 44.] #GoM bbox = [-67.35, -64.72, 44.23, 45.33] #BoF i0,i1,j0,j1 = bbox2ij(lon_rho,lat_rho,bbox) tvar = nc.variables['ocean_time'] # usual ROMS #tvar = nc.variables['time'] # USGS COAWST FMRC Aggregation h = nc.variables['h'][j0:j1, i0:i1] lon = lon_rho[j0:j1, i0:i1] lat = lat_rho[j0:j1, i0:i1] land_mask = 1 - nc.variables['mask_rho'][j0:j1, i0:i1] #start=datetime.datetime(2012,1,1,0,0) #start = datetime.datetime.utcnow() #tidx = netCDF4.date2index(start,tvar,select='nearest') # get nearest index to now tidx = -1 #timestr = netCDF4.num2date(stats.tvar[tidx], stats.tvar.units).strftime('%b %d, %Y %H:%M') #BRING BACK zlev = -1 # last layer is surface layer in ROMS u = nc.variables['u'][tidx, zlev, j0:j1, i0:(i1-1)] v = nc.variables['v'][tidx, zlev, j0:(j1-1), i0:i1] lon_u = nc.variables['lon_u'][ j0:j1, i0:(i1-1)] lon_v = nc.variables['lon_v'][ j0:(j1-1), i0:i1] lat_u = nc.variables['lat_u'][ j0:j1, i0:(i1-1)] lat_v = nc.variables['lat_v'][ j0:(j1-1), i0:i1] lon=lon_rho[(j0+1):(j1-1), (i0+1):(i1-1)] lat=lat_rho[(j0+1):(j1-1), (i0+1):(i1-1)] mask = 1 - nc.variables['mask_rho'][(j0+1):(j1-1), (i0+1):(i1-1)] ang = nc.variables['angle'][(j0+1):(j1-1), (i0+1):(i1-1)] # average u,v to central rho points u = shrink(u, mask.shape) v = shrink(v, mask.shape) # rotate grid_oriented u,v to east/west u,v u, v = rot2d(u, v, ang) basemap = Basemap(projection='merc',llcrnrlat=44,urcrnrlat=46,llcrnrlon=-68,urcrnrlon=-64, lat_ts=30,resolution='i') fig1 = plt.figure(figsize=(10,8)) ax = fig1.add_subplot(111) basemap.drawcoastlines() basemap.fillcontinents() basemap.drawcountries() basemap.drawstates() x_rho, y_rho = basemap(lon,lat) spd = np.sqrt(u*u + v*v) #h1 = basemap.pcolormesh(x_rho, y_rho, spd, vmin=0, vmax=1.0,shading='nearest') #add color nsub=2 scale=0.03 basemap.quiver(x_rho[::nsub,::nsub],y_rho[::nsub,::nsub],u[::nsub,::nsub],v[::nsub,::nsub],scale=1.0/scale, zorder=1e35, width=0.002) #basemap.colorbar(h1,location='right',pad='5%') #add colorbar title('COAWST Surface Current: ROMS Velocity Field') #BRING BACK plt.savefig('ROMS_velocity_field_BoF05152018.png')
[ "def PlotVoltage(cell):\n # check before if \"recordAll\" was TRUE\n t = np.asarray(cell.record['time']) * .001\n\n v = np.asarray(cell.record['voltage']) * .001\n plt.plot(t, v)\n plt.xlabel('Time (s)')\n plt.ylabel('Voltage (mV)')", "def VelocityChart(request):\n kwargs = {\n 'status...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the timepoint of this ScheduleResourceAttributes.
def timepoint(self, timepoint): self._timepoint = timepoint
[ "def setTimePoints(self, timepoints):\n\t\tself.timePoints = timepoints", "def setStartTime(self, startTime):\n self.startTime = startTime", "def set_schedule(self, schedule):\r\n arg_str = p2e._base._util._convert_args_to_string(\"set.object.schedule\", self._object._eco_id, schedule)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the stop_sequence of this ScheduleResourceAttributes.
def stop_sequence(self, stop_sequence): self._stop_sequence = stop_sequence
[ "def stop(self, stop: SourceLocation):\n if stop is None:\n raise ValueError(\"Invalid value for `stop`, must not be `None`\") # noqa: E501\n\n self._stop = stop", "def setStopCondition(self, val):\r\n self.__scl.acquire()\r\n self.__stopCondition = val\r\n self.__sc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the pickup_type of this ScheduleResourceAttributes.
def pickup_type(self, pickup_type): self._pickup_type = pickup_type
[ "def pickup_date(self, pickup_date):\n\n self._pickup_date = pickup_date", "def setTripType(self, tripType: TripType) -> None:\n self.tripType = tripType", "def proprietor_type(self, proprietor_type: str):\n\n self._proprietor_type = proprietor_type", "def set_pick_up_time(self, pick_up_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the drop_off_type of this ScheduleResourceAttributes.
def drop_off_type(self, drop_off_type): self._drop_off_type = drop_off_type
[ "def disruption_type(self, disruption_type):\n\n self._disruption_type = disruption_type", "def _set_drop(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n t = YANGDynClass(v,base=YANGBool, default=YANGBool(\"false\"), is_leaf=True, yang_name=\"drop\", parent=sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the direction_id of this ScheduleResourceAttributes.
def direction_id(self, direction_id): self._direction_id = direction_id
[ "def route_direction(self, route_direction):\n\n self._route_direction = route_direction", "def set_direction(self, direction):", "def requested_route_direction(self, requested_route_direction):\n\n self._requested_route_direction = requested_route_direction", "def set_direction(self, direction)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the departure_time of this ScheduleResourceAttributes.
def departure_time(self, departure_time): self._departure_time = departure_time
[ "def departure_time(self, departure_time: int):\n\n self._departure_time = departure_time", "def departure(self, departureTime):\n self._departure = departureTime", "def add_departure(self, departure_date, departure_time):\r\n self.departure_date = departure_date\r\n self.departure_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the arrival_time of this ScheduleResourceAttributes.
def arrival_time(self, arrival_time): self._arrival_time = arrival_time
[ "def arrival(self, arrivalTime):\n self._arrival = arrivalTime", "def arrive_time(self, arrive_time: int):\n\n self._arrive_time = arrive_time", "def scheduled_arrival_time_ms(self, scheduled_arrival_time_ms):\n if scheduled_arrival_time_ms is None:\n raise ValueError(\"Invalid v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns dynamic enlargement factor.
def dynamic_enlargement_factor(self): return self._dynamic_enlargement_factor
[ "def maximum_stretch_ratio(self):\n return 1.0 + self.tensile_strength / self.elasticity", "def PaperScale(self) -> float:", "def scale(self):\n return self._moyal_bijector.scale", "def SpreadFactor(self): \n return 4.5", "def getReductionRatio(self) -> retval:\n ...", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the ellipsoid update gap used in the algorithm (see
def ellipsoid_update_gap(self): return self._ellipsoid_update_gap
[ "def gap(self) -> float:\n pass", "def set_ellipsoid_update_gap(self, ellipsoid_update_gap=100):\n ellipsoid_update_gap = int(ellipsoid_update_gap)\n if ellipsoid_update_gap <= 1:\n raise ValueError('Ellipsoid update gap must exceed 1.')\n self._ellipsoid_update_gap = ellips...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the enlargement factor used in the algorithm (see
def enlargement_factor(self): return self._enlargement_factor
[ "def dynamic_enlargement_factor(self):\n return self._dynamic_enlargement_factor", "def maximum_stretch_ratio(self):\n return 1.0 + self.tensile_strength / self.elasticity", "def enlarge(n):\r\n return n*100", "def SpreadFactor(self): \n return 4.5", "def threshold_factor_comp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of rejection sample used in the algorithm (see
def n_rejection_samples(self): return self._n_rejection_samples
[ "def rejection_sampling(self, num_samples):\n accepted_count = 0\n trial_count = 0\n accepted_samples = []\n distances = []\n fixed_dataset = DataSet('Fixed Data')\n sim_dataset = DataSet('Simulated Data')\n fixed_dataset.add_points(targets=self.data, summary_stats=s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the number of rejection samples to take, which will be assigned weights and ultimately produce a set of posterior samples.
def set_n_rejection_samples(self, rejection_samples=200): if rejection_samples < 0: raise ValueError('Must have non-negative rejection samples.') self._n_rejection_samples = rejection_samples
[ "def rejection_sampling(self, num_samples):\n accepted_count = 0\n trial_count = 0\n accepted_samples = []\n distances = []\n fixed_dataset = DataSet('Fixed Data')\n sim_dataset = DataSet('Simulated Data')\n fixed_dataset.add_points(targets=self.data, summary_stats=s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the frequency with which the minimum volume ellipsoid is reestimated as part of the nested rejection sampling algorithm. A higher rate of this parameter means each sample will be more efficiently produced, yet the cost of recomputing the ellipsoid may mean it is better to update this not each iteration instead, with gaps of ``ellipsoid_update_gap`` between each update. By default, the ellipse is updated every 100 iterations.
def set_ellipsoid_update_gap(self, ellipsoid_update_gap=100): ellipsoid_update_gap = int(ellipsoid_update_gap) if ellipsoid_update_gap <= 1: raise ValueError('Ellipsoid update gap must exceed 1.') self._ellipsoid_update_gap = ellipsoid_update_gap
[ "def set_ellipsoid(self, ellipsoid):\n if not isinstance(ellipsoid, (list, tuple)):\n try:\n self.ELLIPSOID = ELLIPSOIDS[ellipsoid]\n self.ellipsoid_key = ellipsoid\n except KeyError:\n raise Exception(\n \"Invalid ellipsoi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws from the enlarged bounding ellipsoid.
def _ellipsoid_sample(self, enlargement_factor, A, centroid, n_points): if n_points > 1: return self._draw_from_ellipsoid( np.linalg.inv((1 / enlargement_factor) * A), centroid, n_points) else: return self._draw_from_ellipsoid( np.linalg.inv((1 / enlargement_factor) * A), centroid, 1)[0]
[ "def draw(self,pic):\n # By solving the boundary equation, we have x=a**2/sqrt(a**2+b**2)\n # print \"Drawing an ellipse\" \n self.points=[] \n if self.a>self.b:\n # first go from x axis\n points=self._standardDraw(pic,actuallyDraw=True)\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The hyperparameter vector is ``[ active points, rejection samples, enlargement factor, ellipsoid update gap, dynamic enlargement factor, alpha]``.
def set_hyper_parameters(self, x): self.set_n_active_points(x[0]) self.set_n_rejection_samples(x[1]) self.set_enlargement_factor(x[2]) self.set_ellipsoid_update_gap(x[3]) self.set_dynamic_enlargement_factor(x[4]) self.set_alpha(x[5])
[ "def extractHyperParameters(self):\n return(np.array(self.hypers))", "def setKernelParam(self, alpha, scale) -> None:\n ...", "def params(self):\n\t\treturn {\"k\": self.__k, \"alpha\": self.__alpha}", "def sample_hyperparameters(self):\n\n # This stepsize works for Eve corpus (not much s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a mask of detected table from detected table bounding box coordinates.
def get_mask_from_bounding_box(bounding_box_coordinates,shape): #unwrap bouding box coordinates x,y,w,h = bounding_box_coordinates #create blank image with corresponding shape blank_image = np.zeros(shape, np.uint8) #create corrected mask corrected_mask = cv2.rectangle(blank_image,(x,y),(x+w,y+h),(255,255,255),-1) return corrected_mask
[ "def fixMasks(image, table_mask, column_mask):\r\n table_mask = table_mask.reshape(1024,1024).astype(np.uint8)\r\n column_mask = column_mask.reshape(1024,1024).astype(np.uint8)\r\n \r\n #get contours of the mask to get number of tables\r\n contours, table_heirarchy = cv2.findContours(table_mask, cv2....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute difference between element and next element in a list and return elements where difference is maximum. For instance if we take the list [1,2,3,4,10,12,15], we will compute the list [1,1,1,6,2,3] and the function will return (4,10) representing the maximum gap.
def get_biggest_gap_index(elements_list): #compute list of difference between element and next element steps = [x-y for y,x in zip(elements_list,elements_list[1:])] #Get index where element has biggest gap with next element index_where_biggest_gap = np.where(steps==max(steps))[0][0] #return element and next element return elements_list[index_where_biggest_gap], elements_list[index_where_biggest_gap+1]
[ "def nextGreaterElements(self, nums):\r\n n = len(nums)\r\n res = [-1] * n\r\n s = []\r\n\r\n for _ in range(2):\r\n for i, num in enumerate(nums):\r\n while s and num > nums[s[-1]]:\r\n res[s.pop()] = num\r\n s.append(i)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute sum of a matrix (mask) following an axis, get indexes where sum is higher than 80% of the maximum then find biggest submatrix within detected borders. If axis=1, columns will be removed (else, lines will be removed)
def get_sub_mask_by_removing_overfilled_borders(mask,axis,limit_ratio=0.8): #Compute sum over the axis summed_on_axis = mask.sum(axis=axis) #Get maximum value maximum_value = summed_on_axis.max() #Find lines or columns where sum is over 80% of maximum sum. indexes = np.where(summed_on_axis>=maximum_value*limit_ratio)[0] #Use get_biggest_gap_index to get biggest submatrix within matrix by setting excluded elements to 0 # # ______________ ________ # _______ ____ __________ # _______________________ # --> ____ _____ ___ # Detected | __ _ ________ # Submatrix| ______ # --> ______ ______ _________ # __ _______________ ____ # # start, end = get_biggest_gap_index(indexes) if axis == 1: mask[:start]=0 mask[end:] = 0 elif axis == 0: mask[:, :start]=0 mask[:, end:] = 0 return mask
[ "def DownsampleBoundsMatrix(bm, indices, maxThresh=4.0):\n nPts = bm.shape[0]\n k = numpy.zeros(nPts, numpy.int0)\n for idx in indices:\n k[idx] = 1\n for i in indices:\n row = bm[i]\n for j in range(i + 1, nPts):\n if not k[j] and row[j] < maxThresh:\n k[j] = 1\n keep = numpy.nonzero(k)[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method fetches the genome sequence based on genomeid from PATRIC
def getGenomeSequence(genomeId): r = urllib.urlopen(PatricURL+genomeId+'/'+genomeId+'.fna').read() soup = BeautifulSoup(r) #print type(soup) genomeSequence = soup.prettify().split('| '+genomeId+']')[1] return genomeSequence.replace('\n', '')
[ "def get_sequence(seq_id, anno_db, genome, seq_type='CDS', exon_split='', flank_len=0):\n def get_sequence_from_genome_by_anno_db(df, genome):\n tmp_seq = genome[df['seq_name']]\n tmp_seq_start = df['seq_start']-1\n tmp_seq_end = df['seq_end']\n df['seq'] = tmp_seq[tmp_seq_start:tmp_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method gets the features for a particular genomeId frfom PATRIC
def getFeaturesForGenome(genomeId, CDS_ONLY): data_table = pd.read_table(PatricURL +genomeId+'/'+genomeId+'.PATRIC.features.tab') print data_table.shape if CDS_ONLY: return data_table[(data_table.feature_type == 'CDS')] else: return data_table
[ "def get_features(self, ctx, ref, feature_id_list):\n # ctx is the context object\n # return variables are: returnVal\n #BEGIN get_features\n ga = GenomeAnnotationAPI_local(self.services, ctx['token'], ref)\n returnVal = ga.get_features(feature_id_list)\n #END get_features\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Split scope and key. The first scope will be split from key.
def split_scope_key(key): split_index = key.find('.') if split_index != -1: return key[:split_index], key[split_index + 1:] else: return None, key
[ "def split_scoped_hparams(scopes, merged_hparams):\n split_values = dict([(scope, dict()) for scope in scopes])\n merged_values = merged_hparams.values()\n for scoped_key, value in six.iteritems(merged_values):\n scope = scoped_key.split(\".\")[0]\n key = scoped_key[len(scope) + 1:]\n split_values[scope...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add children for a registry. The ``registry`` will be added as children based on its scope. The parent registry could build objects from children registry.
def _add_children(self, registry): assert isinstance(registry, Registry) assert registry.scope is not None assert registry.scope not in self.children, \ f'scope {registry.scope} exists in {self.name} registry' self.children[registry.scope] = registry
[ "def add_children(self, *children):\n for child in children:\n self.children.append(child)", "def add_children(self, new_children):\n self.children = self.get_children() + new_children", "def append_children(parent, *children):\n for c in children:\n parent.add_child(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The method to get the public_views
def get_public_views(self): return self.__public_views
[ "def get_views(name):", "def get_views():\n views = []\n rnetworkview = requests.get(PAYLOAD['url'] + \"networkview?\",\n auth=(PAYLOAD['username'],\n PAYLOAD['password']),\n verify=False)\n rutfnetworkview...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The method to set the value to public_views
def set_public_views(self, public_views): if public_views is not None and not isinstance(public_views, str): raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: public_views EXPECTED TYPE: str', None, None) self.__public_views = public_views self.__key_modified['public_views'] = 1
[ "def get_public_views(self):\n\n\t\treturn self.__public_views", "def setView(self, v):\n self.view = v", "def set_Public(self, value):\n super(UpdateTicketInputSet, self)._set_input('Public', value)", "def views(self, value=None):\n if value is not None:\n if value in config.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The method to get the other_users_views
def get_other_users_views(self): return self.__other_users_views
[ "def set_other_users_views(self, other_users_views):\n\n\t\tif other_users_views is not None and not isinstance(other_users_views, str):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: other_users_views EXPECTED TYPE: str', None, None)\n\t\t\n\t\tself.__other_users_views = other_users_views\n\t\tself.__k...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The method to set the value to other_users_views
def set_other_users_views(self, other_users_views): if other_users_views is not None and not isinstance(other_users_views, str): raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: other_users_views EXPECTED TYPE: str', None, None) self.__other_users_views = other_users_views self.__key_modified['other_users_views'] = 1
[ "def get_other_users_views(self):\n\n\t\treturn self.__other_users_views", "def custom_view(self, value: discord.ui.View | None):\n self._custom_view = value", "def set_view_rights(user, live_calendar, department_view, employee_view):\n\n # Delete old view rights for this live calendar\n oldDepartm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The method to get the shared_with_me
def get_shared_with_me(self): return self.__shared_with_me
[ "def shared(self):\n if \"shared\" in self._prop_dict:\n if isinstance(self._prop_dict[\"shared\"], OneDriveObjectBase):\n return self._prop_dict[\"shared\"]\n else :\n self._prop_dict[\"shared\"] = Shared(self._prop_dict[\"shared\"])\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The method to set the value to shared_with_me
def set_shared_with_me(self, shared_with_me): if shared_with_me is not None and not isinstance(shared_with_me, str): raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: shared_with_me EXPECTED TYPE: str', None, None) self.__shared_with_me = shared_with_me self.__key_modified['shared_with_me'] = 1
[ "def __set__(self, instance, value):\n instance.__dict__[self.name] = value", "def set_shared_muse_instance(muse_instance):\n global _shared_muse_instance\n _shared_muse_instance = muse_instance", "def at_set(self, new_value):\r\n pass", "def shared(self, shared):\n if shared is Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The method to get the created_by_me
def get_created_by_me(self): return self.__created_by_me
[ "def _get_createdBy(self) -> \"adsk::core::Ptr< adsk::core::User >\" :\n return _core.DataFile__get_createdBy(self)", "def created_by_user_id(self) -> int:\n return pulumi.get(self, \"created_by_user_id\")", "def get_creator_id(self):\n\n\t\treturn self.__creator_id", "def set_created_by(self, c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function obfuscates the text parsed into the text argument in the
def obfuscate(text: str) -> str: if type(text) != str: # Here error checking is handled print('Please enter a string as an argument') return None lowertext = text.lower() text_array = list(lowertext.split()) cypher = {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e', 'e': 'f', 'f': 'g', 'g': 'h', 'h': 'i', 'i': 'j', 'j': 'k', 'k': 'l', 'l': 'm', 'm': 'n', 'n': 'o', 'o': 'p', 'p': 'q', 'q': 'r', 'r': 's', 's': 't', 't': 'u', 'u': 'v', 'v': 'w', 'w': 'x', 'x': 'y', 'y': 'z', 'z': 'a', 'A': 'B', 'B': 'C', 'C': 'D', 'D': 'E', 'E': 'F', 'F': 'G', 'G': 'H', 'H': 'I', 'I': 'J', 'J': 'K', 'K': 'L', 'L': 'M', 'M': 'N', 'N': 'O', 'O': 'P', 'P': 'Q', 'Q': 'R', 'R': 'S', 'S': 'T', 'T': 'U', 'U': 'V', 'V': 'W', 'W': 'X', 'X': 'Y', 'Y': 'Z', 'Z': 'A'} alphabet = 'abcdefghijklmnopqrstuvwxyz' upperalphabet = alphabet.capitalize() # Here the word 'and' is replaced with 'the' and 'the' with 'and' for index in range(len(text_array)): if text_array[index] == 'the': text_array[index] = 'and' elif text_array[index] == 'and': text_array[index] = 'the' # Here a string to handle the upper method is created newstring1 = str(''.join(text_array)) newstring2 = '' # Here every third value is turned into an uppercase value for i in range(1, len(newstring1)+1): if i % 3 == 0: newstring2 += newstring1[i-1].upper() else: newstring2 += newstring1[i-1].lower() newlist = newstring2.split() for i in range(1, len(newlist)): # Here every fifth word is reversed if i % 5 == 0 and i != 0: newlist[i-1] = newlist[i-1][::-1] for word in range(0, len(newlist)): if word % 2 == 0 and word != 0: charlist = list(newlist[word-1]) wordhold = '' for char in charlist: wordhold += cypher[char] newlist[word-1] = wordhold finalstring = ' '.join(newlist) return finalstring
[ "def preprocess(text):\n text = normalize_unicode(text)\n text = remove_newline(text)\n text = text.lower()\n text = decontracted(text)\n text = replace_negative(text)\n text = removePunctuations(text)\n text = remove_number(text)\n text = remove_space(text)\n text = removeArticlesAndPron...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns All tasks from db in a list
def get_all_tasks(): task_list = Task.objects.all().values("name") tasks = list(task_list) task_list = [task["name"] for task in tasks] return task_list
[ "def get_tasks(db, user_id = None):\n\tc = db.cursor()\n\tif user_id:\n\t\tquery = \"\"\"SELECT * FROM Tasks WHERE user_id = ?\"\"\"\n\t\tc.execute(query, (user_id, ))\t\n\telse:\n\t\tquery = \"\"\"SELECT * FROM Tasks\"\"\"\n\t\tc.execute(query)\n\ttasks = []\n\trows = c.fetchall()\n\tfor row in rows:\n\t\tfields =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns All file ids from db in a list
def get_all_file_ids(): id_list = Score.objects.all().values("file_id") return id_list
[ "def extract_file_ids(file_path):\n with open(file_path, \"r\") as f:\n content = f.read()\n\n ids = ID_RE.finditer(content)\n return [id.group(1) for id in ids]", "def Retrieve_NP_IDs(sqlite_file,table_name,id_column = \"structure_id\"):\n # Connecting to the database file\n conn, c = Sql.C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takse task_id and returns all tests to this task
def get_task_tests(task_id): test_list = Test.objects.filter(task_id=task_id) return test_list
[ "def test_get_tasks_for_project(self):\n pass", "def test_get_subtasks_for_task(self):\n pass", "def test_get_task_instances(self):\n pass", "def test_get_tasks_for_section(self):\n pass", "def test_get_tasks_for_user_task_list(self):\n pass", "def test_get_tasks_for_tag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a subframe with outline, using QGridLayout.
def create_sub_frame(self): frame = QtWidgets.QFrame(parent=self) frame.setLineWidth(1) frame.setMidLineWidth(1) frame.setFrameStyle(QtWidgets.QFrame.Box | QtWidgets.QFrame.Raised) lay = QtWidgets.QGridLayout(frame) lay.setContentsMargins(0, 0, 0, 0) frame.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) return frame, lay
[ "def _configureFrame(self, layout):\n\n layout.addWidget(self._leftFrame, 0, 0, 1, 1)\n layout.addWidget(self._rightFrame, 0, 1, 1, 1)\n layout.setColumnStretch(0, 3)\n layout.setColumnStretch(1, 2)\n self.setLayout(layout)\n self.adjustSize()", "def create_fig(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the training dataset, test dataset and number of labels.
def train_test() -> Tuple[TextClassificationDataset, TextClassificationDataset, int]: train_examples, test_examples = datasets.IMDB.splits( text_field=data.Field(lower=False, sequential=False), label_field=data.Field(sequential=False, is_target=True) ) def dataset(examples: data.dataset.Dataset) -> TextClassificationDataset: return TextClassificationDataset( texts=[example.text for example in examples], labels=[float(example.label == 'pos') for example in examples] ) return dataset(train_examples), dataset(test_examples), 2
[ "def read_dataset():\n\ttrain_data = np.genfromtxt('train_data.txt', dtype=int, delimiter=',')\n\ttrain_labels = np.genfromtxt('train_labels.txt', dtype=int, delimiter=',')\n\ttest_data = np.genfromtxt('test_data.txt', dtype=int, delimiter=',')\n\ttest_labels = np.genfromtxt('test_labels.txt', dtype=int, delimiter=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of all videos available in the directory
def list_videos(): videos = [f for f in listdir(HOST_VIDEOS_DIR) if path.isfile(path.join(HOST_VIDEOS_DIR, f))] return videos
[ "def list_ucf_videos():\n global _VIDEO_LIST\n if not _VIDEO_LIST:\n #index = request.urlopen(UCF_ROOT, context=unverified_context).read().decode('utf-8')\n index = request.urlopen(UCF_ROOT).read().decode('utf-8')\n videos = re.findall('(v_[\\w_]+\\.avi)', index)\n _VIDEO_LIST = sorted(set(videos))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This test compares the solution from the MDP interface with the WindyGridWorld's solution.
def test_windy_grid_world_value_iteration(self): mdp = WindyGridWorldMDP() q_values = mdp.optimal_q_values # keep arguments due to expected q_star expected_q_values = np.array([ [-88.97864878, -88.97864878, -88.97864878, -88.86732201], [-88.86732201, -88.86732201, -88.97864878, -88.75487073], [-88.75487073, -88.75487073, -88.86732201, -88.64128358], [-88.64128358, -88.64128358, -88.75487073, -88.52654908], [-88.52654908, -88.52654908, -88.64128358, -88.41065565], [-88.41065565, -88.41065565, -88.52654908, -88.29359158], [-88.29359158, -88.29359158, -88.41065565, -88.17534503], [-88.17534503, -88.17534503, -88.29359158, -88.05590408], [-88.05590408, -88.05590408, -88.17534503, -87.93525666], [-87.93525666, -87.81339058, -88.05590408, -87.93525666], [-88.97864878, -88.97864878, -88.97864878, -88.86732201], [-88.86732201, -88.86732201, -88.97864878, -88.75487073], [-88.75487073, -88.75487073, -88.86732201, -88.64128358], [-88.64128358, -88.64128358, -88.75487073, -88.52654908], [-88.52654908, -88.52654908, -88.64128358, -88.41065565], [-88.41065565, -88.41065565, -88.52654908, -88.29359158], [-88.29359158, -88.29359158, -88.41065565, -88.17534503], [-88.17534503, -88.17534503, -88.29359158, -88.05590408], [-88.05590408, -88.05590408, -88.17534503, -87.93525666], [-87.93525666, -87.69029353, -88.05590408, -87.81339058], [-88.97864878, -88.97864878, -88.97864878, -88.86732201], [-88.86732201, -88.86732201, -88.97864878, -88.75487073], [-88.75487073, -88.75487073, -88.86732201, -88.64128358], [-88.64128358, -88.64128358, -88.75487073, -88.52654908], [-88.52654908, -88.52654908, -88.64128358, -88.41065565], [-88.41065565, -88.41065565, -88.52654908, -88.29359158], [-88.29359158, -88.29359158, -88.41065565, -88.17534503], [-88.17534503, -88.17534503, -88.29359158, -88.05590408], [-88.05590408, -87.93525666, -88.17534503, -87.81339058], [-87.81339058, -87.56595307, -87.93525666, -87.69029353], [-88.97864878, -88.97864878, -88.97864878, -88.86732201], [-88.86732201, -88.86732201, -88.97864878, -88.75487073], [-88.75487073, -88.75487073, -88.86732201, -88.64128358], [-88.64128358, -88.64128358, -88.75487073, -88.52654908], [-88.52654908, -88.52654908, -88.64128358, -88.41065565], [-88.41065565, -88.41065565, -88.52654908, -88.29359158], [-88.29359158, -88.29359158, -88.41065565, -88.17534503], [-87.17534503, -87.17534503, -87.29359158, -87.05590408], [-88.05590408, -87.81339058, -88.17534503, -87.69029353], [-87.69029353, -87.44035665, -87.81339058, -87.56595307], [-88.97864878, -88.97864878, -88.97864878, -88.86732201], [-88.86732201, -88.86732201, -88.97864878, -88.75487073], [-88.75487073, -88.75487073, -88.86732201, -88.64128358], [-88.64128358, -88.64128358, -88.75487073, -88.52654908], [-88.52654908, -88.52654908, -88.64128358, -88.41065565], [-88.41065565, -88.41065565, -88.52654908, -88.29359158], [-88.29359158, -88.29359158, -88.41065565, -88.17534503], [-88.17534503, -87.18534503, -88.29359158, -87.93525666], [-87.93525666, -87.31349158, -87.18534503, -87.56595307], [-87.56595307, -87.56595307, -87.31349158, -87.44035665], [-88.97864878, -88.97864878, -88.97864878, -88.86732201], [-88.86732201, -88.86732201, -88.97864878, -88.75487073], [-88.75487073, -88.75487073, -88.86732201, -88.64128358], [-88.64128358, -88.64128358, -88.75487073, -88.52654908], [-88.52654908, -88.52654908, -88.64128358, -88.41065565], [-88.41065565, -88.41065565, -88.52654908, -88.29359158], [-88.29359158, -88.29359158, -88.41065565, -87.18534503], [-88.17534503, -87.31349158, -88.29359158, -87.81339058], [-87.81339058, -87.44035665, -87.31349158, -87.44035665], [-87.44035665, -87.56595307, -87.44035665, -87.56595307], [-88.97864878, -88.97864878, -88.97864878, -88.86732201], [-88.86732201, -88.86732201, -88.97864878, -88.75487073], [-88.75487073, -88.75487073, -88.86732201, -88.64128358], [-88.64128358, -88.64128358, -88.75487073, -88.52654908], [-88.52654908, -88.52654908, -88.64128358, -88.41065565], [-88.41065565, -87.44035665, -88.52654908, -87.31349158], [-88.29359158, -87.31349158, -88.41065565, -87.31349158], [-87.18534503, -87.44035665, -88.29359158, -87.31349158], [-87.31349158, -87.44035665, -87.44035665, -87.56595307], [-87.56595307, -87.56595307, -87.44035665, -87.56595307] ]) assert np.array_equal(q_values.round(3), expected_q_values.round(3))
[ "def test_projection_logic(self):", "def test_solvable_2d(self):\n mazes = [\n parse_2d_maze('A.www\\n' + 'wxwww'),\n parse_2d_maze('.w....\\n' + 'w..wxw\\n' + '.Awwww')\n ]\n solutions = [\n [(0, 0), (0, 1), (1, 1)],\n [(2, 1), (1, 1), (1, 2), (0, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
See if a read is aligned within `wiggle` of it's real start base.
def is_correct_aln(read, rname, wiggle=5): dwgsim_read = dwgsim_parser(read.qname) if rname != dwgsim_read.seqname: return False return (dwgsim_read.start_1 - read.pos) <= wiggle or (dwgsim_read.start_2 - read.pos) <= wiggle
[ "def has_align(self):\n return self._db_info_cache[\"sequence-aligned\"]", "def is_chunk(xbe, offset: int, section: str) -> bool:\n raw_offset = get_raw_address(offset, section)\n xbe.seek(raw_offset + 4) # skip entry\n geometry_header_pointer = unpack(\"I\", xbe.read(4))[0]\n\n return geometr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the path of the ARC data file given the type. Each ARC split has the corresponding data located in one file.
def type_to_data_file(arc_type): assert(isinstance(arc_type, ARCType)) data_dir = os.path.join(ARC_CACHE_DIR, "ARC-V1-Feb2018-2") split, category = tuple(arc_type.name.lower().split("_")) category = "ARC-{}".format(category.capitalize()) split = "{}-{}".format(category, split.capitalize()) basename = split + ".jsonl" return os.path.join(data_dir, category, basename)
[ "def get_data_file(*path_segments):\n return os.path.join(getdatapath(), *path_segments)", "def generate_file_uri(self, data_type: (str, URL, Path), file_name):\n if not file_name:\n raise ValueError(\" filename must exist \")\n return self.uri_for(data_type) / file_name", "def rlid_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send the status of the heaps as 3 integers to the client socket
def send_heaps_status(conn_soc,game): obj = pack('iii',game.nA, game.nB, game.nC) send_data(conn_soc, obj)
[ "def receive_game_status(client_soc):\n (nA, nB, nC) = receive_data(client_soc, 12, 'iii')\n print(\"Heap A: {}\\nHeap B: {}\\nHeap C: {}\".format(nA, nB, nC))", "def get_status(): # {\n statuses = thePlayer.get_status()\n try:\n status = \"\\n\".join(statuses)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
attempt to receive a single char from the server
def receive_char(client_soc): c = receive_data(client_soc, 1, 'c')[0] return c.decode('ascii')
[ "def receive_byte(self):\n return unpack('B', self.read(1))[0]", "def read_one_line(sock):\r\n newline_received = False\r\n message = \"\"\r\n while not newline_received:\r\n character = sock.recv(1).decode()\r\n if character == '\\n':\r\n newline_received = True\r\n el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send a value as single char to the client socket
def send_char(conn_soc, c): send_data(conn_soc, pack('c',c.encode('ascii')))
[ "def sendchar(self):\n\n self.transport.write(self.payload[self.index])\n self.index += 1\n if self.index >= len(self.payload):\n # Just stop and wait to get reaped.\n self.loop.stop()", "def send_byte(self, byte):\n self.write(pack('B', byte))", "def char_write(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
attempt to receive the game status from the server (as 3 integers that represent the heaps status)
def receive_game_status(client_soc): (nA, nB, nC) = receive_data(client_soc, 12, 'iii') print("Heap A: {}\nHeap B: {}\nHeap C: {}".format(nA, nB, nC))
[ "def send_heaps_status(conn_soc,game):\n obj = pack('iii',game.nA, game.nB, game.nC)\n send_data(conn_soc, obj)", "def get_status(): # {\n statuses = thePlayer.get_status()\n try:\n status = \"\\n\".join(statuses)\n except TypeError:\n status =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A terrible hash function that can be used for testing. A hash function should produce unpredictable results, but it is useful to see what happens to a hash table when you use the worstpossible hash function. The function returned from this factory function will always return the same number, regardless of the key.
def terrible_hash(bin): def hashfunc(item): return bin return hashfunc
[ "def terrible_hash(bin):\r\n def hashfunc(item):\r\n return bin\r\n return hashfunc", "def hash_function_integers(key, table_size):\n return key % table_size", "def hashFunctionTest():\n m = 128\n h = HashFunction(m)\n print(h)\n\n count = [0] * m\n for i in range(m*2):\n c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns NVCC GPU code generation options.
def _nvcc_gencode_options(cuda_version: int) -> List[str]: if sys.argv == ['setup.py', 'develop']: return [] envcfg = os.getenv('CUPY_NVCC_GENERATE_CODE', None) if envcfg is not None and envcfg != 'current': return ['--generate-code={}'.format(arch) for arch in envcfg.split(';') if len(arch) > 0] if envcfg == 'current' and build.get_compute_capabilities() is not None: ccs = build.get_compute_capabilities() arch_list = [ f'compute_{cc}' if cc < 60 else (f'compute_{cc}', f'sm_{cc}') for cc in ccs] else: # The arch_list specifies virtual architectures, such as 'compute_61', # and real architectures, such as 'sm_61', for which the CUDA # input files are to be compiled. # # The syntax of an entry of the list is # # entry ::= virtual_arch | (virtual_arch, real_arch) # # where virtual_arch is a string which means a virtual architecture and # real_arch is a string which means a real architecture. # # If a virtual architecture is supplied, NVCC generates a PTX code # the virtual architecture. If a pair of a virtual architecture and a # real architecture is supplied, NVCC generates a PTX code for the # virtual architecture as well as a cubin code for the real one. # # For example, making NVCC generate a PTX code for 'compute_60' virtual # architecture, the arch_list has an entry of 'compute_60'. # # arch_list = ['compute_60'] # # For another, making NVCC generate a PTX code for 'compute_61' virtual # architecture and a cubin code for 'sm_61' real architecture, the # arch_list has an entry of ('compute_61', 'sm_61'). # # arch_list = [('compute_61', 'sm_61')] # # See the documentation of each CUDA version for the list of supported # architectures: # # https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#options-for-steering-gpu-code-generation aarch64 = (platform.machine() == 'aarch64') if cuda_version >= 12000: arch_list = [('compute_50', 'sm_50'), ('compute_52', 'sm_52'), ('compute_60', 'sm_60'), ('compute_61', 'sm_61'), ('compute_70', 'sm_70'), ('compute_75', 'sm_75'), ('compute_80', 'sm_80'), ('compute_86', 'sm_86'), ('compute_89', 'sm_89'), ('compute_90', 'sm_90'), 'compute_90'] if aarch64: # Jetson TX1/TX2 are excluded as they don't support JetPack 5 # (CUDA 11.4). arch_list += [ # ('compute_53', 'sm_53'), # Jetson (TX1 / Nano) # ('compute_62', 'sm_62'), # Jetson (TX2) ('compute_72', 'sm_72'), # Jetson (Xavier) ('compute_87', 'sm_87'), # Jetson (Orin) ] elif cuda_version >= 11080: arch_list = [('compute_35', 'sm_35'), ('compute_37', 'sm_37'), ('compute_50', 'sm_50'), ('compute_52', 'sm_52'), ('compute_60', 'sm_60'), ('compute_61', 'sm_61'), ('compute_70', 'sm_70'), ('compute_75', 'sm_75'), ('compute_80', 'sm_80'), ('compute_86', 'sm_86'), ('compute_89', 'sm_89'), ('compute_90', 'sm_90'), 'compute_90'] if aarch64: # Jetson TX1/TX2 are excluded as they don't support JetPack 5 # (CUDA 11.4). arch_list += [ # ('compute_53', 'sm_53'), # Jetson (TX1 / Nano) # ('compute_62', 'sm_62'), # Jetson (TX2) ('compute_72', 'sm_72'), # Jetson (Xavier) ('compute_87', 'sm_87'), # Jetson (Orin) ] elif cuda_version >= 11040: # To utilize CUDA Minor Version Compatibility (`cupy-cuda11x`), # CUBIN must be generated for all supported compute capabilities # instead of PTX: # https://docs.nvidia.com/deploy/cuda-compatibility/index.html#application-considerations arch_list = [('compute_35', 'sm_35'), ('compute_37', 'sm_37'), ('compute_50', 'sm_50'), ('compute_52', 'sm_52'), ('compute_60', 'sm_60'), ('compute_61', 'sm_61'), ('compute_70', 'sm_70'), ('compute_75', 'sm_75'), ('compute_80', 'sm_80'), ('compute_86', 'sm_86'), 'compute_86'] if aarch64: # Jetson TX1/TX2 are excluded as they don't support JetPack 5 # (CUDA 11.4). arch_list += [ # ('compute_53', 'sm_53'), # Jetson (TX1 / Nano) # ('compute_62', 'sm_62'), # Jetson (TX2) ('compute_72', 'sm_72'), # Jetson (Xavier) ('compute_87', 'sm_87'), # Jetson (Orin) ] elif cuda_version >= 11010: arch_list = ['compute_35', 'compute_50', ('compute_60', 'sm_60'), ('compute_61', 'sm_61'), ('compute_70', 'sm_70'), ('compute_75', 'sm_75'), ('compute_80', 'sm_80'), ('compute_86', 'sm_86'), 'compute_86'] elif cuda_version >= 11000: arch_list = ['compute_35', 'compute_50', ('compute_60', 'sm_60'), ('compute_61', 'sm_61'), ('compute_70', 'sm_70'), ('compute_75', 'sm_75'), ('compute_80', 'sm_80'), 'compute_80'] elif cuda_version >= 10000: arch_list = ['compute_30', 'compute_50', ('compute_60', 'sm_60'), ('compute_61', 'sm_61'), ('compute_70', 'sm_70'), ('compute_75', 'sm_75'), 'compute_70'] else: # This should not happen. assert False options = [] for arch in arch_list: if type(arch) is tuple: virtual_arch, real_arch = arch options.append('--generate-code=arch={},code={}'.format( virtual_arch, real_arch)) else: options.append('--generate-code=arch={},code={}'.format( arch, arch)) return options
[ "def preferred_virtual_gpu_options(self):\n return self._preferred_virtual_gpu_options", "def init_pycuda():\n drv.init()\n context = drv.Device(0).make_context()\n devprops = { str(k): v for (k, v) in context.get_device().get_attributes().items() }\n cc = str(devprops['COMPUTE_CAPABILITY_MAJOR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create Lineups such that there is a 3 way tie amongst the last 3 ranks.
def create_last_place_tie_teams_three_way(self): max = 6 tie_amount = 10.0 for i in range(1, max + 1): user = self.get_user(username=str(i)) self.fund_user_account(user) lineup = Lineup() if i <= 3: # for 1, 2, 3 lineup.test_fantasy_points = tie_amount else: # teams 4, 5, 6 should have unique test_fantasy_points lineup.test_fantasy_points = tie_amount + i lineup.user = user lineup.draft_group = self.draftgroup lineup.save() bm = BuyinManager(lineup.user) bm.buyin(self.contest_pool, lineup) Entry.objects.filter(contest_pool=self.contest_pool).update(contest=self.contest) self.contest.status = Contest.COMPLETED self.contest.save()
[ "def RankPlayers(players):\r\n #Weights:\r\n WIN_PER = 10\r\n AVG_PTS = 4 \r\n AVG_DIFF = 1\r\n TM_WIN_PER = -3\r\n GP = -1\r\n OPP_WIN_PER = 3 \r\n ranks = []\r\n initorder = []\r\n\r\n for i in range(len(players)): #Creating Rank List\r\n ranks.append([players[i][0]])\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
contest is the contest to associate lineups with lineup_points is an array of the points to give to the lineups in creation order.
def __create_lineups_with_fantasy_points(self, contest_pool, lineup_points=[]): max = contest_pool.entries for i in range(1, max + 1): # get the user for the lineup user = self.get_user(username=str(i)) self.fund_user_account(user) # set the rest of the lineup properties lineup = Lineup() lineup.fantasy_points = lineup_points[i - 1] lineup.user = user lineup.draft_group = self.draftgroup lineup.save() # buy this lineup into the contest bm = BuyinManager(lineup.user) bm.buyin(self.contest_pool, lineup) Entry.objects.filter(contest_pool=self.contest_pool).update(contest=self.contest) # set the contest as payout-able self.contest.status = Contest.COMPLETED self.contest.save()
[ "def CreateOpponentStartingLineup(lineup, time, floridaScore, opponentScore):\n global currentOpponentLineup\n global opponentLinups\n currentOpponentLineup = lineup\n opponentLineups.append(lineup)\n opponentLineupNum = opponentLineups.index(lineup)\n floridaLineupNum = 0\n CreateStarterMatchu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper method that a) creates lineups with the points in 'lineup_points', b) does payouts, c) ensures all the ranks are set as expected based on the ranks in lineup_ranks and payout_ranks
def __run_payouts(self, lineup_points, lineup_ranks, payout_ranks): self.__create_lineups_with_fantasy_points(self.contest_pool, lineup_points=lineup_points) pm = PayoutManager() pm.payout(finalize_score=False) # test payout ranks payouts = Payout.objects.order_by('contest', '-rank') i = 0 for payout in payouts: msg = str(payout), 'rank:%s' % payout.rank, ' should be payout_ranks[%s]:%s' % ( str(payout.rank), str(payout_ranks[i])) logger.info(msg) i += 1 i = 0 for payout in payouts: # print(str(payout), 'rank:%s' % payout.rank, ' should be lineup_rank[%s]:%s' % (str(payout.rank), str(lineup_ranks[i])) ) self.assertEquals(payout.rank, payout_ranks[i]) i += 1 # test Entry ranks (each distinct buyin) lineups = Lineup.objects.order_by('fantasy_points') # ascending i = 0 for lineup in lineups: for entry in Entry.objects.filter(lineup=lineup): msg = (' ', str(entry), 'entry.final_rank:', entry.final_rank, ' should be entry rank:', lineup_ranks[i]) logger.info(msg) self.assertEquals(entry.final_rank, lineup_ranks[i]) i += 1 self.validate_side_effects_of_transaction()
[ "def __create_lineups_with_fantasy_points(self, contest_pool, lineup_points=[]):\n\n max = contest_pool.entries\n for i in range(1, max + 1):\n # get the user for the lineup\n user = self.get_user(username=str(i))\n self.fund_user_account(user)\n\n # set the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the colorbar for range maps.
def draw_colorbar(): print('draw colorbar') depth_bar = np.tile(np.linspace(vmin, vmax, 100), (BAR_WIDTH, 1)) depth_bar = np.flipud(depth_bar.T) plt.imshow(depth_bar, cmap='jet') plt.box(False) plt.axis('off') plt.show()
[ "def colorbar(self):\n if self.s1:\n ax_cb = plt.subplot(self.gs[1])\n else:\n print('must create plot before adding colorbar')\n return\n if self.alt_zi == 'int':\n ticks = np.linspace(-1,1,21)\n # find the intersection of the range of dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that a Gen3Auth instance can be initialized when the required parameters are included.
def test_auth_init_outside_workspace(): # missing parameters with pytest.raises(ValueError): Gen3Auth() # working initialization endpoint = "localhost" refresh_token = "my-refresh-token" auth = Gen3Auth(endpoint=endpoint, refresh_token=refresh_token) assert auth._endpoint == endpoint assert auth._refresh_token == refresh_token assert auth._use_wts == False
[ "def test_auth_init_outside_workspace():\n # working initialization\n auth = gen3.auth.Gen3Auth(refresh_token=test_key)\n assert auth.endpoint == test_endpoint\n assert auth._refresh_token == test_key\n assert auth._use_wts == False", "def test_auth_init_with_both_endpoint_and_idp():\n with pyte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists all clusters owned by a project in either the specified zone or all zones.
def list_clusters( self, project_id, zone, parent=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "list_clusters" not in self._inner_api_calls: self._inner_api_calls[ "list_clusters" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_clusters, default_retry=self._method_configs["ListClusters"].retry, default_timeout=self._method_configs["ListClusters"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.ListClustersRequest( project_id=project_id, zone=zone, parent=parent ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["list_clusters"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def get_cluster_list(self):\n LOG.info(\"Getting clusters\")\n return self.client.request(constants.GET,\n constants.GET_CLUSTER.format\n (self.server_ip), payload=None,\n querystring=constants.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the version and/or image type for the specified node pool.
def update_node_pool( self, project_id, zone, cluster_id, node_pool_id, node_version, image_type, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "update_node_pool" not in self._inner_api_calls: self._inner_api_calls[ "update_node_pool" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_node_pool, default_retry=self._method_configs["UpdateNodePool"].retry, default_timeout=self._method_configs["UpdateNodePool"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.UpdateNodePoolRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, node_pool_id=node_pool_id, node_version=node_version, image_type=image_type, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["update_node_pool"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def update_agent_pool(self, pool, pool_id):\n route_values = {}\n if pool_id is not None:\n route_values['poolId'] = self._serialize.url('pool_id', pool_id, 'int')\n content = self._serialize.body(pool, 'TaskAgentPool')\n response = self._send(http_method='PATCH',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the autoscaling settings for the specified node pool.
def set_node_pool_autoscaling( self, project_id, zone, cluster_id, node_pool_id, autoscaling, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "set_node_pool_autoscaling" not in self._inner_api_calls: self._inner_api_calls[ "set_node_pool_autoscaling" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_node_pool_autoscaling, default_retry=self._method_configs["SetNodePoolAutoscaling"].retry, default_timeout=self._method_configs["SetNodePoolAutoscaling"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetNodePoolAutoscalingRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, node_pool_id=node_pool_id, autoscaling=autoscaling, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_node_pool_autoscaling"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def pool_autoscale_settings(config):\n # type: (dict) -> PoolAutoscaleSettings\n conf = pool_specification(config)\n conf = _kv_read_checked(conf, 'autoscale', {})\n ei = _kv_read_checked(conf, 'evaluation_interval')\n if util.is_not_empty(ei):\n ei = util.convert_string_to_timedelta(ei)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the logging service for a specific cluster.
def set_logging_service( self, project_id, zone, cluster_id, logging_service, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "set_logging_service" not in self._inner_api_calls: self._inner_api_calls[ "set_logging_service" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_logging_service, default_retry=self._method_configs["SetLoggingService"].retry, default_timeout=self._method_configs["SetLoggingService"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetLoggingServiceRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, logging_service=logging_service, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_logging_service"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def set_monitoring_service(\n self,\n project_id,\n zone,\n cluster_id,\n monitoring_service,\n name=None,\n retry=google.api_core.gapic_v1.method.DEFAULT,\n timeout=google.api_core.gapic_v1.method.DEFAULT,\n metadata=None,\n ):\n # Wrap the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the monitoring service for a specific cluster.
def set_monitoring_service( self, project_id, zone, cluster_id, monitoring_service, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "set_monitoring_service" not in self._inner_api_calls: self._inner_api_calls[ "set_monitoring_service" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_monitoring_service, default_retry=self._method_configs["SetMonitoringService"].retry, default_timeout=self._method_configs["SetMonitoringService"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetMonitoringServiceRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, monitoring_service=monitoring_service, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_monitoring_service"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def set_cluster(self, data):\n cluster = Cluster(data['name'])\n for host in data['hosts']:\n cluster.add_host(**host)\n self._cluster = cluster", "def set_cluster_for_vios(self, vios_id, cluster_id, cluster_name):\n # first update the vios_keyed dict\n if vios_id no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the addons for a specific cluster.
def set_addons_config( self, project_id, zone, cluster_id, addons_config, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "set_addons_config" not in self._inner_api_calls: self._inner_api_calls[ "set_addons_config" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_addons_config, default_retry=self._method_configs["SetAddonsConfig"].retry, default_timeout=self._method_configs["SetAddonsConfig"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetAddonsConfigRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, addons_config=addons_config, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_addons_config"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def addons(self, value):\n if self._addons:\n raise RuntimeError(\"AddonManager already set!\")\n self._addons = value", "def set_cluster(self, data):\n cluster = Cluster(data['name'])\n for host in data['hosts']:\n cluster.add_host(**host)\n self._cluster...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the locations for a specific cluster.
def set_locations( self, project_id, zone, cluster_id, locations, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "set_locations" not in self._inner_api_calls: self._inner_api_calls[ "set_locations" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_locations, default_retry=self._method_configs["SetLocations"].retry, default_timeout=self._method_configs["SetLocations"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetLocationsRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, locations=locations, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_locations"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def update_cluster(cluster_collection, locations, centroid_id):\n bulk = cluster_collection.initialize_unordered_bulk_op()\n bulk.find({\"_id\": {\"$in\": locations}}).update({\"$set\": {\"centroid\": centroid_id}})\n try:\n bulk.execute()\n except BulkWriteError as bwe:\n logging.getLogg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the master for a specific cluster.
def update_master( self, project_id, zone, cluster_id, master_version, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "update_master" not in self._inner_api_calls: self._inner_api_calls[ "update_master" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_master, default_retry=self._method_configs["UpdateMaster"].retry, default_timeout=self._method_configs["UpdateMaster"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.UpdateMasterRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, master_version=master_version, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["update_master"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def cmd_node_update_cluster(self, args):\n node_id = args[0]\n cluster_id = args[1]\n data = {'cluster_id': cluster_id}\n self._update_obj(node_id, 'node', data)", "def test_slave_master_up_cluster_id(self):\n self._cluster.master = None\n self._slave_1.is_slave = False\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists all operations in a project in a specific zone or all zones.
def list_operations( self, project_id, zone, parent=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "list_operations" not in self._inner_api_calls: self._inner_api_calls[ "list_operations" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_operations, default_retry=self._method_configs["ListOperations"].retry, default_timeout=self._method_configs["ListOperations"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.ListOperationsRequest( project_id=project_id, zone=zone, parent=parent ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["list_operations"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def get_operations_in_zone(self, zone):\n\n\t\treturn self.compute.zoneOperations().list(project=self.project, zone=zone).execute()", "def list(cls, api_client, **kwargs):\n\n cmd = {}\n cmd.update(kwargs)\n if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():\n cmd['lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists the node pools for a cluster.
def list_node_pools( self, project_id, zone, cluster_id, parent=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "list_node_pools" not in self._inner_api_calls: self._inner_api_calls[ "list_node_pools" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_node_pools, default_retry=self._method_configs["ListNodePools"].retry, default_timeout=self._method_configs["ListNodePools"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.ListNodePoolsRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, parent=parent ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["list_node_pools"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def list_nodepools(\n parent: str = None,\n configuration: Configuration = None,\n secrets: Secrets = None,\n) -> Dict[str, Any]: # noqa: E501\n parent = get_parent(parent, configuration=configuration, secrets=secrets)\n client = get_client(configuration, secrets)\n response = client.list_node_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a node pool for a cluster.
def create_node_pool( self, project_id, zone, cluster_id, node_pool, parent=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "create_node_pool" not in self._inner_api_calls: self._inner_api_calls[ "create_node_pool" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_node_pool, default_retry=self._method_configs["CreateNodePool"].retry, default_timeout=self._method_configs["CreateNodePool"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.CreateNodePoolRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, node_pool=node_pool, parent=parent, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_node_pool"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def create_pool(self, **params):\n pool = self.get_pool(connect=False, **params)\n\n # Save the pool\n self.pool.append(pool)\n\n return pool", "def test_pool_create(self):\n pool_name = p_n()\n self.unittest_command(\n [_STRATIS_CLI, \"pool\", \"create\", poo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes a node pool from a cluster.
def delete_node_pool( self, project_id, zone, cluster_id, node_pool_id, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "delete_node_pool" not in self._inner_api_calls: self._inner_api_calls[ "delete_node_pool" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_node_pool, default_retry=self._method_configs["DeleteNodePool"].retry, default_timeout=self._method_configs["DeleteNodePool"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.DeleteNodePoolRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, node_pool_id=node_pool_id, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["delete_node_pool"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def delete_pool(self, context, pool):\n self._clear_loadbalancer_instance(pool['tenant_id'], pool['id'])", "def delete_pool(self, pool):\n if pool.get('loadbalancer_id', None):\n self._update_loadbalancer_instance_v2(pool['loadbalancer_id'])\n elif pool['vip_id']:\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the NodeManagement options for a node pool.
def set_node_pool_management( self, project_id, zone, cluster_id, node_pool_id, management, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "set_node_pool_management" not in self._inner_api_calls: self._inner_api_calls[ "set_node_pool_management" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_node_pool_management, default_retry=self._method_configs["SetNodePoolManagement"].retry, default_timeout=self._method_configs["SetNodePoolManagement"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetNodePoolManagementRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, node_pool_id=node_pool_id, management=management, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_node_pool_management"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def set_numa_optimization(self):\n\n self.params += \" -XX:+UseNUMA -XX:+UseParallelGC\"", "def set_node_pool_autoscaling(\n self,\n project_id,\n zone,\n cluster_id,\n node_pool_id,\n autoscaling,\n name=None,\n retry=google.api_core.gapic_v1.method...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets labels on a cluster.
def set_labels( self, project_id, zone, cluster_id, resource_labels, label_fingerprint, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "set_labels" not in self._inner_api_calls: self._inner_api_calls[ "set_labels" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_labels, default_retry=self._method_configs["SetLabels"].retry, default_timeout=self._method_configs["SetLabels"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetLabelsRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, resource_labels=resource_labels, label_fingerprint=label_fingerprint, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_labels"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def set_labels(self,labels):\n assert isinstance(labels,dict)\n assert all([isinstance(_k,str) for _k in labels.keys()])\n assert all([isinstance(_v,(int,list,tuple)) for _v in labels.values()])\n \n if self.label_map is None:\n self.label_map = dict()\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables or disables the ABAC authorization mechanism on a cluster.
def set_legacy_abac( self, project_id, zone, cluster_id, enabled, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "set_legacy_abac" not in self._inner_api_calls: self._inner_api_calls[ "set_legacy_abac" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_legacy_abac, default_retry=self._method_configs["SetLegacyAbac"].retry, default_timeout=self._method_configs["SetLegacyAbac"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetLegacyAbacRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, enabled=enabled, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_legacy_abac"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def enable_cluster_backup(self):\n mch_resource = ocp.OCP(\n kind=\"MultiClusterHub\",\n resource_name=constants.ACM_MULTICLUSTER_RESOURCE,\n namespace=constants.ACM_HUB_NAMESPACE,\n )\n mch_resource._has_phase = True\n resource_dict = mch_resource.get()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Completes master IP rotation.
def complete_i_p_rotation( self, project_id, zone, cluster_id, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "complete_i_p_rotation" not in self._inner_api_calls: self._inner_api_calls[ "complete_i_p_rotation" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.complete_i_p_rotation, default_retry=self._method_configs["CompleteIPRotation"].retry, default_timeout=self._method_configs["CompleteIPRotation"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.CompleteIPRotationRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, name=name ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["complete_i_p_rotation"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def reset_master(server):\n server.exec_stmt(\"RESET MASTER\")", "def _cmd_resync(self):\n self.ctx.awaiting_bridge = True", "def delete_last_transport_process(self):", "def switch_sync_finished(self):", "def exit(self):\n # force state of missing Supvisors instances\n self.context....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables or disables Network Policy for a cluster.
def set_network_policy( self, project_id, zone, cluster_id, network_policy, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "set_network_policy" not in self._inner_api_calls: self._inner_api_calls[ "set_network_policy" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_network_policy, default_retry=self._method_configs["SetNetworkPolicy"].retry, default_timeout=self._method_configs["SetNetworkPolicy"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetNetworkPolicyRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, network_policy=network_policy, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_network_policy"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def enable_network_management(request):\n log('Enabling network management')\n _assign_role(request, StandardRole.NETWORK_MANAGER)", "def enable_network(self):\n if self._is_admin():\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Wi-Fi\"', 'enable'])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the maintenance policy for a cluster.
def set_maintenance_policy( self, project_id, zone, cluster_id, maintenance_policy, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "set_maintenance_policy" not in self._inner_api_calls: self._inner_api_calls[ "set_maintenance_policy" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_maintenance_policy, default_retry=self._method_configs["SetMaintenancePolicy"].retry, default_timeout=self._method_configs["SetMaintenancePolicy"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetMaintenancePolicyRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, maintenance_policy=maintenance_policy, name=name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_maintenance_policy"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def maintenance_mode(self, mode):\n service = self._fetch_service_config(self.id)\n old_service = service.copy() # in case anything fails for rollback\n\n try:\n service['metadata']['annotations']['router.deis.io/maintenance'] = str(mode).lower()\n self._scheduler.svc.up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists subnetworks that are usable for creating clusters in a project.
def list_usable_subnetworks( self, parent=None, filter_=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic. if "list_usable_subnetworks" not in self._inner_api_calls: self._inner_api_calls[ "list_usable_subnetworks" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_usable_subnetworks, default_retry=self._method_configs["ListUsableSubnetworks"].retry, default_timeout=self._method_configs["ListUsableSubnetworks"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.ListUsableSubnetworksRequest( parent=parent, filter=filter_, page_size=page_size ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_usable_subnetworks"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="subnetworks", request_token_field="page_token", response_token_field="next_page_token", ) return iterator
[ "def ex_list_networks(self):\r\n list_networks = []\r\n request = '/global/networks'\r\n response = self.connection.request(request, method='GET').object\r\n list_networks = [self._to_network(n) for n in\r\n response.get('items', [])]\r\n return list_networ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
demo a selection process add args for Menu class timeout min sels 1 max sels None cycle how many times to choose if not chosen redo option salesExamples could be used here for menu and Nestedcit app
def select(self): # read 1 json file, 1 quiz from take_quiz() the_list = ['aaa', 'bbb', 'ccc', 'ddd'] # timeout cycle limit men = menu.Menu(cycle=10, limit=0, timeout=4) selections = men.select_from_menu(the_list, "select one or more") print(selections) men = menu.Menu(cycle=5, timeout=4, limit=1) selections = men.select_from_menu(the_list, "select only one item") print(selections) selections = men.select_from_menu(the_list, "select only one item with default", default='default') print(selections)
[ "def targetMenu()->None:\n print(\"\\nEscoja el rango de edad\")\n print(\"*******************************************\")\n print(\"0. 0-10 \")\n print(\"1. 11-20\")\n print(\"2. 21-30\")\n print(\"3. 31-40\")\n print(\"4. 41-50\")\n print(\"5. 51-60\")\n print(\"6. 60+\")\n print(\"**...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot velocities in the model
def plot_velocities(self, LAXIS, xbl, xbr, ybu, ybd, ilg): bconv = self.bconv tconv = self.tconv super_ad_i = self.super_ad_i super_ad_o = self.super_ad_o # check supported geometries if self.ig != 1 and self.ig != 2: print("ERROR(VelocitiesMLTturb.py):" + self.errorGeometry(self.ig)) sys.exit() # load x GRID grd1 = self.xzn0 # load DATA to plot plt1 = self.ux plt2 = self.vexp1 plt3 = self.vexp2 plt4 = self.vturb plt5 = self.vmlt_1 # vmlt_1 = fhh / (alphae * dd * fht_cp * tt_rms) - REFERENCE NEEDED plt6 = self.vmlt_2 # vmlt_2 = gg * betaT * (nabla - nabla_ad) * ((lbd ** 2.) / (8. * Hp)) - REFERENCE NEEDED plt7 = self.vmlt_3 # THIS IS FROM TYCHO's initial model plt8 = self.vrms # create FIGURE plt.figure(figsize=(7, 6)) # format AXIS, make sure it is exponential plt.gca().yaxis.get_major_formatter().set_powerlimits((0, 0)) # temporary hack plt4 = np.nan_to_num(plt4) plt5 = np.nan_to_num(plt5) plt6 = np.nan_to_num(plt6) plt7 = np.nan_to_num(plt7) plt8 = np.nan_to_num(plt8) # set plot boundaries to_plot = [plt4, plt5, plt6, plt7] self.set_plt_axis(LAXIS, xbl, xbr, ybu, ybd, to_plot) # plot DATA plt.title('velocities ' + str(self.nsdim) + "D") # plt.plot(grd1,plt1,color='brown',label = r'$\overline{u}_r$') # plt.plot(grd1,plt2,color='red',label = r'$\widetilde{u}_r$') # plt.plot(grd1,plt3,color='green',linestyle='--',label = r'$\overline{v}_{exp} = -\dot{M}/(4 \pi r^2 \rho)$') #plt.plot(grd1, plt4, color='blue', label=r"$u_{turb} = +\widetilde{u''_x u''_x}^{1/2}$") plt.plot(grd1, plt8, color='blue', label=r"$u_{rms}$") plt.plot(grd1,plt5,color='red',label = r'$u_{mlt}$') # plt.plot(grd1,plt6,color='g',label = r'$u_{MLT} 2$') # plt.plot(self.rr,plt7,color='brown',label = r'$u_{MLT} 3 inimod$') # convective boundary markers plt.axvline(bconv, linestyle='--', linewidth=0.7, color='k') plt.axvline(tconv, linestyle='--', linewidth=0.7, color='k') # convective boundary markers - only super-adiatic regions plt.axvline(super_ad_i, linestyle=':', linewidth=0.7, color='k') plt.axvline(super_ad_o, linestyle=':', linewidth=0.7, color='k') if self.ig == 1: setxlabel = r"x (cm)" setylabel = r"velocity (cm s$^{-1}$)" plt.xlabel(setxlabel) plt.ylabel(setylabel) elif self.ig == 2: setxlabel = r"r (cm)" setylabel = r"velocity (cm s$^{-1}$)" plt.xlabel(setxlabel) plt.ylabel(setylabel) # show LEGEND plt.legend(loc=ilg, prop={'size': 18}) # display PLOT plt.show(block=False) # save PLOT if self.fext == "png": plt.savefig('RESULTS/' + self.data_prefix + 'mean_velocities_turb.png') if self.fext == "eps": plt.savefig('RESULTS/' + self.data_prefix + 'mean_velocities_turb.eps')
[ "def plot(self, *args, **kwargs):\n plt.scatter(self.velocity['colloid'],\n self.velocity['velocity'],\n *args, **kwargs)", "def plot_velocities(self, steps=None, total_steps=None, show_sigma=False, ax=None, animation_mode=False):\n \n # Set plotting opti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Number of time steps in current episode split.
def episode_time_steps(self): return (self.episode_end_time_step - self.episode_start_time_step) + 1
[ "def get_num_timesteps(self):\n return len(self.dm[0])", "def getNrTimesteps():\n\n timesteps = 25\n return timesteps", "def nsteps(self):\n return self._nsteps", "def n_timesteps(self) -> int:\n if self.total_time < self.timestep:\n warnings.warn(\n f\"No simu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Number of time steps between `simulation_start_time_step` and `simulation_end_time_step`.
def simulation_time_steps(self): return (self.__simulation_end_time_step - self.__simulation_start_time_step) + 1
[ "def n_timesteps(self) -> int:\n if self.total_time < self.timestep:\n warnings.warn(\n f\"No simulation possible: you asked for {self.total_time} \"\n f\"simulation time but the timestep is {self.timestep}\"\n )\n return floor(self.total_time.total_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start time step in current episode split.
def episode_start_time_step(self): return self.__episode_start_time_step
[ "def test_start_time_with_timestep(self):\n with mn.model(start_time=2019, timestep=0.25) as m:\n Time = mn.variable('Time', lambda md: md.TIME, '__model__')\n Step = mn.variable('Step', lambda md: md.STEP, '__model__')\n\n self.assertEqual(Time[''], 2019)\n self.assertEqu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End time step in current episode split.
def episode_end_time_step(self): return self.__episode_end_time_step
[ "def calculate_end_episode(self):\n self.end_episode = self.game.is_final(self.current_state)", "def end_episode(self):", "def end_episode(self):\n self.trainer.end_episode()", "def step_end(self):\n if self.log_time:\n total_time = time.monotonic() - self.start_time\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Advance to next episode and set `episode_start_time_step` and `episode_end_time_step` for reading data files.
def next_episode(self, episode_time_steps: Union[int, List[Tuple[int, int]]], rolling_episode_split: bool, random_episode_split: bool, random_seed: int): self.__episode += 1 self.__next_episode_time_steps( episode_time_steps, rolling_episode_split, random_episode_split, random_seed, )
[ "def _read_next_episode(self):\n if self.done_reading_all_episodes:\n return\n assert self.done_reading_current_episode\n _next_episode_num = self._episodes.next()\n self._latest_episode = self._read_episode(_next_episode_num)\n self._latest_episode_next_offset = 0", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Number of seconds in 1 time step.
def seconds_per_time_step(self) -> float: return self.__seconds_per_time_step
[ "def n_timesteps(self) -> int:\n if self.total_time < self.timestep:\n warnings.warn(\n f\"No simulation possible: you asked for {self.total_time} \"\n f\"simulation time but the timestep is {self.timestep}\"\n )\n return floor(self.total_time.total_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Advance to next `time_step` value. Notes Override in subclass for custom implementation when advancing to next `time_step`.
def next_time_step(self): self.__time_step += 1
[ "def step_forward(self) -> None:\n self._time += self.step_size", "def call_next_time_step(self):\n\n if self.time_step_cycle is not None:\n self.canvas.after_cancel(self.time_step_cycle)\n self.time_step_cycle = self.canvas.after(self.delay, self.time_step)", "def increment_step...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Reset `time_step` to initial state. Sets `time_step` to 0.
def reset_time_step(self): self.__time_step = 0
[ "def reset_step_count(self):\n self.step_count = 0", "def reset(self):\n\n self.timestep = 0\n self.historyLayer.reset()", "def reset_timing(self):\n\n self.timing_start = self.current_time()", "def reset(self) -> None:\n self.time_counted = 0\n self.last_start_time = 0\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }