query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Default curvature is convex.
def func_curvature(self): return u.Curvature.CONVEX
[ "def curvature(self):\n return 1.0/self.radius()", "def curvature_pt(self, params):\n pass", "def curvature(self):\n return self.circle().curvature(self.o, self.r, p = self.a)", "def set_curvature(self, f_convex=0):\n self.F_CONVEX = f_convex", "def curvature(x, y):\n dalpha =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the sensitivity of the AddButton depends on the AccountConfig.
def _on_account_config_changed(self, _, state: bool): if state: self.add_button.grab_default() self.add_button.set_sensitive(state)
[ "def enable(self): \n self.feed_button.config(state=\"normal\")\n self.eat_button.config(state=\"normal\") \n for t in range(self.player.game.trait_limit): \n self.add_trait_buttons[t].config(state=\"normal\") \n self.add_population_button.config(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all recipe names for a given recipe_type
def get_recipes_by_type(self, recipe_type): if (recipe_type in self.recipe_list): for item in self.recipe_list[recipe_type]: print(item.name + " ", end='') print()
[ "def get_recipes_by_types(self, recipe_type):\n recipe_names = []\n for recipe in self.recipe_list[recipe_type]:\n recipe_names.append(recipe.name)\n return recipe_names", "def get_recipes_by_types(self, recipe_type):\n if recipe_type not in self.recipe_list.keys():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a recipe to the book and update last_update
def add_recipe(self, recipe): self.recipe_list[recipe.recipe_type].append(recipe) self.last_update = datetime.now
[ "def add_recipe(self, recipe):\n from recipe import Recipe\n #isinstance()\n if isinstance(recipe, Recipe):\n\n # self.recipes_list.update({recipe.recipe_type : recipe})\n self.recipes_list[recipe.recipe_type].append(recipe)\n\n # update last_update\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes the synapse loss of a projection
def projectionwise_synapse_loss(self, proj, marocco): orig_weights = proj.getWeights(format='array') mapped_weights = marocco.stats.getWeights(proj) syns = np.where(~np.isnan(orig_weights)) realized_syns = np.where(~np.isnan(mapped_weights)) orig = len(syns[0]) realized =...
[ "def compute_reprojection_loss(self, pred, target):\n \n abs_diff = torch.abs(target - pred)\n l1_loss = abs_diff.mean(1, True)\n\n ssim_loss = self.ssim(pred, target).mean(1, True)\n \n# photometric error function pe\n \n reprojection_loss = 0.85 * ssim_loss + 0.15 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for a vertex in the 2nd position of List(int, str) and return index.
def search_vertex(ls, vertex): for idx in range(len(ls)): if ls[idx][1] == vertex: return idx
[ "def index_vertices(vertexlist, graph):\n return_list = list()\n for vertex in vertexlist:\n return_list.append(graph.vs.find(name=vertex).index)\n return return_list", "def find_vertex_index(graph, uri_str, brackets=False):\n\tif brackets:\n\t\turi_str = '<'+uri_str+'>'\n\n\ttry:\n\t\treturn grap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implementation of Dijkstra's single source shortest path using the Heap data structure. Reduced time complexity from O(mn), where n is the number of vertices and m is the number of edges; to O((m+n) logn)
def dijkstra_heap(graph, source_vertex): x = set() heap = [] shortest_key = {source_vertex: 0} heapq.heappush(heap, (0, source_vertex)) for v in graph.keys(): if v != source_vertex: shortest_key[v] = float('inf') heapq.heappush(heap, (float('inf'), v)) while hea...
[ "def dijkstra(self, src):\n unvisited = MinHeap() \n visited = set()\n dist = []\n for v_id in range(0, self.v):\n if v_id != src:\n dist.append(sys.maxsize)\n unvisited.insert((sys.maxsize, v_id))\n else:\n unvisi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
As different modalities are not oriented in the same space when converted and as fslorient2std affects only the sform and not the qform. 1) apply fslorient2std 2) set translational part to zero 3) use nibabel to set the sform as the qform
def orient2std(pfi_in, pfi_out, keep_translation=True): # assert os.path.exists(pfi_in) # pfi_intermediate = os.path.join(os.path.dirname(pfi_out), 'zz_tmp_' + os.path.basename(pfi_in)) # # 1 -- # cmd0 = 'fslreorient2std {0} {1}'.format(pfi_in, pfi_intermediate) # print_and_run(cmd0) # # 2 -- ...
[ "def rectify_header_sform_qform(img_nii):\n d = img_nii.header[\"dim\"][0]\n pixdim = np.asarray(img_nii.header.get_zooms())[:d]\n sform, qform = img_nii.get_sform(), img_nii.get_qform()\n norm_sform = affine_to_spacing(sform, r=d)\n norm_qform = affine_to_spacing(qform, r=d)\n sform_mismatch = no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the depth for the given pair. Returns a tuple (asks, bids); each of these is a list of (price, volume) tuples.
def getDepth(session=None): depth = get_data('depth', requests_session=session).json() if not isinstance(depth, dict): raise TypeError("The response is not a dict.") if not isinstance(depth.get('sell'), list): raise TypeError("The response does not contain an asks list.") if not isinsta...
[ "def _find_level(self, typ, price):\r\n lst = {\"ask\": self.asks, \"bid\": self.bids}[typ]\r\n comp = {\"ask\": lambda x, y: x < y, \"bid\": lambda x, y: x > y}[typ]\r\n low = 0\r\n high = len(lst)\r\n\r\n # binary search\r\n while low < high:\r\n mid = (low + h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create RiskSLIM MIP object
def create_risk_slim(input): assert 'coef_set' in input, 'input is missing coef_set' P = len(input['coef_set']) # setup printing and loading function_print_flag = input['print_flag'] if 'print_flag' in input else False print_from_function = lambda msg: print_log(msg) if function_print_flag else la...
[ "def create(\n self,\n ) -> \"SecurityModel[TPureSNMPType, TX690Type]\": # pragma: no cover\n ...", "def __init__(__self__,\n resource_name: str,\n args: VpcIpamPoolArgs,\n opts: Optional[pulumi.ResourceOptions] = None):\n ...", "def __ini...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert coefficient vector 'rho' into a solution for RiskSLIM CPLEX MIP
def convert_to_risk_slim_cplex_solution(rho, indices, loss=None, objval=None): solution_idx = range(0, indices['n_variables']) solution_val = np.zeros(indices['n_variables']) # rho solution_val[indices['rho']] = rho # alpha alpha = np.zeros(len(indices['alpha'])) alpha[np.flatnonzero(rho[i...
[ "def solve_for_rho2(rho):\n # Calculate pressure and enthalpy from conservation laws\n p = conservation_of_momentum(p1, u1, rho1, rho)\n h = conservation_of_energy(h1, u1, rho1, rho)\n\n # Bring gas to equilibrium at specified enthalpy and pressure\n# air.HP = h, p\n# air.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to set CPLEX parameters of CPLEX MIP object
def set_cplex_mip_parameters(mip, cplex_parameters, display_cplex_progress=False): problem_type = mip.problem_type[mip.get_problem_type()] mip.parameters.randomseed.set(cplex_parameters['randomseed']) mip.parameters.threads.set(cplex_parameters['n_cores']) mip.parameters.output.clonelog.set(0) mip.p...
[ "def set_cplex_objective(cpx: cplex.Cplex, c, Q=None,\n epsilon: float = 1e-4) -> cplex.Cplex:\n n = cpx.variables.get_num()\n\n assert len(c) == n, \"c must have {} items but len(c) is {}\".format(\n n, len(c)\n )\n\n # set linear coefficients\n # cTx\n for i i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a initial feasible solution, rho, produces an improved solution that is 1OPT (i.e. the objective value does not decrease by moving in any single dimension) at each iteration, the algorithm moves in the dimension that yields the greatest decrease in objective value the best step size is each dimension is computed ...
def discrete_descent(rho, Z, C_0, rho_ub, rho_lb, descent_dimensions=None, print_flag=False): #print_flag = False # initialize key variables MAX_ITERATIONS = 500 MIN_IMPROVEMENT_PER_STEP = float(1e-10) n_iterations = 0 P = rho.shape[0] rho = np.require(np.require(rho, dtype=np.int_), dtype=...
[ "def discrete_descent(rho, Z, C_0, rho_ub, rho_lb, get_L0_penalty, compute_loss_from_scores, descent_dimensions = None, active_set_flag = True):\n \"\"\"\n \n \"\"\"\n assert callable(compute_loss_from_scores)\n assert callable(get_L0_penalty)\n\n # initialize key variables\n MAX_ITERATIONS = 5...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
finds the value of rho[j] in feasible_coef_values that minimizes log_loss(rho) + C_0j
def compute_objvals_at_dim(dim_index, feasible_coef_values, base_rho, base_scores, base_loss, C_0): # copy stuff because ctypes scores = np.copy(base_scores) # initialize ...
[ "def convert_to_risk_slim_cplex_solution(rho, indices, loss=None, objval=None):\n solution_idx = range(0, indices['n_variables'])\n solution_val = np.zeros(indices['n_variables'])\n\n # rho\n solution_val[indices['rho']] = rho\n\n # alpha\n alpha = np.zeros(len(indices['alpha']))\n alpha[np.fla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
runs DCD polishing for all solutions in the a solution pool can be stopped early using max_runtime or max_solutions
def discrete_descent_solution_pool(pool, Z, C_0, constraints, max_runtime=float('inf'), max_solutions=float('inf')): # quick return if l...
[ "def ccg_algo(dir:str, tol: float, gamma: int, pv_min: np.array, pv_max: np.array, engagement: np.array, solver_param: dict, day:str, log:bool=False, printconsole:bool=False, warm_start:bool=False, M_neg:float=None):\n\n # Compute the maximal deviation between the max and min PV uncertainty set bounds\n max_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Data dependent initialization for eager execution
def _data_dep_init(self, inputs): from tensorflow.python.ops.nn import moments from tensorflow.python.ops.math_ops import sqrt with variable_scope.variable_scope('data_dep_init'): # Generate data dependent init values activation = self.layer.activation self.l...
[ "def _data_dep_init(self, inputs):\n\n with tf.variable_scope(\"data_dep_init\"):\n # Generate data dependent init values\n activation = self.layer.activation\n self.layer.activation = None\n x_init = self.layer.call(inputs)\n m_init, v_init = tf.moments(x_init, self.norm_axes)\n sc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes a file or a directory even if they don't exist
def remove(path): if os.path.isfile(path): try: os.remove(path) except OSError as e: if e.errno != errno.ENOENT: raise elif os.path.isdir(path): try: shutil.rmtree(path) except FileNotFoundError: return
[ "def remove(filename):\n if os.path.isfile(filename):\n os.remove(filename)\n elif os.path.islink(filename):\n os.remove(filename)\n elif os.path.isdir(filename):\n shutil.rmtree(filename)", "def rm_path(path):\n if os.path.exists(path):\n if os.path.isdir(path):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Represent this collection as a list of `asdf.ExternalArrayReference` objects.
def external_array_references(self): return self._to_ears(self.fileuris)
[ "def references(self) -> \"IterableList[Reference]\":\n return Reference.list_items(self)", "def flat_references(self):\n flat_refs = []\n flat_refs.extend(self.references)\n flat_refs.extend(flat_references(self.datasets))\n return flat_refs", "def references(self):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of file names referenced by this Array Container.
def filenames(self): names = [] for furi in np.asarray(self.fileuris).flat: names.append(furi) return names
[ "def filenames(self):\n return [x.filename for x in self.files]", "def embeddedFileNames(self):\n filenames = []\n self._embeddedFileNames(filenames)\n return filenames", "def filenames(self):\n return self._files.keys()", "def filenames(self):\n return self.latest()[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stack a loader array along each of its dimensions. This results in a dask array with the correct chunks and dimensions.
def stack_loader_array(loader_array): if len(loader_array.shape) == 1: return da.stack(loader_to_dask(loader_array)) stacks = [] for i in range(loader_array.shape[0]): stacks.append(stack_loader_array(loader_array[i])) return da.stack(stacks)
[ "def _create_dask_array(\n self, lif: LifFile, selected_scene_dims: List[str]\n ) -> xr.DataArray:\n # Always add the plane dimensions if not present already\n for dim in REQUIRED_CHUNK_DIMS:\n if dim not in self.chunk_dims:\n self.chunk_dims.append(dim)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map a call to `dask.array.from_array` onto all the elements in ``loader_array``. This is done so that an explicit ``meta=`` argument can be provided to prevent loading data from disk.
def loader_to_dask(loader_array): if len(loader_array.shape) != 1: raise ValueError("Can only be used on one dimensional arrays") # The meta argument to from array is used to determine properties of the # array, such as dtype. We explicitly specify it here to prevent dask # trying to auto calc...
[ "def load_array_meta(loader, filename, index):\n return loader(filename, index)", "def load_array(loader, filename, index):\n return loader(filename, index)", "def stack_loader_array(loader_array):\n if len(loader_array.shape) == 1:\n return da.stack(loader_to_dask(loader_array))\n stacks = [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the bot's token from disk.
def read_discord_token(): token_file = Path("./token") if token_file.exists(): with open("token", "r") as f: return "".join(f.readlines()).strip()
[ "def read_token_file(self):\n return open(self.token_file).read().strip()", "def _read_token(self):\n with open(self.keys_path) as data_file:\n return json.load(data_file)", "def read_token_file(self):\r\n try:\r\n with open(self._token_file, 'r') as token_file:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sort the months in chronological order and return them
def sort_the_months(inp_arr): if inp_arr != '': inp_list = [] for i in inp_arr.split(): inp_list.append(int(i.strip())) in_months = [rev_lookup_months.get(i,0) for i in inp_list] # picking up the month names using reverse lookup return sorted(in_months,key=months.get)...
[ "def get_months(self):\n m = []\n for post in self:\n d = \"-\".join(post.Date.split(\"-\")[:2])\n m.append(d)\n return list(sorted(set(m), reverse=True))", "def get_months(self, namespace):\n\n # TODO: check if this limitation still exists in Django 1.6+\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the closest next Determination Date for a given CLO
def next_determination_date(ddates,clo_idx): dd = ddates.loc[ddates['Fund']==clo_idx,'Determination Date'] next_ddate = min(dd.loc[dd>pd.Timestamp.today()], key=lambda s: (s-pd.Timestamp.today())) return next_ddate
[ "def next_payment_date(ddates,clo_idx):\n dd = ddates.loc[ddates['Fund']==clo_idx,'Payment Date'].dropna()\n next_date = min(dd.loc[dd>pd.Timestamp.today()], key=lambda s: (s-pd.Timestamp.today()))\n return next_date", "def prior_determination_date(ddates,clo_idx):\n dd = ddates.loc[ddates['Fund']==cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the closest previous Determination Date for a given CLO
def prior_determination_date(ddates,clo_idx): dd = ddates.loc[ddates['Fund']==clo_idx,'Determination Date'] prior_ddate = max(dd.loc[dd<pd.Timestamp.today()], key=lambda s: (s-pd.Timestamp.today())) return prior_ddate
[ "def next_determination_date(ddates,clo_idx):\n dd = ddates.loc[ddates['Fund']==clo_idx,'Determination Date']\n next_ddate = min(dd.loc[dd>pd.Timestamp.today()], key=lambda s: (s-pd.Timestamp.today()))\n return next_ddate", "def get_prev_close(self):\n prev_day = list(self.portfolio_history.keys()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the closest next Determination Date for a given CLO
def next_payment_date(ddates,clo_idx): dd = ddates.loc[ddates['Fund']==clo_idx,'Payment Date'].dropna() next_date = min(dd.loc[dd>pd.Timestamp.today()], key=lambda s: (s-pd.Timestamp.today())) return next_date
[ "def next_determination_date(ddates,clo_idx):\n dd = ddates.loc[ddates['Fund']==clo_idx,'Determination Date']\n next_ddate = min(dd.loc[dd>pd.Timestamp.today()], key=lambda s: (s-pd.Timestamp.today()))\n return next_ddate", "def prior_determination_date(ddates,clo_idx):\n dd = ddates.loc[ddates['Fund'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates the new Moody's Ratings Factor based on the old Moody's rating. !!! This needs to have the old WARF logic added, just a place holder ATM !!!
def moodys_adjusted_warf_old(df): # moodys_score: dataframe with alphanumeric rating to numeric map (1 to 1 map; linear) moodys_score = pd.DataFrame([[ 'Aaa',1],['Aa1',2],['Aa2',3],['Aa3',4], ['A1',5],['A2',6],['A3',7],['Baa1',8],['Baa2',9], ['Baa3',10],['Ba1',11],['Ba2',12],['B...
[ "def _transform_rating(rating: int) -> int:\n return int(np.power(10, (rating / 400)))", "def __updateRatings(oldRatings, winner):\n r1, r2 = oldRatings\n R1 = 10 ** (float(r1) / 400)\n R2 = 10 ** (float(r2) / 400)\n E1 = R1 / (R1 + R2)\n E2 = R2 / (R1 + R2)\n\n S1 = 0\n S2 = 0\n if winne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function get the S&P recovery rate as a percent. If it doesn't exist in the master field, it will look up in the appropriate first and second lien tables, if not, will look up the bond table.
def sp_recovery_rate(model_df): new_rr_map = {'1+(100)': 0.75, '1(95%)': 0.70, '1(90%)': 0.65, '2(85%)': 0.625, '2(80%)': 0.60, '2(75%)': 0.55, '2(70%)': 0.5, '3(65%)': 0.45, '3(60%)': 0.4...
[ "def recovery_percentage(self):\n return self._recovery_percentage", "def lsnicmpdrppktsrate(self) :\n\t\ttry :\n\t\t\treturn self._lsnicmpdrppktsrate\n\t\texcept Exception as e:\n\t\t\traise e", "def recover(self):\r\n return((self.num_recover / self.num_cases) * 100)", "def lsnudpdrppktsrate(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Per the Virtus Compliance Reports, the Indenture and the CheatsheetSpreadsheet the WAS is based on the 'Effective Spread' which is neither the Floating Spread, nor the AllinRate in the files, but rather derived from the Floating Spread and the Floor vis a vis LIBOR. It is possible that this needs further refinement, bu...
def Weighted_Average_Spread(clo_df,col,libor=.002): clo_df = Specified_Assets(clo_df,col) # This should be a view, not a copy: sub CCC excluded #mask = (clo_df['Asset Type']!='Bond') & (clo_df[col] > 0) & (~clo_df['Spread'].isna()) # Bonds are excluded too mask = (clo_df[col] > 0) & (~clo_df['Spread...
[ "def new_fixed_assets(self) -> float:\n old_depot_ppe = (\n self.balance_sheet.assets.of_which_pe * self.inputs.ppe_pct_depot\n )\n old_fleet_net_value = self.balance_sheet.assets.of_which_fleet\n\n adjustment_factor = (\n self.inputs.trucks_total / self.operations....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wait for the container to emit logs satisfying the predicate.
def wait_for_logs(container, predicate, timeout=None, interval=1): if isinstance(predicate, str): predicate = re.compile(predicate, re.MULTILINE).search start = time.time() while True: duration = time.time() - start stdout = container.get_logs()[0].decode() stderr = container...
[ "def _wait(self, condition, msg, log_after, timeout_timer):\n\n log_timer = None\n if log_after != 0:\n log_timer = timeutils.StopWatch(duration=log_after)\n log_timer.start()\n\n while condition():\n if log_timer is not None and log_timer.expired():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Numerically calculate the energy of a wave function generated by `h_static`. For n=1, we'd like to see if we can backcalculate E = 1/2.
def calc_energy(n: int) -> float: E = -2 / (n + 1) ** 2 x, ψ = h_static(E) # Calculate potential between the e- field and the nucleus point by integrating. # todo: Let's do this manually first, then try to apply a scipy.integrate approach. dx = 1 result = 0 ψ2 = np.conj(ψ) * ψ sampl...
[ "def energy_tot(self, n):\n return self.energy(n) + self.coulomb_nuclei()", "def self_energy(gf_imp0, gf_imp):\n return 1/gf_imp0 - 1/gf_imp", "def energy_requirement(n, f=0.01, N_b=7.3E21, T=300):\n k_B = 1.38064852E-23 \n annual_seconds = 3.154E7 # number of seconds in a year\n \n try:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a distance, calculate the potential energy between 2 n=1 S orbital hydrogen atoms
def h2_potential(dist: float) -> float: pass
[ "def distance(atom_1, atom_2):\n result = 0.0\n for i in range(3):\n result += pow(atom_1.position[i] - atom_2.position[i], 2)\n return math.sqrt(result)", "def get_potential_energy(particle1, particle2):\n pos_diff = Particle.vector_between(particle1, particle2)\n return -1 * (G * particle1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calcualte the electric potential between 2 hydrogen atoms
def h2_potential(x: float) -> float: # Start with the perspectic of one atom. Calculate the interaction between # its nucleus and the other atom's nucleus, and electron. # Our convention will be attraction is positive potential. n = 1 E = -2 / (n + 1) ** 2 H = Hydrogen3d([0, 1]) nuc_nuc_V...
[ "def get_potential_energy(particle1, particle2):\n pos_diff = Particle.vector_between(particle1, particle2)\n return -1 * (G * particle1.mass * particle2.mass) / np.sqrt(\n np.dot(pos_diff, pos_diff))", "def bond_potential(self):\n \n distance = mag(self.atom2.pos - self.atom1.pos)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calcualte the electric potential between 2 hydrogen atoms. In this function, we view things from the perspective of the proton of one of the atoms, and calculate everything else relative to it.
def h2_force_pov(x: float) -> float: # Start with the perspectic of one atom. Calculate the interaction between # its nucleus and the other atom's nucleus, and electron. # Our convention will be that towards our POV nucleus is positive; # repulusion from it is negative. H = Hydrogen3d([0, 1]) ...
[ "def h2_potential(x: float) -> float:\n\n # Start with the perspectic of one atom. Calculate the interaction between\n # its nucleus and the other atom's nucleus, and electron.\n\n # Our convention will be attraction is positive potential.\n n = 1\n E = -2 / (n + 1) ** 2\n H = Hydrogen3d([0, 1])\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MediaDirectorBridge should be configured per each viewport to properly translate director geometry to viewport geometry and provide separation and service granularity.
def __init__(self, adhoc_media_pool_publisher, viewport_name, media_type='video'): self.viewport_name = viewport_name self.adhoc_media_pool_publisher = adhoc_media_pool_publisher self.media_type = media_type
[ "def SetupView(self):\r\n size = self.GetClientSizeTuple()\r\n height = self.maxtop - self.maxbottom\r\n width = self.maxright - self.maxleft\r\n \r\n #The ratio of the width to the height in the client-area\r\n screenratio = float(size[0]) / float(size[1])\r\n \r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translates director messages to AdhocMedias message.
def translate_director(self, data): adhoc_medias = self._extract_adhoc_media(data) logger.info("Publishing AdhocMedias: %s" % adhoc_medias) self.adhoc_media_pool_publisher.publish(adhoc_medias)
[ "def _extract_adhoc_media(self, data):\n # first get assets\n medias = extract_first_asset_from_director_message(data, self.media_type, self.viewport_name)\n logger.info(\"Got assets for %s based media player %s\" % (self.media_type, medias))\n # and wrap them inside AdhocMedia\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list containing AdhocMedia objects extracted from director message for specified viewport specific to adhoc_media that this instance of bridge is configured for.
def _extract_adhoc_media(self, data): # first get assets medias = extract_first_asset_from_director_message(data, self.media_type, self.viewport_name) logger.info("Got assets for %s based media player %s" % (self.media_type, medias)) # and wrap them inside AdhocMedia adhoc_medias...
[ "def _build_adhoc_medias(self, media_list, media_type):\n adhoc_medias = []\n media_id = 0\n for media in media_list:\n media_name = 'adhoc_media_' + media_type + '_' + self.viewport_name + '_' + str(media_id)\n adhoc_media = AdhocMedia()\n adhoc_media.id = medi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts json medias list and converts them into AdhocMedias per any media type.
def _build_adhoc_medias(self, media_list, media_type): adhoc_medias = [] media_id = 0 for media in media_list: media_name = 'adhoc_media_' + media_type + '_' + self.viewport_name + '_' + str(media_id) adhoc_media = AdhocMedia() adhoc_media.id = media_name ...
[ "def _extract_adhoc_media(self, data):\n # first get assets\n medias = extract_first_asset_from_director_message(data, self.media_type, self.viewport_name)\n logger.info(\"Got assets for %s based media player %s\" % (self.media_type, medias))\n # and wrap them inside AdhocMedia\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Syncs the local documents via hg.
def sync_hg(store, path): storedir, _ = os.path.split(path) # get or update the storage if os.path.isdir(os.path.join(storedir, ".hg")): client = hglib.open(storedir) client.pull(update=True, force=True) else: # Strip off three characters for hg+ client = hglib.clone(stor...
[ "def do_sync(d, local_path, remote_path = 'Document'):\n d.sync(local_path, remote_path)", "def sync(org_file):\n commands.sync(org_file)", "def sync():\n\n rsync_project(remote_dir=WORKDIR, local_dir='.', delete=True,\n exclude=['*.pyc', '*.DS_Store', '.git', '.cache/*', '*json', '*pk...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all the dn behaviors in doing where eid is the target.
def active_target_of(doing, eid): if eid is None: return for dn in doing.values(): tgt_eid = dn.behavior_target_id() if tgt_eid == eid: yield dn
[ "def get_targets():\n # Use a list comp because querying MODM with Guid.find(Q('referent', 'eq', None))\n # only catches the first case.\n return [each for each in Guid.find() if each.referent is None]", "def get_target_directed_relationships(self, eClass=None):\n raise NotImplementedError(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lookup or add generic token for entity.
def token(self, ent): if ent.eid in self.lookup: return self.lookup[ent.eid] if ent.tid == data.AGENT_TYPE_ID: prefix = 'A' elif ent.tid in data.combatants: prefix = 'C' elif ent.tid in data.gatherable: prefix = 'G' ct = self.counts[prefix] self.counts[prefix] += 1 ...
[ "def add_entity(self, entity):\n entity_type = str(type(entity)).lower()\n if 'acl' in entity_type:\n entity_ref = entity.submit()\n entity_type = 'acl'\n elif 'secret' in entity_type:\n entity_ref = entity.store()\n entity_type = 'secret'\n el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
All the cases for a given node are in the transitions to that node.
def all_case_groups(self, node_tag): for tag in self.reverse_edges[node_tag]: for from_grp,to_grp in self.nodes[tag].transitions[node_tag]: yield to_grp
[ "def _is_case_for_node(self, case_node, node):\n next_node = case_node.getnext()\n while next_node is not None and self._remove_prefix(next_node) != \"break\":\n # node is subnode of node controled by case\n if self._is_ancestor(next_node, node):\n return True\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print Pandas dataframes side by side in python notebook
def display_side_by_side(*args): html_string = '' for df in args: html_string += df.to_html(index=False, header=True) display_html(html_string.replace('table', 'table style="display:inline"'), raw=True)
[ "def display_side_by_side(*args:\"pandas.DataFrame, pandas.Series\", drop_index:\"bool\"=False)-> \"None\":\n from IPython.display import display_html\n \n strHtml = ''\n for df in args:\n \n if isinstance(df, pandas.Series):\n df = df.to_frame()\n if drop_index:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Join all the tables in dataframe
def merge_tables(): # get sql connection conn = get_sql_conn() # get all info from materials table query_mat = 'Select * from material_procurement' df_mat = pd.read_sql_query(query_mat, con=conn) df_mat = df_mat.drop(['uid'], axis=1) df_mat = df_mat.pivot(index='ball_milling_uid',...
[ "def join_tables(database, query):\n\n table_names = query[\"from\"]\n\n if \"*\" in table_names:\n table_names = list(database)\n\n result_table = database[table_names[0]]\n \n \n for table in table_names[1:]:\n other_table = database[table]\n result_table = cartesian...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read log files and create a dict of zip files processed
def getAllEntries(self): log_entries_dict = collections.defaultdict(list) for logfile in os.listdir(self.log_folder): log = os.path.join(self.log_folder, logfile) with open(log, 'rb') as l: logCSVreader = csv.reader(l, delimiter="|") logCS...
[ "def archive_logs():\n logging.info('Archive start...')\n\n for log_dir in filter(dir_filter, os.listdir('logs')):\n path = 'logs/{}'.format(log_dir)\n archive_files = filter(lambda x: '.log.' in x, os.listdir(path))\n zip_file_name = '{}/{}.zip'.format(\n path,\n st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process all the labels that occur in tex This works by scanning for commands and environments that alter numbering as well as any LaTeX labelling commands.
def process_labels(ctx, tex, chapter): headings = ['chapter'] + ['sub'*i + 'section' for i in range(4)] reh = r'(' + '|'.join(headings) + r'){(.+?)}' environments = ['thm', 'lem', 'exc', 'figure', 'equation'] ree = r'begin{(' + '|'.join(environments) + r')}' rel = r'(\w+)label{(.+?)}' rel2 = r'l...
[ "def _FindLabels(self):\n texs = \" \".join(glob.glob(\"*.tex\"))\n cat_process = subprocess.Popen(shlex.split(\"cat %s\" % texs),\n stdout=subprocess.PIPE)\n grep_process = subprocess.Popen(shlex.split(r\"grep \\\\\\\\label\"),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the next command in tex that occurs at or after pos
def next_command(tex, pos): rx = re.compile(r'\\([a-zA-Z0-9]+\*?)') m = rx.search(tex, pos) if m: optargs, args, t, j = chomp_args(tex, m.end()) cmd = command(m.group(1), optargs, args, m.start(), j) return cmd return None
[ "def GetCurrentToken(tokens, pos):\n i = 0\n while i < len(tokens):\n if pos > tokens[i].start and pos < tokens[i].end:\n return tokens[i]\n if pos < tokens[i].start:\n return tokens[i-1] if i > 0 else None\n i += 1\n\n return tokens[len(tokens)-1] if tokens else None", "def next(self):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
These command break out of math mode
def process_mathbreaker_cmd(ctx, text, cmd, mode): if mode & MATH: return process_cmd_passthru(ctx, text, cmd, mode | MATHBREAK) return process_cmd_strip(ctx, text, cmd, mode)
[ "def cmd_calculation():", "def calc(equation):", "def test01_math_operators(self):\n\n import _cppyy\n number = _cppyy.gbl.number\n\n assert (number(20) + number(10)) == number(30)\n assert (number(20) + 10 ) == number(30)\n assert (number(20) - number(10)) == number(10...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an environment that is started by begincmd.
def get_environment(tex, begincmd): name = begincmd.args[0] pos = begincmd.end optargs, args, t, pos0 = chomp_args(tex, pos) pos = pos0 d = 1 regex = r'\\(begin|end){{{}}}'.format(re.escape(name)) rx = re.compile(regex) while d > 0: m = rx.search(tex, pos) if not m: ...
[ "def get_environment(self):\r\n return self.mcas[0].get_environment()", "def getEnv():", "def getEnvironment(self):\n pass", "def get_env(self):\n return self.env", "def NetworkBase_getEnvironment(*args):\n return _yarp.NetworkBase_getEnvironment(*args)", "def get_environment():\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
detect intrusion between 2 packets per time intervals
def detect_intrusion(packet1, packet2, ips, malicious_ips): for i in range(len(packet2.packets)): packet_per_time1 = packet1.packets[i] packet_per_time2 = packet2.packets[i] for ip, tup in packet_per_time1.packets_map: sent, received = tup
[ "def test_along_scan(self) :\n bt7 = self.get_ch(7)\n refl_test = np.logical_or(self.refl.refl_minus3 < 0.2,\n self.refl.refl_plus3 < 0.2)\n test320 = bt7.data[:] < 320\n test = np.logical_and(\n np.logical_and(test320, bt7.data[:] < self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Multiplies two quaternions according to Hamilton's convention q3 = q1 q2
def quatMultiply(q1, q2): q1 = q1.flatten() q2 = q2.flatten() q3 = np.zeros(4) q3[0] = q1[0] * q2[0] - np.dot(q1[1:], q2[1:]) q3[1:] = (q1[0] * q2[1:] + q2[0] * q1[1:] + np.cross(q1[1:], q2[1:])) return (q3 / np.linalg.norm(q3)).reshape(-1, 1)
[ "def multiply_quaternions(quats1,quats2):\n w1 = quats1[:,0]\n x1 = quats1[:,1]\n y1 = quats1[:,2]\n z1 = quats1[:,3]\n\n w2 = quats2[:,0]\n x2 = quats2[:,1]\n y2 = quats2[:,2]\n z2 = quats2[:,3]\n\n res = np.zeros((quats1.shape[0],4))\n \n res[:,0] = w1 * w2 - x1 * x2 - y1 * y2 - z...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms a vector, v into a different frame with the transformation represented as a quaternion
def quatPassiveRot(q, v): v_q = np.zeros((4, 1)) v_q[1:] = v v_qnew = quatLeftMat(q).T @ quatRightMat(q) @ v_q return v_qnew[1:]
[ "def reflect(q, v):\n q = np.asarray(q)\n v = np.asarray(v)\n\n # Convert vector to quaternion representation\n quat_v = _promote_vec(v)\n return multiply(q, multiply(quat_v, q))[..., 1:]", "def qrot(q, v):\n assert q.shape[-1] == 4\n assert v.shape[-1] == 3\n assert q.shape[:-1] == v.shap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms an active quaternion, q into a DCM
def quat2DCM(q): DCM = quatLeftMat(q) @ quatRightMat(q).T DCM = DCM[1:, 1:] return DCM
[ "def dcm_to_quaternions(dcm):\n trace = np.trace(dcm)\n b_2 = (1/4)*np.array([(1+trace), (1 + 2*dcm[0, 0] - trace), (1 + 2*dcm[1, 1] - trace), (1 + 2*dcm[2, 2] - trace)])\n argmax = np.argmax(b_2)\n b = np.zeros(4)\n b[argmax] = np.sqrt(b_2[argmax])\n\n # There is probably a cleaner way to do thes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store data to config file.
def save(self): try: with open(self._filename, 'w') as conf_file: conf_file.write(json.dumps(self._data)) except OSError: _LOGGER.exception("Can't store config in %s", self._filename)
[ "def save_config(self):\n with open(self.path, 'w', encoding=ENCODING) as f:\n self.data.write(f)", "def write_config(self, data):\n debug('Writing FAUCET config')\n # Write configuration file\n with open(self.path, 'w') as config:\n config.write(data)\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return config path extern for docker.
def path_config_docker(self): return HOMEASSISTANT_CONFIG.format(HASSIO_SHARE_EXT)
[ "def mitogen_docker_path(self):", "def _config_path(self) -> str:\n return self._config_path_for(dir_path=self._dir_path)", "def get_config_file_location():\n\n return './' + CONFIG_FILE_NAME", "def get_config_path(config):\n section = config.sections()[0]\n return Path(config.get(section, \"p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return SSL path extern for docker.
def path_ssl_docker(self): return HOMEASSISTANT_SSL.format(HASSIO_SHARE_EXT)
[ "def path_ssl(self) -> Path:\n return self.path_supervisor / HASSIO_SSL", "def cert_path(self):\n return self._server._cert_path", "def _get_path(client):\n if client is None:\n client = docker.from_env()\n\n info = client.info()\n return os.path.join(info['DockerRootDir'], _CREDEN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Signup user with missing fields
def signup_user_with_missing_fields(self): response = self.client.post( self.signup_url, self.invalid_user_with_missing_fields, format='json') return response
[ "def signup_user_with_empty_fields(self):\n response = self.client.post(\n self.signup_url, self.invalid_user_with_empty_fields, format='json')\n\n return response", "def test_process_signup_no_password(self):\n\n return self.client.post('/sign_up', \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Signup user with empty fields
def signup_user_with_empty_fields(self): response = self.client.post( self.signup_url, self.invalid_user_with_empty_fields, format='json') return response
[ "def signup_user_with_missing_fields(self):\n response = self.client.post(\n self.signup_url, self.invalid_user_with_missing_fields, format='json')\n\n return response", "def test_process_signup_no_password(self):\n\n return self.client.post('/sign_up', \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send sampled subgraph (Nodeflow) to remote trainer.
def _send_subgraph(sender, nodeflow): graph_handle = nodeflow._graph._handle node_mapping = nodeflow._node_mapping.todgltensor() edge_mapping = nodeflow._edge_mapping.todgltensor() # Can we convert NDArray to tensor directly, instead of using toindex()? layers_offsets = utils.toindex(nodeflow._layer...
[ "def send(self, nodeflow):\n _send_subgraph(self._sender, nodeflow)", "def subsample_graph(graph, max_degree,\n rng):\n edges = sampler.get_adjacency_lists(graph)\n edges = sampler.sample_adjacency_lists(edges, graph.train_nodes, max_degree,\n rn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receive sampled subgraph (NodeFlow) from remote sampler.
def _recv_subgraph(receiver, graph): # hdl is a list of ptr hdl = unwrap_to_ptr_list(_CAPI_ReceiverRecvSubgraph(receiver)) return NodeFlow(graph, hdl[0])
[ "def subsample_graph(graph, max_degree,\n rng):\n edges = sampler.get_adjacency_lists(graph)\n edges = sampler.sample_adjacency_lists(edges, graph.train_nodes, max_degree,\n rng)\n senders = []\n receivers = []\n for u in edges:\n for v in edges[u]:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If `tree` is the common ancestor, `_CommonAncestorFound(tree)` is raised. If `node1`/`node2` is in this subtree, return True, otherwise return False.
def recursive(tree): if tree == None: return False if tree == node1 or tree == node2: # Only need to find another node in the left or right subtree. if recursive(tree.left_child) or recursive(tree.right_child): raise _CommonAncestorFound(tree) ...
[ "def isancestor(s2,tree):\n if tree is s2: return True\n if tree is None: return False\n else:\n return isancestor(s2, tree.left) or isancestor(s2, tree.right)", "def contains_tree(t1, t2):\n # Empty tree is always a subtree\n if t2 is None:\n return True\n return sub_tree(t1, t2)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
increases house size by 1 multiplies money value by 2 maximum limit size 3
def upgrade(self): if self._size == 3: return self._size += 1 self._money *= 2
[ "def share_price(hotel):\n tier = dict(zip(hotel_names, [0, 0, 1, 1, 1, 2, 2]))[hotel['name']]\n size = len(hotel['tiles'])\n if size < 2:\n return 0\n elif size < 6:\n return (size + tier) * 100\n elif size < 11:\n return (6 + tier) * 100\n elif size < 21:\n return (7 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is this term describing a power of ten?
def power_of_ten(term): if term is None: return True _, factor = term return round_to_ten(factor) == factor
[ "def is_power(n, k):\n r = iroot(n, k)\n if r is None: return None\n return (r if r**k == n else None)", "def power(num, exponent):\n return num ** exponent", "def power(base, exponent):\n return base ** exponent", "def power(num, exponent):\n power = num ** exponent\n return power", "def is_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method creates storage if it exists
def prepare_storage(self): self.logger.info("Preparing storage for your data...") try: self.dir.mkdir(exist_ok=True) self.full_path_to_file.touch(exist_ok=True) except PermissionError: logging.error( "Conversion cannot be performed. Permission ...
[ "def _init_storage(self):\n if not exists(self.storage_dir):\n os.mkdir(self.storage_dir)\n elif not isdir(self.storage_dir):\n raise IOError(\n \"Storage path '%s' is not a directory.\" % self.storage_dir)", "def storage_create(context, values):\n if not valu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method converts news in HTML format and save file to directory
def convert_to_html(self, news_list): self.logger.info("Converting news to HTML...") self.prepare_storage() self.process_news_list_with_images(news_list) content = self.generate_html_template(news_list) self.write_to_file(content.encode("UTF-8"))
[ "def save_news_in_html_file(news, path_to_html, logger):\n check_path_to_directory(path_to_html, logger)\n html_file = tags.html(title='RSS news')\n html_file.add(tags.head(tags.meta(charset='utf-8')))\n\n logger.info('Converting news to html format...')\n for article in news:\n html_factory(a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method converts news in PDF format and save it to directory
def convert_to_pdf(self, news_list): self.logger.info("Converting news to PDF...") self.prepare_storage() self.process_news_list_with_images(news_list) content = self.generate_html_template(news_list) pdf = io.BytesIO() pisa.pisaDocument(content, pdf) self.write_t...
[ "def save_text_to_file(self, pdf):\r\n Path(f'{self.text_folder}/{self.pdf_category}').mkdir(parents=True,\r\n exist_ok=True)\r\n with open(self.destination, 'w') as f:\r\n f.write(pdf)", "def to_pdf(items, path_to_save_pdf):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method write news to file
def write_to_file(self, content): try: with open(self.full_path_to_file, "wb") as fp: fp.write(content) except PermissionError: logging.error( "Conversion cannot be performed. Permission denied for this directory" ) sys.exit...
[ "def _write_file(self) -> None:\n with open(self.name, 'w') as file:\n file.write(self.body)", "def write(self, content):\n ...", "def save_news_in_html_file(news, path_to_html, logger):\n check_path_to_directory(path_to_html, logger)\n html_file = tags.html(title='RSS news')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method process list of news, replacing image links by local paths to images if they exist in local storage
def process_news_list_with_images(self, news_list): for item in news_list: try: filename = hashlib.md5(item.get("Image").encode()).hexdigest() except AttributeError: continue for existing_img in os.listdir(self.img_storage): if ...
[ "def _process_urls(self):\n if self._urls is None:\n return\n try:\n for url in self._urls:\n # a \"URL\" is either a URL and filename or just a URL.\n try:\n filename, real_url = url\n article = Article(real_url...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the USB children instance ID from the plug and play ID.
def get_children_instance_id(pnpid: str) -> Optional[str]: # Although the registry should not be accessed directly # (See https://docs.microsoft.com/en-us/windows-hardware/drivers/install/hklm-system-currentcontrolset-enum-registry-tree), # noqa E501 # and SetupDi functions/APIs should be used instead in a ...
[ "def getChildPIDs(self):\n\t\treturn self.pids", "def get_child_pids(pid):\n\n wmi = win32com.client.GetObject('winmgmts:')\n # noinspection SqlNoDataSourceInspection,SqlDialectInspection\n children = wmi.ExecQuery('SELECT * FROM Win32_Process WHERE ParentProcessID = %s' % pid)\n return [child.Propert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solve the domain with a new or loaded solver and return it autocast to the level of the domain. By default, Solver.check_domain() provides some boilerplate code and internally calls Solver._check_domain_additional() (which returns True by default but can be overridden to define specific checks in addition to the "domai...
def solve_with(cls, solver: Solver, domain_factory: Optional[Callable[[], Domain]] = None, load_path: Optional[str] = None) -> Solver: if domain_factory is None: domain_factory = cls if load_path is not None: # TODO: avoid repeating this code somehow (id...
[ "def solve(self, solver):\n solver.solve()", "def solve(self):\n self.arcConsistencyHelper()\n if self.isSolved():\n for coordinate in self.board.getCoordinates():\n coordinate.setValue(coordinate.getDomain()[0])\n return True\n elif self.isDeadEnd(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creation du fichier xml source model pour des Lois de puissances avec coupure exponentielle et lois de puissances
def XML_EC_PL(Name, InputsFile, OutputFile, emin,emax): #On commence par afficher ce qu'on fait print " Build xml file " print InputsFile #ouverture du fichier dans lequel on place le source model try: fresult = open(OutputFile, 'w') except: print "Coucou" #ecriture des premieres lignes invariantes ...
[ "def generateXMLmodel(quickLogger,\n base,\n galactic_file=\"gal_2yearp7v6_v0.fits\",\n isotropic_file=\"iso_p7v6source.txt\",\n catalog_file=\"gll_psc_v07.fit\"):\n\n\n try:\n checkForFiles(quickLogger,[base+\"_model.xml\"])\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a boto3 cloud formation client in specified region
def _get_cfn_client(region: str, profile: str = None) -> boto3.client: logger.debug(f"Creating Cloudformation client in region {region}") if profile: session = boto3.Session(profile_name=profile) else: session = boto3.Session() try: cfn_client: client = session.client("cloudforma...
[ "def get_cfn_client(region=\"us-east-1\"):\n return boto3.client(\"cloudformation\", region)", "def _client(region: str = \"\") -> Any:\n region_name = region or os.environ.get(\"AWS_DEFAULT_REGION\", AWS_DEFAULT_REGION)\n return boto3.client(\"sqs\", region_name=region_name)", "def __get_client(servic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the status of a stack. None if not deployed
def _get_stack_status(stack_name: str, region: str, profile: str = None) -> Optional[str]: logger.debug(f"Getting stack status for {stack_name} in {region}") cfn_client = _get_cfn_client(region=region, profile=profile) try: result = cfn_client.describe_stacks(StackName=stack_name) except ClientE...
[ "def get_stack_status(self, stack):\n stack_description = self.cfn.describe_stacks(StackName=stack)\n return stack_description['Stacks'][0]['StackStatus']", "def get_stack_status(heat_cli, stack_id):\n return heat_cli.stacks.get(stack_id).stack_status", "def get_stack_status(stack_name, session=Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if stack is in completed state, else returns false
def _stack_is_complete(stack_name: str, region: str, profile: str = None) -> bool: logger.debug(f"Checking if stack {stack_name} in region {region} is in completed state") stack_status = _get_stack_status(stack_name, region=region, profile=profile) if not stack_status: logger.debug(f"STACK: {stack_n...
[ "def has_finished(self) -> bool:\n return not any(self.__sequencing_stacks.values())", "def is_complete(self):\n return self.status == \"DONE\"", "def done(self, state):\n return self.gamestate.is_done(state)", "def is_complete(self):\n return self.status == \"DONE\"", "def IsComplet...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list stack resources
def _get_stack_resources(stack_name: str, region: str, profile: str = None) -> list: logger.debug(f"Getting stack {stack_name} resources in region {region}") cfn_client = _get_cfn_client(region=region, profile=profile) try: result = cfn_client.describe_stack_resources(StackName=stack_name) excep...
[ "def load_cfn_resources(region: str) -> list:\n cloudformation_client = boto3.client(\n service_name='cloudformation', region_name=region, config=cfn_config)\n stacks_in_account = []\n stack_paginator = cloudformation_client.get_paginator('list_stacks')\n\n stack_page_iterator = stack_paginator.p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates whether template body is valid
def _template_isvalid(template_body: str, region: str, profile: str = None) -> bool: logger.debug(f"checking if template is valid in region {region}") cfn_client = _get_cfn_client(region=region, profile=profile) try: cfn_client.validate_template(TemplateBody=template_body) except Exception as e:...
[ "def validate_template(self, contents):\n try:\n self.conn.validate_template(template_body=contents)\n return True\n except BotoServerError as e:\n print contents\n print e.message\n raise", "def _validate_template(self, template):\r\n in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of stack events that have status that includes FAILED
def _get_failed_stack_events(stack_name: str, region: str, profile: str = None) -> list: logger.debug(f"getting stack {stack_name} failure events in region {region}") cfn_client = _get_cfn_client(region=region, profile=profile) try: events = cfn_client.describe_stack_events(StackName=stack_name) ...
[ "def failures(self):\n return [builder for builder in self.status.keys()\n if builder.tracker.failed]", "def determine_stack_failure_event(stack_name, session=None):\n err_msg = None\n cfn_failure_list = [\n 'CREATE_FAILED',\n 'ROLLBACK_COMPLETE',\n 'ROLLBACK_FAILE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import a troppsphere module
def _import_tropo_module(stack_name: str, module_name: str = None) -> Union[object, TropoformStackBase]: if module_name: logger.debug(f"importing troposphere module: {module_name}") sys.path.append(os.path.dirname(module_name)) module_name = os.path.basename(module_name).replace(".py", "") ...
[ "def import_core(self):\n global pet_mod\n global runoff_mod\n global routing_mod\n\n # import desired module for PET\n if self.s.pet_module == 'hargreaves':\n import xanthos.pet.hargreaves as pet_mod\n\n elif self.s.pet_module == 'hs':\n import xantho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets a string of template body from either template_file or module_name or stack_name
def _load_template(template_file: str = None, module_name: str = None, stack_name: str = None) -> str: if template_file: # read the template file with open(template_file, 'r') as fh: template_body = fh.read() else: # Import the troposphere module stack = _import_tropo...
[ "def template_body(self) -> str:\n return pulumi.get(self, \"template_body\")", "def read_template(file_name):\n infile = open(file_name, 'r')\n return infile.read()", "def get_template_str(template, kwargs):\n from templateflow.api import get as get_template\n\n return str(get_template(templ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a Change Plan for a cloud formation stack and logs the results
def plan(stack_name: str, region: str, module_name: str = None, template_file: str = None, parameter_files: str = None, capabilities: str = default_capabilities, output_type: str = 'text', delete_change_set: bool = True, profile: str = None, **kwargs ) -> bool: logger.debug(f"planning sta...
[ "def main():\n args = get_arguments()\n client = boto3.client('cloudformation')\n if stack_exists(client, args.stack_name):\n stack_operations(\n client, \n args.stack_name, \n args.template, \n args.try_timeout, \n operation=\"update\")\n el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the IAQ algorithm
def iaq_init(self) -> List[int]: # name, command, signals, delay self._run_profile(("iaq_init", [0x20, 0x03], 0, 0.01))
[ "def initialize_ai(self):\n\n self.gid, self.genome = constants.genomes_to_run[self.identifier]\n self.genome.fitness = -1\n self.net = neat.nn.FeedForwardNetwork.create(self.genome, constants.conf)\n # self.net = neat.nn.RecurrentNetwork\n # .create(self.genome, constants.conf)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retreive the IAQ algorithm baseline for eCO2 and TVOC
def get_iaq_baseline(self) -> List[int]: # name, command, signals, delay return self._run_profile(("iaq_get_baseline", [0x20, 0x15], 2, 0.01))
[ "def get_next_baseline(self):\r\n\r\n # Optimal path of baselines to be implemented over the finite horizon\r\n optimal_baseline_path = self.get_optimal_baseline_path()\r\n\r\n # Next 'optimal' emissions intensity baseline to implemented for the coming interval\r\n next_baseline = float(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the previously recorded IAQ algorithm baseline for eCO2 and TVOC
def set_iaq_baseline( # pylint: disable=invalid-name self, eCO2: int, TVOC: int ) -> None: if eCO2 == 0 and TVOC == 0: raise RuntimeError("Invalid baseline") buffer = [] for value in [TVOC, eCO2]: arr = [value >> 8, value & 0xFF] arr.append(self._...
[ "def setBaseline(self, baseline):\n self.baseline = AmpObject(baseline, 'limb')", "def load_baseline(self, baseline):\n self.baseline = es.make_baseline(baseline, spacy_model = self.spacy_model, language = self.language)", "def set_baseline(self, baseline):\n assert isinstance(baseline, (tu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the name of the current carrier (or None) for the request lifecycle.
def get_carrier(): return getattr(_local, 'carrier', None)
[ "def carrier_name(self) -> str:\n return pulumi.get(self, \"carrier_name\")", "def get_carrier(self):\n\n return self.carrier", "def get_created_carrier_name(self):\n return self.carrier_page.get_created_carrier_name()", "def carrier(self):\n return self._carrier", "def carrier_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the carrier ID for the request lifecycle.
def get_carrier_id(): carrier = get_carrier() if carrier is None: return carrier for carr in CARRIERS: if carr.slug == carrier: return carr.id return mkt.constants.carriers.UNKNOWN_CARRIER.id
[ "def carrier_name(self) -> str:\n return pulumi.get(self, \"carrier_name\")", "def carrier(self):\n return self._carrier", "def carrier_voyage_number(self) -> Object:\n return self._carrier_voyage_number", "def get_carrier(self):\n\n return self.carrier", "def get_created_carrier...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the name of the carrier for the current request lifecycle.
def set_carrier(name): _local.carrier = name
[ "def carrier_name(self, carrier_name):\n\n self._carrier_name = carrier_name", "def carrier_name(self) -> str:\n return pulumi.get(self, \"carrier_name\")", "def carrier(self, carrier):\n self._carrier = carrier", "def carrier_class(self, carrier_class):\n self._carrier_class = car...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function looks for overlap between two sets of ranges, usually times, formatted in seconds. It will output a boolean array equal in length to table1.
def overlap(table1, table2): out = np.zeros(np.size(table1, axis=0), dtype='bool') for i in range(np.size(table1, axis=0)): s1_s2 = table1[i, 0] < table2[:, 0] s1_e2 = table1[i, 0] <= table2[:, 1] e1_s2 = table1[i, 1] < table2[:, 0] e1_e2 = table1[i, 1] < table2[:, 1] # ...
[ "def time_overlap(d1, d2):\n gt1, gt2, vt1, vt2 = parse_date(d1[\"t1\"]), parse_date(d1[\"t2\"]), parse_date(d2[\"t1\"]), parse_date(d2[\"t2\"])\n return (gt1 != vt2) and (vt1 != gt2) and (gt1 <= vt2) and (vt1 <= gt2)", "def overlapping(time_1, time_2):\n\n if (time_1[0] <= time_2[0] <= time_1[1]) or...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will take a table of time ranges formatted as strings (compatible with bad_times) and convert it to an nx2 array in DateTime seconds
def str_to_secs(table): out = np.zeros([len(table), 2]) for i in range(len(table)): t1, t2 = table[i].split() out[i, 0] = Time.DateTime(t1).secs out[i, 1] = Time.DateTime(t2).secs return out
[ "def __process_times(raw_array: list, num_row: int):\n\n # format strings used in datetime.time().strftime()\n full_time_format = '%H:%M:%S'\n hours_time_format = '%H:00:00'\n minutes_time_format = '00:%M:00'\n seconds_time_format = '00:00:%S'\n\n # booleans for telling what the integers in the se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function reads a commadelimited text file of 31x136 solar torque values and outputs the values as an array
def read_torque_table(table): f = open(table) lines = f.readlines() f.close() out = np.zeros((61, 136)) line_num = 0 for line in lines: fields = line.split() out[line_num, :] = [float(field) for field in fields] line_num = line_num + 1 return out
[ "def read_forces(filename):\n f=open(filename,\"r\")\n castep_forces = f.readlines()\n f.close() \n nruter = []\n for index, line in enumerate(castep_forces):\n if 'Total number of ions in cell' in line:\n n_atoms = int(line.split()[7])\n if 'Cartesian components (eV/A)'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns an array of length a with the indices of array b that are closest to the values of array a.
def find_closest(a, b): a = np.atleast_1d(np.array(a)) b = np.atleast_1d(np.array(b)) out = [np.argmin(abs(b - a1)) for a1 in a] return out
[ "def closest_vals(arr1, arr2):\n arr1 = np.array(arr1).T\n arr1 = arr1[:, np.newaxis]\n arr2 = np.array(arr2).T\n\n return np.argmin(abs(arr2 - arr1), axis=1)", "def closest_argmin(A, B):\n L = B.size\n sidx_B = B.argsort()\n sorted_B = B[sidx_B]\n sorted_idx = np.searchsorted(sorted_B, A)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an error metric using the groundtruth and returned patterns Error = gt_patterns missed / total gt_patterns
def get_gt_patterns_found(groundtruth, patterns): hits = [0 for g in groundtruth] # 1 if hit, 0 if miss (on gt) # For each ground_truth pattern, check if we found it with our algorithm for i, gt in enumerate(groundtruth): c1 = gt.vs["label"] c1_edge = gt.es["label"] for p in patte...
[ "def get_patterns_also_in_gt(groundtruth, patterns):\n hits = [0 for p in patterns] # 1 if hit, 0 if miss\n\n # For each ground_truth pattern, check if we found it with our algorithm\n for i, p in enumerate(patterns):\n if len(p.es) == 0:\n continue\n c1 = p.vs[\"label\"]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an error metric using the groundtruth and returned patterns Error = patterns not in gt / total patterns
def get_patterns_also_in_gt(groundtruth, patterns): hits = [0 for p in patterns] # 1 if hit, 0 if miss # For each ground_truth pattern, check if we found it with our algorithm for i, p in enumerate(patterns): if len(p.es) == 0: continue c1 = p.vs["label"] c1_edge = p.es...
[ "def get_gt_patterns_found(groundtruth, patterns):\n hits = [0 for g in groundtruth] # 1 if hit, 0 if miss (on gt)\n\n # For each ground_truth pattern, check if we found it with our algorithm\n for i, gt in enumerate(groundtruth):\n c1 = gt.vs[\"label\"]\n c1_edge = gt.es[\"label\"]\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print (repr) the iGraph representation and count of the topN patterns
def print_top_n_graphs(C, n): ps = sorted(C.P, key=itemgetter(2), reverse=True) for i in range(n): if i >= len(ps): break p, c, s = ps[i] print(p) print("Appeared %d times" % c)
[ "def output(self):\n\t\t# Sort graph nodes by id\n\t\tnodes = list(self.nodes.values())\n\t\tnodes.sort(key=lambda n:n.id)\n\n\t\tfor n in nodes:\n\t\t\t# Get all edges\n\t\t\tedges = []\n\t\t\tfor edge in n.neighbours:\n\t\t\t\tfor neighbour in n.get_neighbours(edge):\n\t\t\t\t\tedges.append((neighbour.id, edge))\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run compress on the Subgen file, then checks against GT
def _test_graphzip_subgen(self, fin_graphzip, fin_insts, n=None): print('Running compression on %s...' % fin_graphzip) start = time.perf_counter() # run compression to get pattern dictionary self.c.compress_file(fin_graphzip) elapsed = time.perf_counter()-start print('Com...
[ "def clean_gzip():\n this_dir = os.getcwd()\n os.chdir(\"/data/COHERENT2/data/CrystalChar/raw\")\n all_files = glob.glob(\"./**\", recursive=True)\n for f in all_files:\n if \".gz\" in f and \"tar\" not in f:\n print(f)\n sh(\"gunzip \" + f)\n os.chdir(this_dir)", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Bundler component. config A dictionary of required configuration values. logger The object the bundler should use for logging.
def __init__(self, config: Dict[str, str], logger: Logger) -> None: super(Bundler, self).__init__("bundler", config, logger) self.file_catalog_client_id = config["FILE_CATALOG_CLIENT_ID"] self.file_catalog_client_secret = config["FILE_CATALOG_CLIENT_SECRET"] self.file_catalog_rest_url = ...
[ "def build_component(self, config_dict):\n pass", "def from_config(cls, config: Dict):\n # start with artifact store\n artifact_store = ArtifactStore(config[keys.GlobalKeys.ARTIFACT_STORE])\n\n # metadata store\n metadata_store = ZenMLMetadataStore.from_config(\n conf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Quarantine the supplied bundle using the supplied reason.
async def _quarantine_bundle(self, lta_rc: RestClient, bundle: BundleType, reason: str) -> None: self.logger.error(f'Sending Bundle {bundle["uuid"]} to quarantine: {reason}.') right_now = now() pat...
[ "def test_403_on_bundle_application(self):\n EditorCraftRoom(self, Terms=True, Coordinator=False)\n partner = PartnerFactory(authorization_method=Partner.BUNDLE)\n url = reverse(\"applications:apply_single\", kwargs={\"pk\": partner.id})\n response = self.client.get(url, follow=True)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes txt and returns a sanitized utf8 string.
def clean_txt(txt): r = txt.encode("utf-8", errors="backslashreplace").decode('utf-8').replace("\\u0144", "") return r
[ "def clean_unicode(str_text_raw):\n str_text = re.sub(\"&amp;\", \"\", str_text_raw)\n return(re.sub(r\"[^\\x00-\\x7F]+\",\" \", str_text))", "def remove_non_ascii(text):\n return re.sub(r'[^\\x00-\\x7F]', ' ', text)", "def remove_special_characters(self, txt: str) -> str:", "def removeUnicode(text):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a DOI string and returns a JSON string of metadata.
def doi2json(doi): if "arxiv" in doi: print("This script does not yet support arXiv.") sys.exit(2) else: url = "https://dx.doi.org/" + doi headers = {"accept": "application/json"} r = requests.get(url, headers = headers) if repr(r)=="<Response [200]>": #success! #handle potential enc...
[ "def get_metadata_from_pubmed(doi_string):\n doi = get_normalised_DOI(doi_string)\n if doi is None:\n return {\"success\": False,\n \"error_msg\": \"Parse Error: '{}' is no valid DOI\".format(doi_string)\n }\n url = \"https://www.ebi.ac.uk/europepmc/webservices/rest/sear...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes the DOI result and returns a string of the year.
def make_year(res): return str(res['issued']['date-parts'][0][0])
[ "def get_year(data):", "def get_year():\n\treturn dsslib.SolutionI(ctypes.c_int32(5), ctypes.c_int32(0))", "def year():\n return datetime.date.today().strftime('%Y')", "def year(self, pid):\n return parse_id(pid, self.config.namespace).year", "def get_year(book):\n return int(book[\"date\"].spl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a markdown citation from metadata.
def make_citation(meta): pass
[ "def generate_readme_url(self, dn):\n\n df_curation = dn.curation_dict\n\n # Preferred citation\n single_str_citation = df_curation['item']['citation']\n\n # handle period in author list. Assume no period in dataset title\n str_list = list([single_str_citation.split('):')[0] + ')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }