query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Return the four intersection points for the four given lines whose enclosed shape is a quadrilateral.
def get_intersection_points(lines, debug_img=None): # Convert [a,b,c,d] to [(a,b), (b,c), (c,d), (d,a)] line_pairs = list(zip(lines, lines[1:]+lines[:1])) corners = [get_intersection_point(*p) for p in line_pairs] if debug_img is not None: int_corners = np.array(corners, np.int32) dra...
[ "def line_segment_intersect(x1, y1, x2, y2, x3, y3, x4, y4):\n\n # Common divisor\n print(x1, y1, x2, y2, x3, y3, x4, y4, file=sys.stderr)\n d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)\n \n # Check for parallel lines\n if d == 0:\n return None\n\n # Make sure we're not off the end ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the locations of the four outside corners of two pieces of tape. The given corners should be a 3D array of shape (2, 4, 2).
def get_outside_corners(tape_corners, debug_img=None): lines = get_lines(tape_corners, debug_img) return get_intersection_points(lines, debug_img)
[ "def corners(boxes: np.ndarray) -> np.ndarray:\n top_right = boxes[:, :2] - boxes[:, 2:] * 0.5\n bot_left = boxes[:, :2] + boxes[:, 2:] * 0.5\n return np.concatenate((top_right, bot_left), axis=1)", "def get_enclosing_box(corners):\n x_ = corners[:, [0, 2, 4, 6]]\n y_ = corners[:, [1, 3, 5, 7]]\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure logging and start the given root component in the default asyncio event loop. Assuming the root component was started successfully, the event loop will continue running until the process is terminated.
def run_application( component: Component | dict[str, Any], *, event_loop_policy: str | None = None, max_threads: int | None = None, logging: dict[str, Any] | int | None = INFO, start_timeout: int | float | None = 10, ) -> None: # Configure the logging system if isinstance(logging, dict)...
[ "def run(self):\n _LOGGER.info(\"Started\")\n try:\n self._main_loop()\n except Exception:\n _LOGGER.exception(\"Uncaught exception\")\n raise", "def startLoop(self):\n if(self.loop is not None):\n raise Exception(\"Event loop is already started!\")\n self.loop = a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Env wrapper that returns a previous observation with probability `p` and the current observation with a probability `1p`. `last_k` previous observations are stored.
def __init__(self, env: gym.Env, sticky_probability: float, last_k: int): super().__init__(self, env) if 1 >= sticky_probability >= 0: self._sticky_probability = sticky_probability else: raise ValueError( f"sticky_probability = {sticky_probability} is not ...
[ "def first_active(self, k):\n return k - self.p", "def prevPose(self):\n self.setPose((self.pose - 1) % self.__num_poses)", "def generate_y_pred_at_k(y_prob, k):\n n_items = y_prob.shape[1]\n index_array = np.argsort(y_prob, axis=1)\n col_idx = np.arange(y_prob.shape[0]).reshape(-1, 1)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether a given date was a national holiday in Russia or not. Note that
def is_russian_2017_holiday(date): return int(date in russian_2017_holidays)
[ "def is_bank_holiday(date):\n return date in BANK_HOLIDAYS", "def is_holiday(self) -> bool:\n return set(self._get_date_text_ascii()) == set([int(x) for x in self.params['holiday']['holiday_text']])", "def is_holiday(date):\n \n return date.day in __get_holidays(date.year)[date.month]", "def is_pu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper function that is identical to the fit method of TPOTClassifier or TPOTRegressor. The purpose is to store the feature and target and use it in other methods of TpotAutoml
def fit(self, features, target, **kwargs): self.features = features self.target = target super(tpot_class, self).fit(features, target, **kwargs)
[ "def fit(self, target):", "def tpotclass(X_train, y_train):\n pipeline_optimizer = TPOTClassifier(generations=5,\n population_size=50,\n cv=5,\n random_state=42,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines whether scoring_function being greater is more favorable/better.
def is_greater_better(scoring_function): if scoring_function in [ 'accuracy', 'adjusted_rand_score', 'average_precision', 'balanced_accuracy','f1', 'f1_macro', 'f1_micro', 'f1_samples', 'f1_weighted', 'precision', 'precision_macro', 'precision_micro', 'precision_samples','precision_w...
[ "def important_features_(self):\n return self.scores_ > self.score_cutoff_", "def is_better(self, curr, best, **kwargs):\r\n score_threshold = kwargs.pop('score_threshold', 1e-3)\r\n relative_eps = 1.0 + score_threshold\r\n return curr >= best*relative_eps", "def is_best(self, metric...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a JSON configuration file
def create_config_file(name): config = {} config['name'] = name to_dir = os.getcwd() + '/' + name with open(os.path.join(to_dir, 'configuration.json'), 'w') as config_file: json.dump(config, config_file)
[ "def createConfig():\n\twith open(configPath, 'w', encoding='utf-8') as file:\n\t\tjson.dump(default_config, file, indent=3)", "def save(config, filename=None):\n filename = add_directory(filename or 'configure.json')\n directory = os.path.dirname(filename)\n if not os.path.exists(directory):\n os...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that N/A values (None, numpy.nan) are handled consistently when using CSV vs Arrow as a prediction payload format. 1. Make CSV and Arrow prediction payloads from the same dataframe 2. Read both payloads 3. Assert the resulting dataframes are equal
def test_read_structured_input_arrow_csv_na_consistency(tmp_path): # arrange df = pd.DataFrame({"col_int": [1, np.nan, None], "col_obj": ["a", np.nan, None]}) csv_filename = os.path.join(tmp_path, "X.csv") with open(csv_filename, "w") as f: f.write(df.to_csv(index=False)) arrow_filename =...
[ "def test_converted_type_null():\n p = fastparquet.ParquetFile(os.path.join(TEST_DATA,\n \"test-converted-type-null.parquet\"))\n data = p.to_pandas()\n expected = pd.DataFrame([{\"foo\": \"bar\"}, {\"foo\": None}])\n for col in data:\n if isinstance(data[c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download poety from all the given sockets.
def get_poetry(sockets): poems = dict.fromkeys(sockets, '') # socket -> accumulated poem # socket -> task numbers sock2task = dict([(s, i + 1) for i, s in enumerate(sockets)]) sockets = list(sockets) # make a copy # we go around this loop until we've gotten all the poetry # from all the sock...
[ "def get_poetry(sockets):\r\n\r\n poems = dict.fromkeys(sockets, '') # socket -> accumulated poem\r\n\r\n # socket -> task numbers\r\n sock2task = dict([(s, i + 1) for i, s in enumerate(sockets)])\r\n\r\n sockets = list(sockets) # make a copy\r\n\r\n # we go around this loop until we've gotten all th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads in the header of a csv file.
def read_csv_header(input_file_path): return pd.read_csv(input_file_path, nrows=0)
[ "def read_header(filepath):\n logging.info(\"Reading header for {0}\".format(filepath))\n with open(filepath, \"r\") as f:\n reader = csv.reader(f)\n i = next(reader)\n # print(i)\n # i = filter(None, i)\n # print(i)\n return i", "def test_header_of_csv(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads in a csv file, and attempts to use the date format that is specified in the config file. The date columns it uses are the ones that are specified by the date_cols, first_exp_date_cols, last_exp_date_cols, index_date_col and lookback_date_col params in the general section of the YAML config. Depending on the size ...
def read_csv(config, input_file_path): header = read_csv_header(input_file_path) general = config['general'] date_cols_types = ['date_cols', 'first_exp_date_cols', 'last_exp_date_cols', 'index_date_col', 'lookback_d...
[ "def get_data_from_csv_full_path(filepath, datatypes, date_column_list):\n\n dataframe = pandas.read_csv(filepath, dtype=datatypes, date_parser=pandas.to_datetime, parse_dates=date_column_list)\n\n return dataframe", "def read_in_data(filename, datetime_colname):\n return pd.read_csv(filename, parse_date...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
arr1 and arr2 are well sorted array,
def merge(arr1, arr2): res = [] i = j = 0 while i< len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: res.append(arr1[i]) i+=1 else: res.append(arr2[j]) j+=1 while i < len(arr1): res.append(arr1[i]) i +=1 while j < len(arr2): j +=1 res.append(arr2[j]) return res
[ "def sort2arr(arr1, arr2):\n arr1, arr2 = list(zip(*sorted(zip(arr1, arr2))))\n return arr1, arr2", "def merge(arr1, arr2, asc=True):\n arr1.extend(arr2)\n return insertion_sort(\n arr1,\n asc\n )", "def relativeSortArray(arr1, arr2):\n def compare(number):\n if nu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert version format depsolver is using (depsolver.SemanticVersion) into version format I'm using (string of loose form '1.56.3a'). Currently, for proof of concept and initial tests, we're using versions that fit the SemanticVersion spec instead of PyPI's sometimes elaborate ones. Depsolver can't accept anything othe...
def convert_version_from_depsolver(semantic_version): return str(semantic_version)
[ "def suggest_normalized_version(s):\r\n try:\r\n NormalizedVersion(s)\r\n return s # already rational\r\n except IrrationalVersionError:\r\n pass\r\n\r\n rs = s.lower()\r\n\r\n # part of this could use maketrans\r\n for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the distkey to one usable by depsolver. e.g. 'X(1)' to 'X1.0.0' e.g. 'pipaccel(1.0.0) to 'pip_accel1.0.0'. (Shudder)
def convert_distkey_for_depsolver(distkey, as_req=False): (packname, version) = depdata.get_pack_and_version(distkey) # depsolver can't handle '-' in package names (ARGH!), so turn all '-' to '_' # Must turn them back in the conversion back........ try: my_ds_distkey = convert_packname_for_depsolver(pack...
[ "def convert_dist_to_packageinfo_for_depsolver(distkey, deps):\n\n # Convert the distkey to one usable by depsolver.\n try:\n my_ds_distkey = convert_distkey_for_depsolver(distkey)\n\n except DepsolverConversionError as e:\n logger.exception('In converting dist ' + distkey + ', unable to convert '\n '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Revert from depsolver's package name format to that expected by pip and my code. (Reverses convert_packname_for_depsolver, the package name part of convert_distkey_for_depsolver.)
def convert_packname_from_depsolver(depsolver_packname): return depsolver_packname.replace('_', '-')
[ "def convert_dist_to_packageinfo_for_depsolver(distkey, deps):\n\n # Convert the distkey to one usable by depsolver.\n try:\n my_ds_distkey = convert_distkey_for_depsolver(distkey)\n\n except DepsolverConversionError as e:\n logger.exception('In converting dist ' + distkey + ', unable to convert '\n '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given deps for a single distkey (e.g. DEPS_SIMPLE[X(1)] above), converts to a depsolver compatible format, depsolver.PackageInfo (e.g. DEPS_SIMPLE_PACKAGEINFOS[0] above) Returned object is type depsolver.PackageInfo.
def convert_dist_to_packageinfo_for_depsolver(distkey, deps): # Convert the distkey to one usable by depsolver. try: my_ds_distkey = convert_distkey_for_depsolver(distkey) except DepsolverConversionError as e: logger.exception('In converting dist ' + distkey + ', unable to convert ' 'the distkey i...
[ "def convert_packs_to_packageinfo_for_depsolver(deps):\n\n packageinfos = []\n packs_unable_to_convert = []\n\n for distkey in deps:\n try:\n packageinfos.append(\n convert_dist_to_packageinfo_for_depsolver(distkey, deps))\n\n except DepsolverConversionError as e:\n logger.exception('In ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given deps (e.g. DEPS_SIMPLE above), converts to a depsolver compatible format, depsolver.PackageInfo (e.g. DEPS_SIMPLE_PACKAGEINFOS above) Uses convert_single_dist_deps_to_packageinfo_for_depsolver
def convert_packs_to_packageinfo_for_depsolver(deps): packageinfos = [] packs_unable_to_convert = [] for distkey in deps: try: packageinfos.append( convert_dist_to_packageinfo_for_depsolver(distkey, deps)) except DepsolverConversionError as e: logger.exception('In converting dicti...
[ "def convert_dist_to_packageinfo_for_depsolver(distkey, deps):\n\n # Convert the distkey to one usable by depsolver.\n try:\n my_ds_distkey = convert_distkey_for_depsolver(distkey)\n\n except DepsolverConversionError as e:\n logger.exception('In converting dist ' + distkey + ', unable to convert '\n '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a json containing an array of the repr() values from depsolver.package.PackageInfo objects, reinstantiates those objects. (That is how I am storing the converted objects offline, as the conversion is timeconsuming, and this reinstantiation is faster.) Discards any that do not parse correctly. AFAIK, that currentl...
def reload_already_converted_from_json(fname): converted = json.load(open(fname, 'r')) pinfos = [] #unable_to_parse = [] n_unable_to_parse = 0 i = 0 for pinfo_str in converted: i += 1 try: pinfos.append(depsolver.package.PackageInfo.from_string(str(pinfo_str))) # cleansing unicode bullshit ...
[ "def update_from_json(self, json_string):\n parsed = json.loads(json_string)\n self.add_packages(parsed.pop('packages', []))\n self.data(parsed)", "def sanitize_json_and_store(file):\n with open(file, 'r') as read_file:\n data = json.load(read_file)\n data.pop('numberOfModules', ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper for the depsolver package so that it can be tested via the same testing I employ for my own resolver package. Solves a dependency structure for a given package's dependencies, using the external depsolver package. Intended to be compatible with resolver.depdata.test_resolver.
def resolve_via_depsolver(distkey, deps, versions_by_package=None, already_converted=False): # Convert the dependencies into a format for depsolver, if they are not # already in a depsolver-friendly format. converted_dists = [] dists_unable_to_convert = [] if already_converted: converted_dists = deps...
[ "def resolve_all_via_depsolver(dists_to_solve_for, pinfos, fname_solutions, fname_errors,\n fname_unresolvables):\n\n def _write_data_out(solutions, unable_to_resolve, unresolvables):\n \"\"\"THIS IS AN INNER FUNCTION WITHIN resolve_all_via_depsolver!\"\"\"\n print('')\n print('------------------------...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try finding the install solution for every dist in the list given, using dependency information from the given PackageInfo objects. Write this out to a temporary json occasionally so as not to lose data if the process is interrupted, as it is INCREDIBLY SLOW.
def resolve_all_via_depsolver(dists_to_solve_for, pinfos, fname_solutions, fname_errors, fname_unresolvables): def _write_data_out(solutions, unable_to_resolve, unresolvables): """THIS IS AN INNER FUNCTION WITHIN resolve_all_via_depsolver!""" print('') print('------------------------') print('---...
[ "def _select_relevant_packages(cls) -> dict:\n\n def create_or_update_package(dist, packages: dict) -> None:\n if dist.name not in packages:\n packages[dist.name] = {\n \"name\": dist.name,\n \"apps\": list(),\n \"current\": d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the loss for l2 weight decay and adds it to `cost`.
def decay_weights(cost, weight_decay_rate): costs = [] for var in tf.trainable_variables(): costs.append(tf.nn.l2_loss(var)) cost += tf.multiply(weight_decay_rate, tf.add_n(costs)) return cost
[ "def logistic_L2_loss(y, X, w, lamb):\r\n\r\n cost = logistic_L0_loss(y, X, w) + cost_L2_regularizer(w, lamb)\r\n\r\n return cost", "def l2_reg_cost(cost):\n return cost + tf.losses.get_regularization_losses()", "def l2_reg_cost(cost, lambtha, weights, L, m):\n enorm = 0\n for i in range(1, L + 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find reference sequence make a index return mappy alignment result default only keep one best alignment default using 2 threads
def getIndex(reference, thread): if reference: reffa = reference else: reffa = path.join(path.dirname(path.abspath(path.dirname(__file__))),"reference.fa") if not path.isfile(reffa): logging.error("Could not find reference.fa") sys.exit("ERROR: Could not find reference.fa! Pr...
[ "def find_matching_seqs_from_alignment(sequences, ref_sequence):\n\n # if the first sequence (gaps removed) in MSA matches with reference,\n # return this sequence.\n first_seq_in_alignment = sequences[0] \n #first_seq_in_alignment_gaps_removed = first_seq_in_alignment.replace('-','')\n first_seq_in_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert an image containing CARLA semantic segmentation labels to Cityscapes palette.
def labels_to_cityscapes_palette(image): classes=ZHANG_classes result =np.zeros((img.shape[0], img.shape[1], 3),dtype=np.uint8) for key, value in classes.items(): result[np.where(img == key)] = value return result
[ "def labels_to_cityscapes_palette(image):\n classes=Apollo_class\n result =np.zeros((img.shape[0], img.shape[1], 3),dtype=np.uint8)\n for key, value in classes.items():\n result[np.where(img == key)] = value\n return result", "def create_cityscapes_label_colormap():\r\n col...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check result of a Coroutine
def check_result(self, coro_id): try: status, response = self.coros_result.get(coro_id) if status != CoroStatus.Queued: self.remove_coro(coro_id) return status, response except KeyError: raise CoroMissingException("Coroutine Id {}" ...
[ "def test_await_if_coroutine(coroutine, exp_return, args):\n result = asyncio.run(await_if_coroutine(coroutine, *args))\n\n assert result == exp_return", "async def _do_if_possible(self, coroutine: Awaitable[None]) -> None:\n try:\n await coroutine\n except IncorrectStateException:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query the published timestamp.
def published(self): xutimes = self.xutimes() # If there are 2 xutimes, published is the second. Otherwise, it is the # first and only xutime. offset = 0 if len(xutimes) == 1 else 1 return dt.fromtimestamp(int(xutimes[offset]))
[ "def time_published(self):\n return self._time_published", "def published(self, site=None):\n pub = self.on_site(site).filter(published=True)\n ref_date = get_timetravel_date()\n\n if settings.CMS_SHOW_START_DATE:\n pub = pub.filter(\n Q(publication_date__lt=ref_date) |\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query the updated timestamp.
def updated(self): xutimes = self.xutimes() # If there are 2 xutimes, updated is the first. Otherwise, there is no # updated date, just published. return ( dt.fromtimestamp(int(xutimes[0])) if len(xutimes) == 2 else None )
[ "def updated_time(self):\n return self._updated_time", "def updated(self, key=None):\n if key:\n sql = u\"\"\"\n SELECT `updated` FROM `{table}` WHERE `key` = ?\n \"\"\".format(table=self.name)\n\n row = self.conn.execute(sql, (key,)).fetchone()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map into the Profile model.
def parse(self): details = self.details() return Profile( book_id=self.book_id, title=self.title(), user_id=self.user_id(), username=self.username(), summary=self.summary(), published=self.published(), updated=self.upda...
[ "def _profile_from_dict(obj):\n return ProfileModelFactory.from_dict(obj)", "def _getProfileFromUser(self):\n # make sure user is authed\n user = endpoints.get_current_user()\n if not user:\n raise endpoints.UnauthorizedException('Authorization required')\n\n # get Pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the current position of the goal.
def goal_pos(self) -> Pt: return self._goal
[ "def get_current_position(self):\r\n return self.grid[self.ant_position]", "def _goal_position(self, raw_data):\n return raw_data['goal_position_ego_n2']", "def get_position(self):\n return self.bot_client.send_command(_Command.GetPosition)", "def get_goal_position(self, index):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the distance between the player and the goal.
def player_goal_distance(self) -> float: route = self.best_route return sum(route.values())
[ "def distance_to(self, otherPlayer):\n\n distance = sqrt((self.x - otherPlayer.x)**2 + (self.y - otherPlayer.y)**2)\n\n return distance", "def check_goal_distance(self): \n result = self.get_model_srv(self.robot_model)\n robot_pos = result.pose.position\n\n result = self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the best route from the player to the goal.
def best_route(self, player: Optional[Pt] = None, goal: Optional[Pt] = None): best = empty_path() if player is None and goal is None: diff = self._goal - self._player else: diff = goal - player horz = diff.x // self.PLAYER_DIM vert = diff.y // self.PLAYE...
[ "def getBestPath(self):\n if self._bestPathVertex.getNextWaypoint() is None:\n numWaypointsCompleted = len(self._waypoints)\n quality = 2\n if self._vertexQueue.isEmpty():\n quality += 1\n else:\n numWaypointsCompleted = self._bestPathVertex.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the best route as a numpy array.
def best_routes_matrix(self) -> np.array: x = np.empty((0, 4)) y = np.empty((0, 4)) for k, v in self.routes.items(): x_row = np.zeros((1, 4)) y_row = np.zeros((1, 4)) # Player start position player = Pt(k[0][0], k[0][1]) x_row[0, 0] = ...
[ "def best_routes(self) -> Sequence['outputs.GetRouterStatusBestRouteResult']:\n return pulumi.get(self, \"best_routes\")", "def getBestPath(self):\n if self._bestPathVertex.getNextWaypoint() is None:\n numWaypointsCompleted = len(self._waypoints)\n quality = 2\n if s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the player up one cell.
def player_up(self) -> None: self._routes[self._current_route_key]["UP"] += 1 new_pos = self._player.y - self.MOVE_INC if new_pos + self.PLAYER_DIM <= self._height and new_pos - self.PLAYER_DIM >= 0: self._player.y = new_pos
[ "def move_up(self):\n if self.grid_pos_y == 0:\n self.grid_pos_y = self.grid_row_len -1\n self.y_pos = self.grid_row_len\n\n self.grid[0][self.grid_pos_x] = self.tile_symbol\n self.grid[self.grid_pos_y][self.grid_pos_x] = self.pos_symbol\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the player down one cell.
def player_down(self) -> None: self._routes[self._current_route_key]["DOWN"] += 1 new_pos = self._player.y + self.MOVE_INC if new_pos + self.PLAYER_DIM <= self._height and new_pos - self.PLAYER_DIM >= 0: self._player.y = new_pos
[ "def move_down(self):\n self.game_piece.y = self.game_piece.y + 1", "def move_down(self):\n\n if self.grid_pos_y == len(self.grid) - 1:\n self.grid_pos_y = 0\n self.y_pos = 1\n\n self.grid[-1][self.grid_pos_x] = self.tile_symbol\n self.grid[self.grid_pos_y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the player left one cell.
def player_left(self) -> None: self._routes[self._current_route_key]["LEFT"] += 1 new_pos = self._player.x - self.MOVE_INC if new_pos + self.PLAYER_DIM <= self._width and new_pos - self.PLAYER_DIM >= 0: self._player.x = new_pos
[ "def move_left(self):\n if self.grid_pos_x == 0:\n self.grid_pos_x = self.grid_column_len - 1\n self.x_pos = self.grid_column_len\n\n self.grid[self.grid_pos_y][0] = self.tile_symbol\n self.grid[self.grid_pos_y][self.grid_pos_x] = self.pos_symbol\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the player right one cell.
def player_right(self) -> None: self._routes[self._current_route_key]["RIGHT"] += 1 new_pos = self._player.x + self.MOVE_INC if new_pos + self.PLAYER_DIM <= self._height and new_pos - self.PLAYER_DIM >= 0: self._player.x = new_pos
[ "def move_right(self):\n if self.grid_pos_x == self.grid_column_len - 1:\n self.grid_pos_x = 0\n self.x_pos = 1\n\n self.grid[self.grid_pos_y][-1] = self.tile_symbol\n self.grid[self.grid_pos_y][self.grid_pos_x] = self.pos_symbol\n else:\n self.gr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initiate a game loop by using the action callback to get player movements.
def callback_game_loop(self) -> None: self._goal_generate() self._update() self.reset() while self._player != self._goal: self._update() action = self._action_callback( self._player.np, self._goal.np, *self._action_...
[ "def _game_loop(self):\n self._keyboard_pressing()\n self._ship_action()\n self._torpedos_action()\n self._asteroids_action()\n self._check_lost_game()\n self._check_won_game()\n self._check_quit_game()", "def player_loop(self):\n\n # Generate game tree obje...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that headers are retrieved from the cache when they exist and not retrieved from Auth0 unecessarily.
def test_headers_from_cache(db, mocker): get_token = mocker.patch('creator.authentication.get_token') cache_key = "ACCESS_TOKEN:my_aud" cache.set(cache_key, "ABC") headers = client_headers("my_aud") assert "Authorization" in headers assert headers["Authorization"] == "Bearer ABC" assert ge...
[ "def test_headers(self):\n response = self.client.get(reverse('search'), {'q': 'audio', 'w': 3})\n eq_('max-age=%s' % (settings.SEARCH_CACHE_PERIOD * 60),\n response['Cache-Control'])\n assert 'Expires' in response\n response = self.client.get(reverse('search'))\n eq_('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that Auth0 is called for a new token
def test_new_token(db, mocker): settings.AUTH0_CLIENT = "123" settings.AUTH0_SECRET = "abc" class Resp: def json(self): return {"access_token": "ABC"} def raise_for_status(self): pass mock = mocker.patch("creator.authentication.requests.post") mock.return_v...
[ "def test_create_obtain_auth_token(self):\n pass", "def test_oauth2_token_exchange(self):\n pass", "def test_get_new_access_token(authorizer, token_data, on_refresh):\n # take note of original access_token_hash\n original_hash = authorizer._access_token_hash\n\n # get new_access_token\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that no token is fetched when there is not enough config
def test_new_token_insuficient_config(db, mocker): settings.AUTH0_CLIENT = None mock = mocker.patch("creator.authentication.requests.post") assert get_token("my_aud") is None assert mock.call_count == 0
[ "def test_config_token_is_set():\n assert len(Config.token) > 0", "def test_not_existent_token(self):\n response = self.client.get(self.url + 'ABC123def456ghi7/')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, msg=response.content.decode())", "def test_no_token_get_all(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run each initial move a number of times to get a better idea of which ones will work best
def run_each_move(root: State, state: GameState) -> State: for m, base_move in enumerate(root.moves): for _ in range(50): base_move = expand(base_move) outcome, _ = MCTS(base_move, state, False, 0) if outcome == state.player: base_move.winner() ...
[ "def run_each_move(root: State, state: GameState) -> State:\n # Decide how many times to run the initial states\n #num_inits = len(root.moves)\n #if num_inits < 2:\n # num_inits = 3\n num_inits = 20\n for m, base_move in enumerate(root.moves):\n base_move = expand(base_move)\n for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Computes the noise level sigma to reach a total budget of (target_epsilon, target_delta) at the end of epochs, with a given sample_rate
def get_noise_multiplier( target_epsilon: float, target_delta: float, sample_rate: float, epochs: int, alphas: [float], sigma_min: float = 0.01, sigma_max: float = 10.0, ) -> float: from opacus import privacy_analysis eps = float("inf") while eps > target_epsilon: ...
[ "def gauss_kernel(sigma, sample_rate, duration):\n l = duration * sample_rate\n x = np.arange(-np.floor(l / 2), np.floor(l / 2)) / sample_rate\n y = (1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-(x ** 2 / (2 * sigma ** 2)))\n y /= np.sum(y)\n return y", "def RMSE(energy_guess, energy_target):\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a mock feed entry for testing purposes.
def _generate_mock_feed_entry( external_id, title, distance_to_home, coordinates, category ): feed_entry = MagicMock() feed_entry.external_id = external_id feed_entry.title = title feed_entry.distance_to_home = distance_to_home feed_entry.coordinates = coordinates ...
[ "def _generate_mock_feed_entry(\n external_id,\n title,\n distance_to_home,\n coordinates,\n category=None,\n attribution=None,\n published=None,\n updated=None,\n status=None,\n):\n feed_entry = MagicMock()\n feed_entry.external_id = external_id\n feed_entry.title = title\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialization of vanderpol output
def __init__(self): super(vanderpol_output,self).__init__() # add figure object for further use fig = plt.figure() self.ax = fig.add_subplot(111) self.ax.set_xlim([-2.5,2.5]) self.ax.set_ylim([-10.5,10.5]) plt.ion() self.sframe = None
[ "def _populate_output(self):\n pass", "def __init__(self):\n _snap.TStdOut_swiginit(self, _snap.new_TStdOut())", "def __init__(self, *args, **kwargs):\n _richtext.RichTextPrintout_swiginit(self,_richtext.new_RichTextPrintout(*args, **kwargs))", "def printVOTHeader(self):\n votableT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The key algorithm to use when generating the private key.
def key_algorithm(self) -> str: return pulumi.get(self, "key_algorithm")
[ "def key_algorithm(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"key_algorithm\")", "def public_key_algorithm(self):\n return self._public_key_native[\"algorithm\"][\"algorithm\"]", "def key_algorithm(self) -> Optional[pulumi.Input['KeyKeyAlgorithm']]:\n return pulumi.get(self, \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets details of a single CertificateIssuanceConfig.
def get_certificate_issuance_config(certificate_issuance_config_id: Optional[str] = None, location: Optional[str] = None, project: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGe...
[ "def get_certificate_issuance_config_output(certificate_issuance_config_id: Optional[pulumi.Input[str]] = None,\n location: Optional[pulumi.Input[str]] = None,\n project: Optional[pulumi.Input[Optional[str]]] = None,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets details of a single CertificateIssuanceConfig.
def get_certificate_issuance_config_output(certificate_issuance_config_id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[Optional[str]]] = None, ...
[ "def get_certificate_issuance_config(certificate_issuance_config_id: Optional[str] = None,\n location: Optional[str] = None,\n project: Optional[str] = None,\n opts: Optional[pulumi.InvokeOptions] = None) -> Awa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the learning rate of a given `model` generated by `fe.build`.
def set_lr(model: Union[tf.keras.Model, torch.nn.Module], lr: float, weight_decay: Optional[float] = None): assert hasattr(model, "fe_compiled") and model.fe_compiled, "set_lr only accept models from fe.build" if isinstance(model, tf.keras.Model): # when using decoupled weight decay like SGDW or AdamW, ...
[ "def set_learning_rate(self, lr):\n self.lr = lr", "def set_learning_rate(self, rate):\n self.SGD.set_learning_rate(rate)", "def do_set_learning_rate(self, learning_rate) -> None:\r\n self.learning_rate = float(learning_rate)", "def set_lr(model, lr):\r\n\tK.set_value(model.optimizer.lr, floa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a histogram of smart meter readings to identify their distribution and find outliers.
def hourly_sm_reading_histogram(): cursor = connections["ldc"].cursor() cursor.execute("select smr.Reading " "from essex_annotated.SmartMeterReadings smr " "inner join Meters m on m.MeterID = smr.MeterID " " and m.`Phase` = 1 " ...
[ "def reading_count_histogram():\r\n cursor = connections[\"ldc\"].cursor()\r\n cursor.execute(\"select count(smr.read_datetime) \"\r\n \"from essex_annotated.SmartMeterReadings smr \" \r\n \"inner join Meters m \"\r\n \" on m.MeterID = smr.MeterID and m.`...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the number of readings in a time range grouped by MeterID
def reading_count_histogram(): cursor = connections["ldc"].cursor() cursor.execute("select count(smr.read_datetime) " "from essex_annotated.SmartMeterReadings smr " "inner join Meters m " " on m.MeterID = smr.MeterID and m.`Phase` = 1 " ...
[ "def num_of_readings(since: datetime, until: datetime = datetime.now()):\n delta = until - since\n # We use floor() to round down because 1.99999 readings is 1 reading in an interval, not 2\n return math.floor((delta.total_seconds() / 60) / INTERVAL)", "def getMeterReadings(self):\n return self._M...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Counts the number of exceptions per MeterNumber and plots a histogram.
def sm_reading_exception_count_histogram(): cursor = connections["ldc"].cursor() cursor.execute("select count(smre.reading_datetime_standard) " "from Meters m " "left join SmartMeterReadingsExceptions smre " " on smre.MeterNumber = m.MeterNumber " ...
[ "def histoPlot(h,fmt='.',lighter_error=0.75,ax=None,counts='counts', bins='bins',label=\"\",errorbar_kw={'capsize':5, 'elinewidth':1, 'markeredgewidth':1},step_kw={},**kwargs):\n ##############################################\n if ax is None:\n ax = plt.axes()\n # to keep plotting on the same ax...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SELECT "visit_occurrence"."visit_concept_id", COUNT("visit_occurrence"."visit_concept_id") AS "visit_concept_id__count" FROM "visit_occurrence" GROUP BY "visit_occurrence"."visit_concept_id"
def total(request) : # foreign key 가 아니라서 ORM 상에서 JOIN 이 안됨;; data = VisitOccurrence.objects.values('visit_concept_id').annotate(Count('visit_concept_id')) for tmp in data : # JOIN 안해서 생긴 불필요한 반복문(N+1 문제) concept_id = tmp['visit_concept_id'] concept_name = Concept.objects.filter(concept_id=conc...
[ "def count_county(spark, insurance_df):\n # YOUR CODE HERE\n return insurance_df.groupBy(\"county\").count().toPandas()", "def annotation_count(content_object):", "def n_count(category):\r\n sql = text('''\r\n WITH uniq AS (\r\n SELECT COUNT(app.id) FROM task, app\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Push transaction to the miner network. Returns txid if done successfully.
def push_tx(self, crypto, tx_hex): raise NotImplementedError( "This service does not support pushing transactions to the network. " "Or rather it has no defined 'push_tx' method." )
[ "def _broadcast_transaction(self) -> str:\n self.transaction_handler = SimplifiedEthereumTransactionHandler(\n chain=self.config.original_chain.split('_')[1],\n path_to_secret=self.path_to_secret,\n private_key=self.config.get('eth_private_key'),\n recommended_max_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get block based on either block height, block number or get the latest block. Only one of the previous arguments must be passed on.
def get_block(self, crypto, block_height='', block_number='', latest=False): raise NotImplementedError( "This service does not support getting getting block data. " "Or rather it has no defined 'get_block' method." )
[ "def get_block_from_height(self, height):\n try:\n block = json.loads(self.chain[height-1])\n except:\n print('Index out of bounds')\n return False\n return block", "def get_block_by_height(\n *,\n height: int,\n) -> Any:\n block = crud.block.get_by_h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Each service class is instantiated here so the service instances stay in scope for the entire life of this object. This way the service objects can cache responses.
def __init__(self, services=None, verbose=False, responses=None): if not services: from moneywagon import ALL_SERVICES services = ALL_SERVICES self.services = [] for ServiceClass in services: self.services.append( ServiceClass(verbose=verbose,...
[ "def __init__(self):\n super(ServiceLayer, self).__init__()\n self._application = _Application()\n self._server = httpserver.HTTPServer(self._application)\n self._services = {}", "def __init__(self):\n\n services = app.config['YAML'].services\n self.updated = datetime.now...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try each service until one returns a response. This function only catches the bare minimum of exceptions from the service class. We want exceptions to be raised so the service classes can be debugged and fixed quickly.
def _try_services(self, method_name, *args, **kwargs): for service in self.services: crypto = ((args and args[0]) or kwargs['crypto']).lower() address = kwargs.get('address', '').lower() fiat = kwargs.get('fiat', '').lower() if service.supported_cryptos and (cryp...
[ "def check_services(self):\n for service in self.services:\n try:\n self.cloud.search_services(service)[0]\n except Exception: # pylint: disable=broad-except\n self.is_skipped = True\n break", "async def start_all(self):\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is called when all Services have been tried and no value can be returned. It much take the same args and kwargs as in the method spefified in `method_name`. Returned is a string for the error message. It should say something informative.
def no_service_msg(self, *args, **kwargs): return "All either skipped or failed."
[ "def _try_services(self, method_name, *args, **kwargs):\n for service in self.services:\n crypto = ((args and args[0]) or kwargs['crypto']).lower()\n address = kwargs.get('address', '').lower()\n fiat = kwargs.get('fiat', '').lower()\n\n if service.supported_crypto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches the value according to the mode of execution desired. `FetcherClass` must be a class that is subclassed from AutoFallback. `services` must be a list of Service classes. `kwargs` is a list of arguments used to make the service call, usually
def enforce_service_mode(services, FetcherClass, kwargs, modes): average_level = modes.get('average', 1) paranoid_level = modes.get('paranoid', 1) verbose = modes.get('verbose', False) if modes.get('random', False): random.shuffle(services) if paranoid_level == 1 and average_level == 1: ...
[ "def _fetch(self, fetch):\n if fetch == 'posts':\n if self['handle'] and not self['guid']: self.fetchhandle()\n else: self.fetchguid()\n elif fetch == 'data' and self['handle']:\n self.fetchprofile()", "def get(cls, fetcher_name_request: str):\n\n\t\tfor i in cls:\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a string of 'currency units' to 'protocol units'. For instance converts 19.1 bitcoin to 1910000000 satoshis. Input is a float, output is an integer that is 1e8 times larger. It is hard to do this conversion because multiplying floats causes rounding nubers which will mess up the transactions creation process.
def currency_to_protocol(amount): if type(amount) == float: amount = "%.8f" % amount return int(amount.replace(".", '')) # avoiding float math
[ "def unitConverter(self,value):\r\n assert type(value) == str\r\n \r\n try:\r\n return float(value)\r\n except:\r\n self.isSIUnit(value)\r\n\r\n multiplier = 1\r\n unitPrefixes = {\r\n 'p':10**-12,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of minutes it would take to prepare a layer of lasagna assuming that each layer takes two minutes to prepare.
def preparation_time_in_minutes(number_of_layers): return number_of_layers * 2
[ "def preparation_time_in_minutes(number_of_layers):\n\n layers_preparation_time = number_of_layers * PREPARATION_TIME\n return layers_preparation_time", "def elapsed_time_in_minutes(number_of_layers: int, elapsed_bake_time: int) -> int:\n return preparation_time_in_minutes(number_of_layers) + elapsed_bak...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET requrest to fetch categories of one domain_concept
def fetch_categories_from_json(domain_concept): S = requests.Session() URL = "https://en.wikipedia.org/w/api.php" PARAMS = { "action": "query", "format": "json", "titles": domain_concept, "prop": "categories", "clshow": "!hidden", "cllimit": "500", "re...
[ "def get_categories(request):\n query_dict = get_query_from_json(request)\n categories = models.Category.objects.filter(type='cultural')\n source_categories = []\n if 'source' in query_dict:\n source = models.Source.objects.filter(id=query_dict['source'])\n variables = models.Variable.obje...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allows the user to import a list of tickers from a .csv or .txt file using File>Import. The list should be have no headers and separated only by commas (i.e. aapl,msft,amzn).
def import_csv(self): path = tk.filedialog.askopenfile(initialdir="/", title="Select File", filetypes=(("Comma-separated values (.csv)", "*.csv"), ("Text Document (.txt)", "*.txt"), ("All Files", "*.*"))) items = [] if path is not None: ...
[ "def importAll():\n csvFile = openCsv()\n items = [] # chooseKey, count, grade, keyType, mainCategory, mainKey,\n # name, pricePerOne, subCategory, subKey, totalTradeCount,\n # mainLabel, subLabel, description\n\n with open(csvFile) as i:\n readItem = csv.reader(i)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allows the user to use File>Export to save the current stock data in the main table (i.e. Treeview). The supported file types are .csv or .txt.
def export_data(self): stocks = {} headings = ['Security', 'Price', 'Change', 'Change %', '52 Week', 'Market Cap'] for data in range(6): for items in self.root.main.treeview.get_children(): values = self.root.main.treeview.item(items, 'values') ...
[ "def do_export(self,args):\n if args == \"csv\":\n self.db.export_csv()\n else:\n self.db.export_json()", "def __export(self):\n information = []\n\n if self.export_name.get():\n information.append('name')\n\n if self.export_artists.get():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Controls the type of graph that should be displayed when the user toggles between the different radio buttons (View>Line/Area/or Candlestick).
def get_radio(self): current_status = self.radio_var.get() if current_status != self.radio_status: self.radio_var.set(current_status) self.radio_status = current_status self.root.main.generate_graph(self.root.main.ticker) self.root.main.remove_old_graphs()
[ "def type_determine(self):\n\n if self.data_type == \"ECG\" or self.data_type == \"ENR\":\n self.curve_channel2 = self.ECGWinHandle.plot(self.display_channel2, pen=self.pen)\n self.curve_channel1 = self.RespirationWinHandle.plot(self.display_channel1, pen=self.pen)\n self.two...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Highlights all of the items in the main table (Treeview) when the user uses View>Select All. This enables the user to use the Remove button to delete multiple line of stocks, rather than one at a time.
def select_all(self): selected_stocks = self.root.main.treeview.get_children() self.root.main.treeview.selection_set(selected_stocks)
[ "def unselectAll(self):\n\t\tself.tree.UnselectAll()", "def SelectAll(self):\r\n\r\n if not self.HasAGWFlag(TR_MULTIPLE) and not self.HasAGWFlag(TR_EXTENDED):\r\n raise Exception(\"SelectAll can be used only with multiple selection enabled.\")\r\n \r\n rootItem = self.GetRootItem()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the user's ticker entry and calls get_quote() to add the stock to the main table.
def add_ticker(self): ticker = self.addEntry.get().upper() self.get_quote(ticker)
[ "async def stock(self, ctx, ticker: str):\n symbols = await self.bot.aiojson(\"https://api.robinhood.com/quotes/\"\\\n f\"?symbols={ticker.upper()}\")\n if not symbols:\n await ctx.send(\"Stock not found. This stock is probably not tradeable on robinho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function fixes a styling bug in Tkinter see References. Returns the style map for 'option' with any styles starting with ("!disabled", "!selected", ...) filtered out
def fixed_map(self, option): return [elm for elm in self.style.map("Treeview", query_opt=option) if elm[:2] != ("!disabled", "!selected")]
[ "def __renderStyles(self):\n html = '<select onchange=\"submitStyle();\" name=\"styleSelect\">\\n'\n for style in self.styles:\n html += \"<option value=\\\"\"+style+\"\\\" \"\n if self.style == style:\n html += \"selected \"\n html += \">\" + style + \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens a window that enables the user to save the current graph as a .png or .pdf file.
def save_image(self): filename = filedialog.asksaveasfilename(title='Save Image As...', filetypes=(("Portable Network Graphics (.png)", "*.png"), ("Portable Document Format(.pdf)", "*.pdf"))) self.graph.savefig(filename, dpi=self.graph.dpi)
[ "def on_save(self, event):\n file_choices = \"PNG (*.png)|*.png\"\n \n dlg = wx.FileDialog(\n self, \n message=\"Save plot as...\",\n defaultDir=os.getcwd(),\n defaultFile=\"plot.png\",\n wildcard=file_choices,\n style=wx.SAVE)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dates obtained from the API are in string form, which is converted to Date objects using Date's datestr2num() method.
def bytes_to_dates(self, date_str): return mpldates.datestr2num(date_str.decode('utf-8'))
[ "def parse_dates(json_date):\n return datetime.fromtimestamp(int(json_date)/1000.0).strftime('%Y-%m-%d')", "def numeric_date(date_str):\n final_date = \"\"\n date = date_str.split(\" \")\n final_date += DATE_DICTIONARY[date[0]] + \"-\"\n final_date += date[1][:-1] + \"-\"\n final_date += date[2]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the user's mouse leaves a button, the color of the button reverts back to default.
def mouse_out(self, event): self['background'] = self.defaultBackground
[ "def mouse_out(self):\n pass", "def hover(self, mousepos: Tuple[int, int]) -> None:\n if self.rect.collidepoint(mousepos):\n # Become darker when mouse is hovering over button\n self.color = tuple([self.color[i] - 2 if self.color[i] > 20 else self.color[i] for i in range(3)])\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get all images related to project
def getImages(self,Project=""): #images = ["image1.jpg","image2.jpg","image3.jpg"] os.chdir(self.dataDir) images = glob.glob("*.png") return images
[ "def list_images(self, ex_project=None):\n list_images = []\n request = '/global/images'\n if ex_project is None:\n response = self.connection.request(request, method='GET').object\n else:\n # Save the connection request_path\n save_request_path = self.co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a text list with output for this node and its descendents.
def exportNode(self, node, level=0): title = node.title() textList = ['<node>', title, repr(level)] output = node.formatOutput(True) if output and output[0] == title: del output[0] # remove first line if same as title textList.extend(output) if (output an...
[ "def get_all_text(self) :\n return Patent.get_tree_text(self._root)", "def to_list(self):\n root = self.label\n if len(self.children) > 0:\n children = [c.to_list() for c in self.children]\n else:\n children = []\n return [root, [children]]", "def get_tex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Taken from mock_django as importing mock_django created issues with Django 1.9+ Temporarily attaches a receiver to the provided ``signal`` within the scope of the context manager. The mocked receiver is returned as the ``as`` target of the ``with`` statement. To have the mocked receiver wrap a callable, pass the callab...
def mock_signal_receiver(signal, wraps=None, **kwargs): if wraps is None: def wraps(*args, **kwrags): return None receiver = mock.Mock(wraps=wraps) signal.connect(receiver, **kwargs) yield receiver signal.disconnect(receiver)
[ "def receiver(signal, **kwargs):\n def _decorator(func):\n signal.connect(func, **kwargs)\n return func\n return _decorator", "def wrapped(signal_name, sender=dispatcher.Anonymous, safe=False):\n @wrapt.decorator\n def signal_wrapped(wrapped_func, _, args, kwargs):\n def signal_wr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that returns True if a human face is detected in the image, False otherwise
def face_detector(img_path: str): img = cv2.imread(img_path) # if no image at that path, return False if img is None: return False # convert to grey gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # detect faces. If no face detected, it's empty and len(faces) will be 0 fac...
[ "def detect_face(img):\r\n image = cv2.imread(img)\r\n faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n faces = faceCascade.detectMultiScale(\r\n gray,\r\n scaleFactor=1.2,\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts `gzip_file` and put into `path`. If members is None, all members on `gzip_file` will be extracted.
def decompress(infile, path, members=None): with open(infile, 'rb') as inf, open(path, 'w', encoding='utf8') as tof: decom_str = gzip.decompress(inf.read()).decode('utf-8') tof.write(decom_str)
[ "def extractall(self, path, members=None):\n names = self.zip_obj.namelist()\n for name in self.get_paths(names):\n fullname = os.path.join(path, name)\n if not os.path.exists(fullname): \n os.mkdir(fullname)\n for name in self.get_files(names):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Train the particle proposer k.
def train_particle_proposer(self): batch_size = self.trainparam['batch_size'] # epochs = self.trainparam['epochs'] epochs = 500 lr = self.trainparam['learning_rate'] particle_num = self.trainparam['particle_num'] std = 0.2 encoder_checkpoint = "encoder.pth" ...
[ "def train(self):\n self.k_XX = squared_exponential_kernel(self.X_train, self.X_train, self.parameter_l, self.parameter_sig_f)\n self.inv_Cov = np.linalg.inv(self.k_XX + self.parameter_sig_n * self.parameter_sig_n * np.eye(self.order))\n\n pass", "def train(self):\n\n print \"==> Runni...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Eval the particle proposer
def eval_particle_proposer(self, val_loader, epoch): std = 0.2 mle_loss_total = 0.0 niter = 0 sta_eval = None particles_eval = None for i, (sta, obs, act) in enumerate(val_loader): obs = obs.cuda().reshape(-1, 24, 24, 3).permute(0,3,1,2).float() st...
[ "def concurrent_run(self, particle): \r\n # Store the leader values.\r\n leader_vals = self.population[self.leader].values[:]\r\n \r\n # Calculate velocity and move the particle\r\n particle.calculate_velocity(leader_vals)\r\n particle.move()\r\n particle.eval...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Train the observation likelihood estimator l (and h)
def train_likelihood_estimator(self): batch_size = self.trainparam['batch_size'] epochs = self.trainparam['epochs'] lr = self.trainparam['learning_rate'] self.observation_encoder = self.observation_encoder.double() self.likelihood_estimator = self.likelihood_estimator.double() ...
[ "def log_likelihood(self, data, reward_model, bias_params):", "def train(cls, x, y):\n mdl = LR()\n mdl.fit(x, y)\n \n des_x = np.insert(x,0,1,axis=1)\n probs = mdl.predict_proba(x)\n w = np.diag(np.multiply(probs[:,0],probs[:,1]))\n fisher = np.dot(np.dot(des_x.T,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Eval the observation encoder and likelihood estimator
def eval_likelihood_estimator(self, val_loader): likelihood_list = [] self.observation_encoder.eval() self.likelihood_estimator.eval() for i, (sta, obs, act) in enumerate(val_loader): if self.use_cuda: sta = sta.cuda() obs = obs.cuda() ...
[ "def _evaluate_during_fit(self, test_loader, epoch):", "def _eval(self, epoch):\n raise NotImplementedError", "def evaluate_model():\n\n print '\\n\\tevaluate result'\n os.system('./conlleval.pl -d \\'\\t\\' < ' + encoded_test + ' >> ' + result_file)\n print '\\t--done\\n'", "def eval(self, pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rename sample names by map and ratify action.
def _rename_samples_by_map(self, map_like: Mapper, **kwargs) -> Optional[Mapper]: self.__internal_samples.rename(mapper=map_like, axis=0, inplace=True) return self._ratify_action("_rename_samples_by_map", map_like, **kwargs)
[ "def rename_sample(self, new_name, plate_locations):\r\n\r\n for i, row in self.records.iterrows():\r\n if row['wellPosition'] in plate_locations:\r\n self.records.loc[i,'sampleId'] = new_name", "def rename_samples(self, mapper: Mapper) -> None:\n if isinstance(mapper, dict...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove samples by sample ids and ratify action.
def _remove_samples_by_id( self, ids: AnyGenericIdentifier, **kwargs ) -> Optional[AnyGenericIdentifier]: tmp_ids = np.asarray(ids, dtype=self.__internal_samples.index.dtype) if len(tmp_ids) > 0: self.__internal_samples.drop(tmp_ids, inplace=True) return self._ratify_acti...
[ "def remove_samples(self, *samples):\n samples = [get_sample_id(s) for s in samples]\n # XXX: Make in one request when supported on API\n for sample in samples:\n self.resolwe.api.sample(sample).remove_from_collection.post({'ids': [self.id]})\n\n self.samples.clear_cache()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rename sample names by `mapper`
def rename_samples(self, mapper: Mapper) -> None: if isinstance(mapper, dict) or callable(mapper): if isinstance(mapper, dict): if self.__internal_samples.index.isin(list(mapper.keys())).sum() == len( mapper ): self._rename_samp...
[ "def _rename_samples_by_map(self, map_like: Mapper, **kwargs) -> Optional[Mapper]:\n self.__internal_samples.rename(mapper=map_like, axis=0, inplace=True)\n return self._ratify_action(\"_rename_samples_by_map\", map_like, **kwargs)", "def rename_sample(self, new_name, plate_locations):\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Drop samples by sample identifiers.
def drop_sample_by_id( self, ids: AnyGenericIdentifier, **kwargs ) -> Optional[AnyGenericIdentifier]: target_ids = np.asarray(ids) if self.xsid.isin(target_ids).sum() == len(target_ids): return self._remove_samples_by_id(target_ids, **kwargs) else: raise Value...
[ "def _remove_samples_by_id(\n self, ids: AnyGenericIdentifier, **kwargs\n ) -> Optional[AnyGenericIdentifier]:\n tmp_ids = np.asarray(ids, dtype=self.__internal_samples.index.dtype)\n if len(tmp_ids) > 0:\n self.__internal_samples.drop(tmp_ids, inplace=True)\n return self._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge samples by `variable`.
def merge_samples_by_variable( self, variable: Union[str, int], aggfunc: Union[str, Callable] = "mean", **kwargs ) -> Optional[Mapper]: ret = {} if variable not in self.__internal_samples.columns: raise TypeError("`variable` is invalid.") groups = ...
[ "def merge_single_process(self):\n sample_names = [sample.name for sample in self.samples]\n duplicates_names = set([x for x in sample_names if sample_names.count(x) > 1])\n for name in duplicates_names:\n duplicate_samples = [s for s in self.samples if s.name == name]\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads lines from stdin pipe and yields results onebyone.
def stdin(): while sys.stdin in select.select([sys.stdin], [], [], 0)[0]: line = sys.stdin.readline() if not line: yield from [] break line = line.strip() yield line
[ "def iterate_stdin():\n\n while True:\n try:\n line = sys.stdin.readline()\n except KeyboardInterrupt:\n raise StopIteration\n\n if not line:\n raise StopIteration\n\n yield line.strip()", "def read_lines(prompt=\"\"):\n if os.isatty(sys.stdin.fil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes iterator (list or generator) `lines` and spawns `procs` processes, calling `func` with prefined arguments `args` and `kwargs`. Using a queue and multiprocessing to call `func` with the format func(line, args, kwargs)
def parallel(lines, func, args, kwargs, procs=1): # Start a queue with the size of processes for jobs and a result queue to # collect results q_res = mp.Queue() q_job = mp.Queue(maxsize=procs) # print lock iolock = mp.Lock() # Start the pool and await queue data pool = mp.Pool(procs, ...
[ "def _parallel_apply(func, iterable, n_jobs, sep='\\n', out_stream=sys.stdout):\n # if there is only one job, simply read from iterable, apply function\n # and write to outpu\n if n_jobs == 1:\n for each in iterable:\n out_stream.write(str(func(each)) + sep)\n out_stream.flush()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Run object by reading in a CSV per the pandas read_csv function.
def read_csv(cls, filepath, name=None, description="", **kwargs): name = filepath if name is None else name return Run(read_csv(filepath, **kwargs), name=name, description=description)
[ "def from_csv(cls, name, csv, **kwargs):\r\n data = pd.read_csv(csv, **kwargs)\r\n return Dataset(name, data, **kwargs)", "def from_csv(file):\n return Replay(Replay.load_csv(file))", "def from_csv(self, path):\n for model, table in [(self.Dataset, 'dataset'),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=> Verify that can clear all breakpoints.
def test_40_clear_all(self): break_bar = {"gdb": "break Bar\n", "lldb": "breakpoint set --fullname Bar\n"} for backend, spec in subtests.items(): with self.subTest(backend=backend): e.Ty(spec['launch'], delay=1) e.Ty(break_bar[backend]) e.Ty(sp...
[ "def debugger_clear_all_breakpoints():", "def debugger_clear_breakpoint():", "def clear_all_breakpoints(self):\r\n #clear all the breakpoints in each engine\r\n console = self.app.toolmgr.get_tool('Console')\r\n engines = console.get_all_engines()\r\n\r\n for eng in engines:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a random set of bias model parameters for this feedback modality in this environment.
def init_bias_params(self, rng): return self.bias_prior.sample(rng)
[ "def init_parameters():\n return {'w': random.uniform(-1, 1) * 0.001, 'b': 0}", "def get_bias(self):\n bias_obj = {}\n\n for bias_name, module_address, parameter_address in self.configs_list:\n bias_obj[bias_name] = self.get_config(module_address, parameter_address)\n\n # get no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prior for the bias parameters.
def bias_prior(self):
[ "def init_bias_params(self, rng):\n return self.bias_prior.sample(rng)", "def get_bias(self):", "def priorLikelihood(self, theta, prior):", "def biasDecisionStump():\n global bias\n minErr = 0\n minBias = 0\n _y = np.sort(y)\n for i in range(len(_y)):\n bias = y[i]\n _Err,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute log likelihood of given human data under the current reward and bias model parameters.
def log_likelihood(self, data, reward_model, bias_params):
[ "def log_likelihood_grad_rew(self, data, reward_model, bias_params):", "def log_likelihood_grad_bias(self, data, reward_model, bias_params):", "def log_likelihood(self) -> tf.Tensor:\n # K⁻¹ + GᵀΣ⁻¹G = LLᵀ.\n l_post = self._k_inv_post.cholesky\n num_data = self.observations_index.shape[0]\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute gradient of log likelihood of human data with respect to reward parameters only.
def log_likelihood_grad_rew(self, data, reward_model, bias_params):
[ "def log_likelihood_grad_bias(self, data, reward_model, bias_params):", "def grad_log(self, X):\n # \"\"\"\n # Evaluate the gradients (with respect to the input) of the log density at\n # each of the n points in X. This is the score function.\n\n # X: n x d numpy array.\n XB = np.do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute gradient of log likelihood of human data with respect to bias parameters only.
def log_likelihood_grad_bias(self, data, reward_model, bias_params):
[ "def log_likelihood_grad_rew(self, data, reward_model, bias_params):", "def log_likelihood_gradient(y, tx, w):\n return tx.T.dot(sigmoid(tx.dot(w))-y)", "def grad_llh(self, params):\n grad = np.clip(self.grad_log_likelihood(params[0], params[1], params[2:]), SMALLEST_NUMBER,\n LA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a motor step position to absolute mm.
def step2mm(step): return step / KST101.STEPS_PER_MM
[ "def mm2step(pos):\n return pos * KST101.STEPS_PER_MM", "def px2mm(self, value):\n return value / (self.dpi / 25.4)", "def to_native_units(self, motor):\n return self.percent / 100 * motor.max_speed", "def mm_to_m(millimeters):\n return millimeters / 1000.0", "def get_position(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert an absolute position to a number of steps.
def mm2step(pos): return pos * KST101.STEPS_PER_MM
[ "def backtrack_steps():\n\n # Initialize position and number of steps\n x = 0\n n_steps = 0\n\n # Walk until we get to positive 1\n while x < 1:\n x += 2 * np.random.randint(0, 2) - 1\n n_steps += 1\n\n return n_steps", "def get_steps_num():\n return 0", "def steps_to_angl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open serial port and connect to controller. port should be a serial device node (or serial port name on Windows. If debug is set to true, raw messages are printed to stdout. dst is the motor address, defaults to value for directly attached motor. Inbuilt source assumes this is running on a PC (0x01). This also assumes ...
def __init__(self, port='/dev/ttyUSB0', debug=False, dst=0x50): # Motor parameters self.__pos = -1 self.__status = 0xFFFFFFFF self.__param_lock = threading.Lock() # self.__chan = 0x01 # Controller only has one channel, number 1. self.__debug = debug self.__src = 0x01 # 0x01 = PC Controll...
[ "def open(self):\n self.serial.port = self.name\n self.serial.timeout = self.ctrl_client.ser_rtimeout\n self.serial.write_timeout = self.ctrl_client.ser_wtimeout\n self.serial.inter_byte_timeout = self.ctrl_client.ser_itimeout\n self.serial.parity = self.ctrl_client.ser_parity\n self.serial.baudra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a single "short format" (6byte) message to the controller. msg_id is the 2byte message code with byte parameters param1 & 2. Returns nothing.
def __send_short(self, msg_id, param1, param2): data_out = struct.pack("<HBBBB", msg_id, param1, param2, self.__dst, self.__src) if self.__debug: print ">>> %s" % binascii.hexlify(data_out) self.__ser.write(data_out) self.__ser.flush()
[ "def send_protocol_message(self, msg):\n self.conn.send(msg + \"\\0\")", "def sendmsg(self, msg):\n self.client.send(msg.encode())", "def send_single(self, pid, msg_type, msg=\"\"):\r\n m = Message(self._id, pid, msg_type, msg)\r\n self._io.send(m)", "def send(self, msg: tgpdu.TGMess...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send long sends a packet in the "longformat" (>6byte) format to the controller. msg_id is the 2byte ID code and data should be the raw payload to include.
def __send_long(self, msg_id, data): # Long format packets have the upper bit of DST set. data_out = struct.pack("<HHBB", msg_id, len(data), self.__dst | 0x80, self.__src) data_out += data if self.__debug: print ">>> %s" % binascii.hexlify(data_out) self.__ser.write(...
[ "def read_long_long(data):\n s_type = \"=%s\" % get_type(\"long_long\")\n return struct.unpack(s_type, data.read(8))[0]", "def __send_short(self, msg_id, param1, param2):\n data_out = struct.pack(\"<HBBBB\", msg_id, param1, param2,\n self.__dst, self.__src)\n if self.__debug:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decodes a status message payload from the controller and updates the local state of the motor. This function is thread safe.
def __decode_status(self, data): chan, pos, _, status = struct.unpack("<HllL", data) if chan != self.__chan: # Unknown channel, ignore return self.__param_lock.acquire() self.__pos = pos self.__status = status self.__param_lock.release()
[ "def handle(self):\n global latest_status\n data = self.request[0]\n socket = self.request[1]\n logging.info(\"Received {} bytes from {}\".format(len(data), self.client_address[0]))\n jss = interface.joystick_status_pb2.JoystickStatus()\n jss.ParseFromString(data)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable/disable automatic sending of update messages. Freq sets the frequency of the messages (if enabling, otherwise parameter is ignored.
def en_update_msg(self, enable=True, freq=64): if enable: self.__send_short(self.MGMSG_HW_START_UPDATEMSGS, freq, 0x00) else: self.__send_short(self.MGMSG_HW_STOP_UPDATEMSGS, 0x00, 0x00)
[ "def set_update_rate(self, delay_ms):\n self._log_msg_start(\"Setting NMEA message update rate\")\n self._ubx.send(\"CFG-RATE\", measRate=delay_ms, navRate=1, timeRef=1)", "def set_frequency(miner: Miner, login, frequency):\n #default for S9 is 550\n #\"bitmain-freq\" : \"550\",\n commands ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }