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)...
[ "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_ANNOTATIO...
[ "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( ...
[ "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...
[ "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(n...
[ "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. ...
[ "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...
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), ...
[ "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: ...
[ "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,...
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)...
[ "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, ...
[ "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_inf...
[ "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...
[ "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 ...
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): ...
[ "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 = [-...
[ "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, wi...
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.l...
[ "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...
[ "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 ...
[ "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>=maxi...
[ "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_tab...
[ "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_use...
[ "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',...
[ "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.setSiz...
[ "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.Dat...
[ "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.9...
[ "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()) base...
[ "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...
[ "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 l...
[ "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 ...
[ "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', '-r...
[ "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 == endpoin...
[ "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_clust...
[ "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, ): ...
[ "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 th...
[ "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 ad...
[ "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...
[ "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 re...
[ "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 ...
[ "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...
[ "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_ope...
[ "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. ...
[ "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...
[ "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 retr...
[ "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 ...
[ "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 tran...
[ "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 ...
[ "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 log...
[ "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 ...
[ "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...
[ "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. ...
[ "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 = men...
[ "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):" + s...
[ "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_spl...
[ "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" ] ] } }