query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Advice Create Advice lines in Payment Advice and compute Advice lines.
def compute_advice(self): for advice in self: old_lines = self.env['hr.payroll.advice.line'].search([('advice_id', '=', advice.id)]) if old_lines: old_lines.unlink() payslips = self.env['hr.payslip'].search([('date_from', '<=', advice.date), ('date_to', '>=', ...
[ "def compute_advice(self):\n payslip_pool = self.env['hr.payslip']\n advice_line_pool = self.env['hr.payroll.advice.line']\n payslip_line_pool = self.env['hr.payslip.line']\n\n for advice in self:\n old_line_ids = advice_line_pool.search([('advice_id', '=', advice.id)])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`check_for_fit` wraps a method that validates if `self._is_fitted` is `True`.
def check_for_fit(cls, method): @wraps(method) def _check_for_fit(self, *args, **kwargs): klass = type(self).__name__ if not self._is_fitted: raise PipelineNotYetFittedError( f"This {klass} is not fitted yet. You must fit {klass} before callin...
[ "def check_for_fit(cls, method):\n\n @wraps(method)\n def _check_for_fit(self, X=None, y=None):\n klass = type(self).__name__\n if not self._is_fitted and self.needs_fitting:\n raise ComponentNotYetFittedError(\n f\"This {klass} is not fitted yet...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the title and title size of the figure.
def set_title(self): plt.title(label=self.title, fontsize=self.titlesize)
[ "def set_figure_title(self):\n\n if self.title.on:\n title = self.axes.obj[0,0].title\n title.text = self.title.text\n title.align = self.title.align\n title.text_color = self.title.font_color\n title.text_font_size = '%spt' % self.title.font_size\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output the figure, either as an image on the screen or to the harddisk as a .png or .fits file.
def to_figure(self, structure): if not self.bypass: if self.format is "show": plt.show() elif self.format is "png": plt.savefig(self.path + self.filename + ".png", bbox_inches="tight") elif self.format is "fits": if structure is...
[ "def show_plot(savefig=False, title='Title'):\n if savefig:\n # create dir if it doesn't exist\n if not os.path.isdir(output_path):\n os.makedirs(output_path)\n plt.savefig(output_path + '/' + title + '.png')\n logging.info('Image saved in SourceClassifier/output.')\n else:\n plt.show()", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that all test data can be converted back to a FITS header.
def test_fitsheader(): extensions = ('fts', 'fits') for ext in extensions: for ffile in Path(testpath).glob(f"*.{ext}*"): fits_file = fits.open(ffile) fits_file.verify("fix") data, header = fits_file[0].data, fits_file[0].header meta_header = MetaDict(Orde...
[ "def verify_header (filename, htypes=None):\n\n # dictionary\n dict_head = {\n # raw header\n # commenting out SIMPLE, BSCALE and BZERO - basic keywords\n # that will be present in images but not in binary fits tables\n #'SIMPLE': {'htype':'raw', 'dtype':bool, 'DB':False, 'None_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the distance between two points A and B on a sphere of radius R.
def spherical_dist_AB_latlon(latA, lonA, latB, lonB, R): deg2rad = np.pi / 180 θA, φA = (90 - latA) * deg2rad, lonA * deg2rad θB, φB = (90 - latB) * deg2rad, lonB * deg2rad dAB = R * np.arccos( np.cos(θA)*np.cos(θB) + np.sin(θA)*np.sin(θB)*np.cos(φB - φA) ) return dAB
[ "def distance(a: Point, b: Point) -> float:\n return math.sqrt(math.pow(b.x - a.x, 2) + math.pow(b.y - a.y, 2))", "def distance_from_sphere(self, points, params, sqrt=False):\n center, radius = params\n center = center.reshape((1, 3))\n distance = (torch.norm(points - center, p=2, dim=1) -...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the parameters of the projected ellipse of a pixel FOV on Mars.
def params_ellipse_fov(lon_px, lat_px, emergence, lon_subsc, lat_subsc, d_Mars_sc, ifov=2.7e-3): # IFOV radius in km r_ifov = d_Mars_sc * np.tan(ifov) # Ellipse axes a = r_ifov / np.cos(emergence * np.pi / 180) b = r_ifov # Ellipse rotation angle #> v10 - Spherical com...
[ "def ellipse(self):\n f = self.img\n x = self.x\n y = self.y\n x2 = self.x2\n y2 = self.y2\n xy = self.xy\n self.a2 = (x2+y2) + sqrt(((x2-y2)/2.)**2 + xy**2)\n self.b2 = (x2+y2) - sqrt(((x2-y2)/2.)**2 + xy**2)\n self.a = sqrt(self.a2)\n self.b = sqrt(self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if a point of coordinates (x, y) is within an ellipse.
def in_ellipse(x, y, a, b, x0=0, y0=0, θ=0): testin = ( ( (x - x0) * np.cos(θ) + (y - y0) * np.sin(θ) )**2 / a**2 + ( (x - x0) * np.sin(θ) - (y - y0) * np.cos(θ) )**2 / b**2 ) return (testin <= 1)
[ "def in_ellipse(x,y,a,b):\n return ellipse(x,y,a,b) <= 1", "def existing_ellipse(ellipse, center_points):\r\n x_new = int(round(ellipse[0][0]))\r\n y_new = int(round(ellipse[0][1]))\r\n\r\n for point in center_points:\r\n\r\n x_existing = point[0]\r\n y_existing = point[1]\r\n x_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if a point of coordinates (lat, lon) on a sphere of radius R is within an ellipse.
def in_ellipse_spherical(lon, lat, R, a, b, lon0=0, lat0=0, θ=0): deg2rad = np.pi / 180 # Compute distances to the center of the ellipse in km Δx = 2 * (R * np.cos(lat*deg2rad)) * np.tan( (lon - lon0)*deg2rad / 2 ) Δy = 2 * R * np.tan( (lat - lat0)*deg2rad / 2 ) # Test if in ellipse testin = ( ...
[ "def is_on_sphere(c, r, p):\n return np.isclose(distance(c, p), r)", "def point_inside_circle(x,y,center_x,center_y,radius):\n return (x-center_x)**2 + (y - center_y)**2 < radius**2", "def is_point_in_circle(r, p):\n return r >= math.hypot(*p)", "def is_point_inside_hypersphere(point: np.array, c: List...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a pandas Series, generate a descriptive visualisation with a boxplot and a histogram with a kde. By default, this function drops `nan` values. If you desire to handle them differently, you should do so beforehand and/or specify dropna=False.
def dist_plot(series: pd.core.series.Series, dropna: bool = True) -> NoReturn: if dropna: series = series.dropna() quarts = scipy.stats.mstats.mquantiles(series, [0.001, 0.25, 0.5, 0.75, 0.975]) f, (ax_box, ax_hist) = plt.subplots( 2, sharex=True, gridspec_kw={"height_ratios": (0.25, 0.75...
[ "def dist_plot(\n series: pd.core.series.Series, dropna: bool = True, sig: Optional[int] = None\n) -> NoReturn:\n\n if dropna:\n series = series.dropna()\n sig = sig or 0\n\n quarts = scipy.stats.mstats.mquantiles(series, [0.001, 0.25, 0.5, 0.75, 0.975])\n\n f, (ax_box, ax_hist) = plt.subplots...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store wavelengths for a spectrum
def storeWavelengths(self, nm): pre = "w,0" d = {"wavelength_nm": list(nm)} self._writeline(pre, str(d))
[ "def designWavelengths(self):\n\n wavelengths = self.value(\"WAVM\", index=1)\n if isinstance(wavelengths, list):\n while float(wavelengths[-1]) == 0.55:\n wavelengths.pop()\n return [ float(x) for x in wavelengths]\n else:\n return [float(wavelen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets up a scan named `fname` with `path` the scan pattern type, `size_xy` the scan dimensions in steps, `step_xy_deg` the step sizes in [°], and `int_s` the integration time in [s]. If `fname` is empty, the output is send to the REPL.
def setupScan(self, fname, size_xy, step_xy_deg, int_s, path=PATH_R_SPIRAL): # Create data structure self.SI = SpectImg(size_xy, step_xy_deg, int_s, self.SP.channels, fname) self.SI.storeWavelengths(self.SP.wavelengths) # Set integration time and move to origin self.SP.setIntegrationTime_s(max(0.00...
[ "def __init__(self, path, template):\n super(GenerateSpectrum, self).__init__(path)\n self._template = template", "def exportPath(viewer, robot, problem, pathId, stepsize, filename):\n length = problem.pathLength(pathId)\n t = 0\n tau = []\n dt = stepsize / length\n while t < length:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pop n oldest experiences from buffer
def _popN(self, n): for _ in range(n): self._buffer.popleft()
[ "def _cull_oldest(self, n=1):\n for msg_id in self.get_history()[:n]:\n self.log.debug(\"Culling record: %r\", msg_id)\n self._culled_ids.add(msg_id)\n self.drop_record(msg_id)", "def remove_old_experience(self):\n while len(self.history) > self.maxSize:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
output_isochrone. Writes isochrone as file. Used to save best fit isochrone.
def output_isochrone(self, file_to_name): N = len(self.color) # length of data points color = self.color abs_mag = self.abs_mag metallicity = self.metallicity best_fit = int(self.best_fit)*np.ones(N) age = self.age*np.ones(N) df_out = pd.DataFrame({'color' : col...
[ "def output_otis_elevation(elevation_file,h,xlim,ylim,constituents):\n fid = open(elevation_file,'wb')\n ny,nx,nc = np.shape(h)\n #-- length of header: allow for 4 character >i c_id strings\n header_length = 4*(7 + nc)\n fid.write(struct.pack('>i',header_length))\n fid.write(struct.pack('>i',nx))\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Usually removing constant columns gives improvement in model's quality.
def drop_const_columns(df, drop_columns=True, print_columns=True): # 1. report SingleValueCols = [] for col in df.columns: unique_count=df[col].nunique() if unique_count < 2: SingleValueCols.append(col) if print_columns: print(col, unique_count) ...
[ "def del_unwanted_cols_fact(data):\r\n # del data['do_plu']\r\n del data['dorder_receiveon']\r\n # del data['dorder_receiveon_time']\r\n return data", "def _remove_redundant_columns(self):\n self.dataframe.drop(['letter', 'sentiment'], axis=1, inplace=True)", "def eliminateRedundantInfo(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
1. Find date columns automatically 2. Convert them to datetime format
def find_date_columns(df): def look_to_date(s): dates = {date: pd.to_datetime(date) for date in s.unique()} return s.apply(lambda v: dates[v]) date_cols = [] for col in df.select_dtypes(include=['object']).columns: try: df[col] = look_to_date(df[col]) print(...
[ "def handle_datetime_types(df):\n for col in df.columns:\n if df[col].dtype == \"object\":\n try:\n df[col] = pd.to_datetime(df[col])\n\n except ValueError:\n pass\n\n return df", "def _infer_datetime_columns(self) -> pd.DataFrame:\n cli = se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays recieved messages. This ensures that recieved messages dont get lost by the time this display takes.
def display_messages(self): while self.joined: if len(self.messages) != 0: for msg in self.messages: #: If the message is empty, ignore it. if msg == "": continue #: If the message is close", then the server has told the client #: to shut down, so it will. This is not an issue, as u...
[ "def show_messages(self):\n for msg in self.messages:\n print msg['text']", "def get_messages( self ):\n message = self.text_sock.recv( 4096 )\n while message:\n print( message.decode(), end='' )\n message = self.text_sock.recv( 4096 )\n self.clean_up()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a list of accessible reciprocal lattice vectors. To be accessible, the magnitude of a rlv's wavevector must be less than twice that of the input radiation's wavenumber.
def find_accessible_rlvs(crystal, wavelength): # The wavenumber of the input wavelength nu = 2*n.pi/wavelength # Now we find the shortest distance to a wall of a # parallelogram "shell" in the reciprocal lattice min_step = min(abs(n.dot( (crystal.rlattice[0]+crystal.rlattice[1] ...
[ "def get_reciprocal_vectors(self):\n return self.recip_lattice_vectors", "def gen_reciprocal_vectors(lattice_vectors):\n reciprocal_vectors = np.zeros((3, 3))\n\n # NOTE: the volume here should have a sign, i.e. DO NOT add any abs()\n # here. Otherwise the results will be wrong when volume < 0.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a powder XRD spectrum for radiation with the given wavelength (in angstroms)
def powder_XRD(crystal,wavelength, get_mults=False): # The wavenumber of the input wavelength nu = 2*n.pi/wavelength # Make a list of the accessible rlvs rlvs = find_accessible_rlvs(crystal,wavelength) # Now we calculate the scattering intensity from each rlv intensities = { t...
[ "def wavelength_model(p, x):\n order = p[4]\n y = p[5]\n (alpha, sinbeta, gamma, delta) = p[0:4]\n sinbeta = np.radians(sinbeta)\n d = 1e3/110.5 # Groove spacing in micron\n pixelsize, focal_length = 18.0, 250e3 # micron\n scale = pixelsize/focal_length\n\n costerm = np.cos(scale * (y-1024))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is just a nice function to turn the raw scattering data into a humanreadable scattering spectrum
def spectrumify(scattering_data, instr_broadening=0.1): graph_angles = n.linspace(0,180,10000) graph_intensities = n.zeros(graph_angles.shape) for angle, intensity in sorted(scattering_data.items()): graph_intensities += intensity * \ n.exp(-(graph_angles - angle)**...
[ "def spectrum_to_xyz(spectrum: Callable) -> ndarray:\n xyz = spectrum(WAVELENGTHS_380_780) @ CIE_XYZ_380_780\n xyz /= sum(xyz)\n return xyz", "def _info_spectral_points(self):\n d = self.data\n ss = \"\\n*** Spectral points ***\\n\\n\"\n ss += \"{:<25s} : {}\\n\".format(\"SED referen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
yield each group of choices with replacement.
def bootstrap(items, choices, repeats): for i in range(repeats): yield sample(items, choices, replace=True)
[ "def permute_choices(l, choose):\n\tindecies = range(0,choose)\n\twhile indecies[0] < len(l) - choose + 1:\n\t\tyield [l[i] for i in indecies]\n\t\tpos = choose - 1\n\t\twhile pos < choose:\n\t\t\tindecies[pos] += 1\n\t\t\t# if indecies[choose - 1] >= len(l)\n\t\t\t# if indecies[choose - 2] >= len(l) - 1\n\t\t\tif ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a matrix of words ~ genera word_prob_provided_genus. use total_seqs as int, genus_seqs as int 1darray.
def _get_word_posteriors(self, seq_counts, genus_seqs, total_seqs): # n(wi) as a col vector word_seqs = c_[seq_counts.sum(1)] # p(wi) as a col vector word_priors = (word_seqs + 0.5) / (total_seqs + 1) # p(wi|G) word_posteriors = (seq_counts + word_priors) / (genus_seqs + ...
[ "def get_matrix_of_vectors(wv_from_bin, required_words=['softball', 'technology','street','project','fellow','maps','view','fuel','summer','clubhouse','ball','steal','soccer','driving','motor','comedy']):\n import random\n words = list(wv_from_bin.vocab.keys())\n print(\"Shuffling words ...\")\n random....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raise a ValidationError if data does not match the author format.
def __call__(self, data): if self.required and len(data) <= 0: raise ValidationError('An author is required') if not isinstance(data, list): # Convert single instance to a list data = [data] AUTHOR_TYPES = {'author', 'photographer', 'illustrator', 'videograp...
[ "def _validate_author_id(cls, item):\n if (\n item.author_id and\n not user_services.is_user_or_pseudonymous_id(item.author_id)\n ):\n cls._add_error(\n 'final %s' % (\n base_model_validators.ERROR_CATEGORY_AUTHOR_CHECK),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a cue ball with a starting velocity of (0,0,0) at the right end of the map
def make_cueball(starting_position = vec(15,0,0), starting_vel = vec(0,0,0)): cueball = sphere(size = 1.0*vec(1,1,1), pos = starting_position) cueball.vel = starting_vel isMoving = False return cueball
[ "def paddle_bounce(self):\n # TODO: Change this so it will rebound the ball back based on\n # when the ball struck the paddle. Above the center returns the\n # ball with a positive y, below the center returns with a -y.\n # P |/ y=+++\n # A |/ y=++\n # D |/ y=+\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a new moving blackHole with a starting position and default velocity with vec(0,0,0)
def make_blackHole(starting_position, starting_vel = vec(0,0,0)): blackHole = helix(size = 1.0*vec(1, 1, 1), pos = starting_position, color = color.black) # ball is an object of class helix blackHole.vel = starting_vel # This is the initial velocity return blackHole
[ "def create_hole(self):\n self.is_active = False\n self.fish = 0", "def createBouncingPixel():\n height = width = 16\n empty = numpy.zeros((height, width), dtype=numpy.int32)\n x = 0\n y = 0\n x_diff = 1\n y_diff = 1\n frames = []\n for i in xrange(61): # Comes back to starting position in 6...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements Python's choice using the random() function.
def choice(L): LEN = len(L) # Get the length randomindex = int(LEN*random()) # Get a random index return L[randomindex] # Return that element
[ "def choice(seq):\r\n i = int(random() * len(seq))\r\n return seq[i]", "def choice(seq):\n return seq[int(random() * len(seq))] # raises IndexError if seq is empty", "def choice(*args, **kwargs):\n return sample_from(lambda _: np.random.choice(*args, **kwargs))", "def random_choice(seq):\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements Python's randint using the random() function. returns an int from low to hi _inclusive_ (so, it's not 100% Pythonic)
def randint(low, hi): if hi < low: low, hi = hi, low # Swap if out of order! LEN = int(hi) - int(low) + 1. # Get the span and add 1 randvalue = LEN*random() + int(low) # Get a random value return int(randvalue) # Return the integer part of it
[ "def _randint(low, high):\n return random(low, high).to(int).value()", "def randint(lower: int, upper: int):\n return Integer(lower, upper).uniform()", "def random_int() -> int:\r\n\r\n return randint(0, 1000)", "def random_integer(min=0, max=sys.maxsize):\n return random.randint(min, max)", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a vec of (r, g, b) random from 0.0 to 1.0.
def randcolor(): r = random(0.0, 1.0) g = random(0.0, 1.0) b = random(0.0, 1.0) return vec(r, g, b) # A color is a three-element vec
[ "def random_color_gen():\n r = randint(0, 255)\n g = randint(0, 255)\n b = randint(0, 255)\n return [r, g, b]", "def random():\n return tuple(int(round(i * 255, 0)) for i in hls_to_rgb(randrange(0, 360) / 360, randrange(50, 90, 1) / 100, randrange(30, 80, 10) / 100))", "def get_random_color():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Corral collisions! Ball must have a .vel field and a .pos field.
def corral_collide(ball): # If the ball hits wallA if ball.pos.z < wallA.pos.z: # Hit -- check for z ball.pos.z = wallA.pos.z # Bring back into bounds ball.vel.z *= -1.0 # Reverse the z velocity # If the ball hits wallB if ball.pos.x < wallB.pos.x: # Hit -- check for...
[ "def detect_collision():\n # with the top and bottom of screen\n if ball.ycor() > GAME_Y_BARRIER or ball.ycor() < -GAME_Y_BARRIER:\n ball.bounce_y()\n # with the paddles\n if ball.distance(paddle_right) < 50 and ball.xcor() > GAME_X_BARRIER \\\n or ball.distance(paddle_left) < 50 and b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Paints a square on the grid at a particular (int, int) position. Color is given as an RGB triple (of floats between 0 and 1); cr is the Cairo context. Used only in the expose methods of Board and NextPieceDisplay
def paint_square(self, pos, color, cr): cr.set_source_rgb(*color) i, j = pos cr.rectangle(i*DOT_SIZE+1, j*DOT_SIZE-1, DOT_SIZE-2, DOT_SIZE-2) cr.fill()
[ "def draw_square(self, x, y, color):\n\n if self.screen:\n pygame.draw.rect(self.screen, color, self.gen_rect(x, y))", "def draw_multicolor_square(t,sz):\r\n for i in [\"red\", \"purple\", \"hotpink\", \"blue\"]:\r\n t.color(i)\r\n t.forward(sz)\r\n t.left(90)", "def si...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Drop (and lock) curr_piece as far as possible, granting points equal to the distance of the drop.
def drop_curr_piece(self): if self.over: return delta = (0, 0) # now make this as big as possible while True: new_delta = tuple_add(delta, (0, 1)) if self.can_move_curr_piece(new_delta): delta = new_delta else: break se...
[ "def _drop_piece(self) -> None:\n try:\n self._game_state.drop_piece(self._current_coordinate[0],\n self._current_coordinate[1])\n self._redraw_canvas()\n \n except othello_module.InvalidMoveError:\n pass", "def drop_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add squares of current piece to the collection of locked squares. Make calls to clear full rows, generate another piece, and check whether the game should end.
def lock_curr_piece(self): for pos in self.curr_piece.occupying(): self.locked_squares[pos] = self.curr_piece.color self.clear_rows() self.curr_piece = self.next_piece_display.get_piece() if any(pos in self.locked_squares for pos in self.curr_piece.occupying...
[ "def add_piece(self, piece: Model):\n new_piece_coordinates = piece.get_block_positions()\n for coordinates in new_piece_coordinates:\n if not self.piece_encompasses_coordinates(coordinates):\n continue\n else:\n print('GAME OVER')\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear any full rows, modifying the variables locked_squares, level, lines, and score as appropriate.
def clear_rows(self): ### Previous version had a bug, in that it assumed the set of ### ### indices of full rows had to be a contiguous sequence! ### full_rows = [j for j in range(ROWS) if all( (i, j) in self.locked_squares for i in range(COLS))] if not full_rows...
[ "def clear(self):\n self._board = [['.' for _ in range(10)] for _ in range(22)]\n self._score = 0\n self._cleared_lines = 0", "def removeFullRows(data):\r\n newBoard = []\r\n # Adds old rows that are not full to new board\r\n for row in range(len(data.board)):\r\n if data.empt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increment lines by d, and change the label.
def increment_lines(self, d): self.lines += d styled_set_label_text(self.lines_display, "Lines: "+str(self.lines))
[ "def line_counter(self, event=None):\n try:\n text_area = self.get_current()\n self.canvas.delete('all')\n i = text_area.index(\"@0,0\")\n while True:\n dline = text_area.dlineinfo(i)\n if dline is None: break\n y = dlin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increment score by x, and change the label.
def increment_score(self, x=1): self.score += x styled_set_label_text(self.score_display, "Score: "+str(self.score))
[ "def increment_score(self):\n self.score += 1", "def increaseScore(self):\n self.score = self.score+1", "def increase_score(self):\n self.score += 10", "def increase_score(self, score):\r\n self.score += score", "def update_score(self):\r\n self.score += 1\r\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increment level by 1, and change the label. Also call make_timer and hook up the resulting function with glib.timeout_add, to be called every 2.0/(level+3) seconds.
def increment_level(self): self.level += 1 styled_set_label_text(self.level_display, "Level: "+str(self.level)) glib.timeout_add(2000//(self.level+3), self.make_timer(self.level))
[ "def handle_level_change(self, event):\n\n self.map_level.set_text('%d' % event.level)", "def refresh_label(self):\n # increment the time\n self.seconds += 1\n # display the new time\n self.label.configure(text=\"%i s\" % self.seconds)\n # request tkinter to call self.ref...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a callback function on_timer, which moves current piece down (without granting a point). If the current level moves beyond lev, then on_timer will stop working, and will need to be replaced.
def make_timer(self, lev): def on_timer(): if (lev == self.level) and not self.over: # finds lev in scope self.move_curr_piece((0, 1)) return True else: return False # kills on_timer return on_timer
[ "def _timer_callback(self, timer, libev_events):\r\n if timer in self._active_timers:\r\n (callback_method,\r\n callback_timeout,\r\n kwargs) = self._active_timers[timer]\r\n\r\n if callback_timeout:\r\n callback_method(timeout=timer, **kwargs)\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a new piece and shows it; returns the old piece. Analogous to next() operation for iterators.
def get_piece(self): old = self.next_piece new = self.create_piece() self.next_piece = new self.queue_draw() return old
[ "def spawn_new_piece(self):\n\n del self.active_piece\n\n new_x = self.WIDTH // 2 - 1\n self.active_piece = Figure(random.choice(PIECE_TYPES), new_x, 0)", "def update_next_piece(self, board):\n # next piece\n if board.next_shape:\n for preview_row_offset in range(4):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the text of a gtk.Label with the preferred markup scheme. (Simple enough not to be worth extending gtk.Label just for this method.)
def styled_set_label_text(label, text): front = "<b><span foreground='#AAAAAA' size='large'>" end = "</span></b>" label.set_markup(front+text+end)
[ "def SetLabelMarkup(*args, **kwargs):\n return _core_.Control_SetLabelMarkup(*args, **kwargs)", "def set_label_one_text(self, text: str):\n self.label_one.setText(text)", "def set_label(self, text):\n self._label = text", "def _style_label(self):\n self._set_option(\"*Label.foregro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the template was rendered
def rendered(template): def was_rendered(client, response, testcase): testcase.assertTemplateUsed(response, template) return was_rendered
[ "async def _validate_template(self, template):\n try:\n templater.Template(template, self.hass).async_render()\n return True\n except Exception as exception: # pylint: disable=broad-except\n _LOGGER.error(exception)\n pass\n return False", "def sho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the email.outbox contains n items
def outbox_len(count): def outbox_len_is(client, response, testcase): testcase.assertEqual( len(mail.outbox), count ) return outbox_len_is
[ "def check_not_empty(self, wait_time):\n for i in range(3):\n self.refresh_emailbox(wait_time)\n if not self._device(resourceId='com.tct.email:id/empty_view').exists:\n self._logger.debug('The box is not empty')\n return True\n self._logger.debug('Th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the pool of servers used by this client.
def set_servers(self, servers): self.servers = [] self.buckets = [] for server_desc in servers: if type(server_desc) == tuple: server_addr, weight = server_desc else: server_addr, weight = server_desc, 1 server = _ServerConnection(server_addr, weight, self._debuglog) self.servers.append(se...
[ "def server_pool(self, server_pool):\n\n self._server_pool = server_pool", "def set_servers(self, servers):\n pass", "def assignServers(self):\n\n # Hand over enabled servers to LVSService\n self.lvsservice.assignServers(\n set([server for server in self.servers.itervalues() i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get statistics from each of the servers.
def get_stats(self): data = [] for server in self.servers: stats = yield server.get_stats() data.append(stats) raise StopIteration(data)
[ "def listServers():\n servers = AdminControl.queryNames( 'type=Perf,*').split(\"\\n\")\n for i in range(0, len(servers)):\n srvName = servers[i].split(\",\")[1].split(\"=\")[1]\n if srvName == \"nodeagent\":\n continue\n print \"Serve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a command to the server to atomically increment the value for ``key`` by ``delta``, or by 1 if ``delta`` is unspecified. Returns None if ``key`` doesn't exist on server, otherwise it returns the new value after incrementing. Note that the value for ``key`` must already exist in the memcache, and it must be the st...
def incr(self, key, delta=1): return self._incrdecr("incr", key, delta)
[ "def incr_version(self, key, delta=1, version=None, client=None):\r\n\r\n if client is None:\r\n client = self.get_client(write=True)\r\n\r\n if version is None:\r\n version = self._backend.version\r\n\r\n old_key = self.make_key(key, version)\r\n value = self.get(o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For each key in data, determine which server that key should be mapped to. Returns a dict. Keys are `_ServerConnection` instances; for each server, the value is a list of (prefixed_key, original_key) tuples for all values which belong on that server.
def _map_keys_to_servers(self, key_iterable, key_prefix): # Only check the prefix once key_extra_len = len(key_prefix) if key_prefix: check_key(key_prefix) # server -> list of (prefixed_key, value) server_keys = {} deprefix = {} # build up a list for each server of all the keys we want. for orig_k...
[ "def _map_and_prefix_keys(self, key_iterable, key_prefix):\r\n # Check it just once ...\r\n key_extra_len=len(key_prefix)\r\n #changed by steve\r\n #if key_prefix:\r\n #self.check_key(key_prefix)\r\n\r\n # server (_Host) -> list of unprefixed server keys in mapping\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform value to a storable representation, returning a tuple of the flags and the new value.
def _value_to_stored(value, min_compress_len): flags = 0 if isinstance(value, str): pass elif isinstance(value, int): flags |= Client._FLAG_INTEGER value = "%d" % value # Don't try to compress it min_compress_len = 0 elif isinstance(value, long): flags |= Client._FLAG_LONG value = "%d" % v...
[ "def _val_to_store_info(self, val, min_compress_len):\r\n flags = 0\r\n if isinstance(val, str):\r\n pass\r\n elif isinstance(val, int):\r\n flags |= Client._FLAG_INTEGER\r\n val = \"%d\" % val\r\n # force no attempt to compress this silly string.\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test incr and decr functions
def test_incrdecr(self): yield self.conn.set("an_integer", 42) self.assertEqual((yield self.conn.incr("an_integer", 1)), 43) self.assertEqual((yield self.conn.decr("an_integer", 1)), 42)
[ "def testIncrementDecrement(self):\n\n memcache.incr('unknown_key')\n assert memcache.get('unknown_key') == None\n memcache.set('counter', 0)\n assert memcache.get('counter') == 0\n memcache.incr('counter')\n assert memcache.get('counter') == 1\n memcache.incr('count...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that invalid keys raise the appropriate exception
def test_invalid_keys(self): try: yield self.conn.set("this has spaces", 1) except ValueError: pass else: self.fail("key with spaces did not raise ValueError") try: yield self.conn.set("\x10control\x02characters\x11", 1) except ValueError: pass else: self.fail("key with control character...
[ "def is_invalid(self, key): # pragma: no cover\n\t\traise NotImplementedError", "def test_raises_keys_not_present(self):\n valid_test_df = pd.DataFrame({'valid_column_name': [0, 1, 2, 3]})\n non_valid_key = ['not_present_in_valid_test_df']\n with pytest.raises(ValueError) as exc_info:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that get_multi works as expected
def test_get_multi(self): yield self.conn.set("an_integer", 42) yield self.conn.set("a_string", "hello") res = yield self.conn.get_multi([ "a_string", "an_integer" ]) self.assertEquals(res, { "a_string": "hello", "an_integer": 42 })
[ "def test_multi(self):\n self.assertEqual(6, foo.multi(2, 3))", "def test_multi(self):\n self.assertEqual(6, multi(2, 3))", "def test_sub_compute_get_get(self):\n pass", "def test_get_canary_result_using_get1(self):\n pass", "def test_get_by_key_multi(self):\n tree = Multi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts the interval into the tree.
def insert(self, interval): if self.root == None: self.root = Node(interval) return self.root (start, end) = interval node = self.root while True: if node.key <= start: path = 'right' else: path = 'left' ...
[ "def insert(self, interval):\n if not isinstance(interval, Interval):\n raise Exception(\"Not an Interval instance: \", interval)\n if interval.xmax>self.xmax+EPSILON or interval.xmin<self.xmin-EPSILON:\n raise Exception(\"Interval\", interval, \"exceeded tier boundary.\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
raises the given exception type in the context of this thread
def raise_exc(self, exctype): _async_raise(self._get_my_tid(), exctype)
[ "def raise_exc(self, exctype):\n\t\tself.async_raise(self.get_my_tid(), exctype)", "def raiseException(self, exceptionType):\n if self.is_alive():\n ## Assuming Python 2.6+, we can remove the need for the _get_my_tid as\n ## specifed in the Stack Overflow answer\n _asyncRaise( self.ident, except...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add VM to db Return True if this is new.
def add_cloudyvent_vm(self, runname, iaasid, nodeid, hostname, service_type, parent, runlogdir, vmlogdir): cyvm = self.get_by_iaasid(iaasid) if not cyvm: cyvm = _CYVM(runname, iaasid, nodeid, hostname, service_type, parent, runlogdir, vmlogdir) self.session.add(cyvm) ...
[ "def add_vm(self, vm, cache=True):\n if not hasattr(vm, 'preferred_ip'):\n vm.preferred_ip = ''\n gc3libs.utils.write_contents(\n os.path.join(self.path, vm.id), vm.preferred_ip)\n self._vm_ids.add(vm.id)\n if cache:\n self._vm_cache[vm.id] = vm\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse ingredients The ingredients come in from the form as normal key value pairs. This needs to be changed so that the ingredients can be stored as the following data structure. [ {
def _parse_ingredients(recipe): ingredients = [] group_counter = 1 counter = 0 filtered_dict = {k: v for k, v in recipe.items() if "ingredient" in k} ingredient = {} for key, value in filtered_dict.items(): if not value: continue elif key == f"ingredient{group_coun...
[ "def recipe_parser(form_data, user):\n\n # The way the ingredients and steps data is structured in the form data is not the\n # structure required for the database so additional processing is required. The\n # `ingredients` and `steps` lists will be created and added to the recipe\n recipe[\"ingredients...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse steps The steps come in from the form as normal key value pairs. This needs to be changed so that the ingredients can be stored as the following data structure. [ "Dice chicken", "Cook chicken until brown" ]
def _parse_steps(recipe): steps = [] filtered_dict = {k: v for k, v in recipe.items() if "step" in k} for key, value in filtered_dict.items(): if value: steps.append(value) return steps
[ "def it_should_parse_the_file_to_create_a_dictionary_of_the_steps():", "def _parse_ingredients(recipe):\n ingredients = []\n group_counter = 1\n counter = 0\n\n filtered_dict = {k: v for k, v in recipe.items() if \"ingredient\" in k}\n ingredient = {}\n\n for key, value in filtered_dict.items():...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Strip excess data Remove any references to the old data structure from the initial form data. This will be old `ingredients` and `steps` keys
def _strip_excess_data(recipe): for key in list(recipe.keys()): if key == "ingredients" or key == "steps": continue elif "ingredient" in key or "step" in key: del recipe[key] return recipe
[ "def clean_ingredients_file(dirty):\n clean_file = 'clean_ingredients.json'\n all_ingredients = []\n with open(dirty) as infile:\n line = infile.readline()\n while line:\n split_line = line.split(',')\n for ing in split_line:\n ing = ing.strip(' \\n.')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recipe parser Bundles up the information retrieved from the request, parses it and strips away the excess information.
def recipe_parser(form_data, user): # The way the ingredients and steps data is structured in the form data is not the # structure required for the database so additional processing is required. The # `ingredients` and `steps` lists will be created and added to the recipe recipe["ingredients"] = _parse...
[ "def parse_request(self, request):\n request.process_inputs()", "def parse_this_url():\n print request.form\n parser = Parser(request.form['recipeUrl'])\n return jsonify({\n 'recipe': parser.fully_parsed(),\n 'steps': parser.steps\n })", "def parseRemainingVariables(json_respons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will return a boolean if a user with specific username exits in the database, it will support later tests of user with assertion Function, will search for a user id that has matching username from the arguments
def userExists(self, username): data = db.session.query(User.id).filter_by(username = username).first() if data is None: return False else: return True
[ "def user_exists(userid):", "def is_user_present(self, username): # WORKS\n done = self.cur.execute(\"SELECT username FROM users WHERE username = \\\"{}\\\"\".format(username))\n if done == 1:\n return True\n else:\n return False", "def test_user_identifier_in_database...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will search the booking of specific user id and car id then tell whether it exists or not
def bookingExists(self, user_id, car_id): data = db.session.query(Booking).filter_by(user_id = user_id, car_id = car_id).first() if data is None: return False else: return True
[ "def validate_bookings(bookingid, username, car_id):\n\n # get booking object for bookingid\n booking = Booking.query.get(bookingid)\n print(\"Booking:::\")\n print(booking)\n\n user = booking.customer\n print(\"User:::\")\n print(user)\n \n print(\"Params:::\"+bookingid+\"--\"+username+\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will search the history of specific user id and car id then tell whether it exists or not
def historyExists(self, user_id, car_id): data = db.session.query(History).filter_by(user_id = user_id, car_id = car_id).first() if data is None: return False else: return True
[ "def has_history(self, user):\n\n header = connect(self.__path)\n curs = header.cursor()\n encrypted_id = md5((str(user.id) + \"typicaluser\").encode()).hexdigest()\n curs.execute(\"SELECT * FROM users WHERE id = (?)\", (encrypted_id,))\n data = curs.fetchall()\n return len...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This test will test the login credentials by query the database to see if that username and password do exist
def test_login(self): username = "user1" password = "pw1" userID = 1 data = db.session.query(User.id).filter_by(username = username, password = password).first() self.assertTrue(data is not None)
[ "def check_db(args):\n # Open connection to the registered users db\n base_path = \"pypackage\"\n users_db = \"openaq_users.db\"\n conn = sqlite3.connect(os.path.join(base_path, users_db))\n cursor = conn.cursor()\n\n # Check for username\n row = cursor.execute(\"SELECT * FROM user_database WHE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will be the getter for dummy user id we created in the test abow
def get_test_id(self): test_username = "testusername" test_user_id = db.session.query(User.id).filter_by(username = test_username).first() print(test_user_id) return test_user_id
[ "def test_user_id_get(self):\n pass", "def test_user_controller_get_id(self):\n pass", "def test_get_user_id(self):\n print('(' + self.test_get_user_id.__name__+')',\n self.test_get_user_id.__doc__)\n # for patient\n self.assertEqual(\n PATIENT_ID, self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This test will user history by query the database to see if any row with matching user id (in this case 12) exists
def test_userHistories(self): user_id = 12 histories = History.query.filter_by(user_id = user_id).all() self.assertTrue((histories is not None))
[ "def has_history(self, user):\n\n header = connect(self.__path)\n curs = header.cursor()\n encrypted_id = md5((str(user.id) + \"typicaluser\").encode()).hexdigest()\n curs.execute(\"SELECT * FROM users WHERE id = (?)\", (encrypted_id,))\n data = curs.fetchall()\n return len...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This test will test the car search by query the database to see if any car with specific make, body type, etc do exist
def test_searchCar(self): make = "Toyota" body_type = "Seden" colour = "Black" seats = "5" cost_per_hour = "10.5" booked = True cars = db.session.query(Car).filter(or_(Car.make == make, ...
[ "def test_create_a_car_make(car_make):\n car_makes = models.CarMake.objects.all()\n\n assert car_make\n assert car_make.name == \"Volkswagen\"\n assert len(car_makes) == 1", "def test_list_cars(self, mock_get_input, mock_db):\n mock_get_input.return_value = \"2013\"\n list_cars_by_year()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This test will create a booking in the database
def test_bookCar(self): user_id = "12" car_id = "6" begin_date = "2020-05-21" begin_time = "12:00:00" return_date = "2020-05-23" return_time = "12:00:00" begin_datetime = "{} {}".format(begin_date, begin_time) return_datetime = "{} {}".forma...
[ "def test_new_booking(self):\n fake_booking = bookings.booking_schema.loads(self.new_booking_json)\n with bookings.app.test_client() as new_booking_route:\n # send data as POST form to endpoint:\n response = new_booking_route.post(self.post_url,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This test will delete a booking in the database
def test_cancelBooking(self): user_id = "12" car_id = "6" begin_date = "2020-05-21" begin_time = "12:00:00" begin_datetime = "{} {}".format(begin_date, begin_time) booking = db.session.query(Booking).filter( Booking.user_id == user_id, ...
[ "def test_meeting_delete(self):\n pass", "def booking_delete(id):\n booking = Booking.query.get(id)\n payment = Payment.query.filter_by(booking_id=id).first()\n if not booking:\n return \"DELETED\"\n db.session.delete(booking)\n db.session.delete(payment)\n db.session.commit()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This test will create a booking in the database, then will run the unlockCar function
def test_unlockCar(self): user_id = "12" car_id = "7" begin_date = "2020-05-21" begin_time = "12:00:00" return_date = "2020-05-23" return_time = "12:00:00" begin_datetime = "{} {}".format(begin_date, begin_time) return_datetime = "{} {}".for...
[ "def test_bookCar(self):\n user_id = \"12\"\n car_id = \"6\"\n begin_date = \"2020-05-21\" \n begin_time = \"12:00:00\"\n return_date = \"2020-05-23\"\n return_time = \"12:00:00\"\n\n begin_datetime = \"{} {}\".format(begin_date, begin_time) \n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test loading a python2generated whoosh index under python3. This test passes only because of the monkeypatching of whoosh.compat.loads with knowhow.util.pickle_loads.
def test_index_load_python2(monkeypatch): expected = { "id": ("02a7cefe1189668fa85b56b52ee1e769" "1ee1821913f2031c8117263c07526468"), "content": "Hello, from Python2", "tag": ["python2"], "updated": datetime.datetime(2017, 9, 15, 14, 58, 12, 441405, tzinfo=UTC), } import know...
[ "def test_read_index_swift(self):\n\n indexfile = tempfile.mktemp()\n self.addCleanup(os.unlink, indexfile)\n\n TroveSwiftIndexBuilder(\"short.dat\", out=indexfile)\n\n index = TroveSwiftIndex()\n index.reload(indexfile)\n\n docs = sorted([doc for doc in index.documents])\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes in array of predicted values and verifies that each prediction has the correct label. If any of the predictions are wrong, the test fails. Returns
def CheckWrong(predicted, correct): for prediction in predicted: if prediction != correct: print("Expected: ", correct," recieved: ", prediction) return False return True
[ "def test_infer_labels(self):\n for _ in range(self.Nreps):\n self._simulate_and_fit()\n\n scores = self.cl.compute_scores(self.R)\n y_inferred = self.cl.infer_labels(self.R)\n \n for i, s in enumerate(scores):\n if s > 0:\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the control environment of the system by verifying the execution of the program executes without exceptions
def testControlEnvironment(video1, video2): try: control.main(video1, video2, Verbose=True, Testing=True) return True except ValueError: return False
[ "def test_run_app(self):\n\n self.run_app()\n self.assertGoodExitCode()", "def test_script_integrity(capsys):\n script = os.path.abspath(\"examples/scikitlearn-iris/main.py\")\n\n return_code = subprocess.call([\"python\", script, \"0.1\"])\n\n assert return_code != 2, \"The example script ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for convertion rainfall depth (in mm) to rainfall intensity (mm/h)
def depth2intensity(depth, interval=300): return depth * 3600 / interval
[ "def mm_to_inches(rainfall_in_mm):\r\n rainfall_in_inches = rainfall_in_mm * 0.0393701\r\n return rainfall_in_inches", "def pixel_to_rainfall(img, a=58.53, b=1.56):\n dBZ = pixel_to_dBZ(img)\n dBR = (dBZ - 10.0 * np.log10(a)) / b\n rainfall_intensity = np.power(10, dBR / 10.0)\n return rainfall_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for convertion rainfall intensity (mm/h) to rainfall depth (in mm)
def intensity2depth(intensity, interval=300): return intensity * interval / 3600
[ "def pixel_to_rainfall(img, a=58.53, b=1.56):\n dBZ = pixel_to_dBZ(img)\n dBR = (dBZ - 10.0 * np.log10(a)) / b\n rainfall_intensity = np.power(10, dBR / 10.0)\n return rainfall_intensity", "def rainfall_to_pixel(rainfall_intensity, a=58.53, b=1.56):\n dBR = np.log10(rainfall_intensity) * 10.0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allow a snapshot, a patch, or a list of patches
def _patches(s): if hasattr(s,'dict'): pp=s.patches elif isinstance(s,dispatch._dispatch._patch): pp=[s] else: pp=s return pp
[ "def validate_patch(patch):\n\n if not isinstance(patch, list):\n patch = [patch]\n\n for p in patch:\n path_pattern = re.compile(\"^/[a-zA-Z0-9-_]+(/[a-zA-Z0-9-_]+)*$\")\n\n if not isinstance(p, dict) or \\\n any(key for key in [\"path\", \"op\"] if key not in p):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests all possible keys and returns keys with highest likelihood of bring the encryption key.
def test_possible_keys(ciphertext): top_keys = [] for num in range(0, 255, 1): decrypted_str = xor_decrypt(ciphertext, num) score = count_score(decrypted_str) if score > 80: top_keys.append(chr(num)) return top_keys
[ "def get_possible_keys(self):", "def get_all_cipher():\n return OpenSSL.cipher_algo.keys()", "def test_key_lengths():\n for n in range(1,15):\n n_substrings = split_substrings(CIPHERTEXT,n)\n index_total = 0\n for sub in n_substrings:\n index_total += index_of_coinciden...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a `query_dict`, will attempt to return a xapian.Query
def parse_query(self, query_dict): if query_dict is None: return xapian.Query('') # Match everything elif query_dict == {}: return xapian.Query() # Match nothing query_tree = self.build_query_tree(query_dict) return query_tree.to_query(self.schema, self.databa...
[ "def _adapt_query(self, translator, query):\n if isinstance(query, dict):\n return self._adapt_dict_query(translator, query)\n else:\n return self._adapt_advancedQuery_query(translator, query)", "def _query(self, query):\n return self.sf.query(query)", "def querydict_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A safer version of Xapian.enquire.get_mset Simply wraps the Xapian version and catches any `Xapian.DatabaseModifiedError`, attempting a `database.reopen` as needed.
def _get_enquire_mset(self, database, enquire, start_offset, max_offset): try: return enquire.get_mset(start_offset, max_offset) except xapian.DatabaseModifiedError: database.reopen() return enquire.get_mset(start_offset, max_offset)
[ "def mset(self, *args):\n if self._cluster:\n return self.execute(u'MSET', *args, shard_key=args[0])\n return self.execute(u'MSET', *args)", "def lset(self, *args):\n if self._cluster:\n return self.execute(u'LSET', *args, shard_key=args[0])\n return self.execute(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A safer version of Xapian.document.get_data Simply wraps the Xapian version and catches any `Xapian.DatabaseModifiedError`, attempting a `database.reopen` as needed.
def _get_document_data(self, database, document): try: return document.get_data() except xapian.DatabaseModifiedError: database.reopen() return document.get_data()
[ "def openDatabase(self, parentPath: unicode, itemName: unicode, version: int, minChangeDataVer: int) -> db.buffers.ManagedBufferFileHandle:\n ...", "def load_from_db(self, for_update=False):\n\twait_on_locks = local.conf.wait_on_locks\n\tif not getattr(self, \"_metaclass\", False) and self.meta.issingle:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private method that returns the column value slot in the database for a given field.
def _value_column(self, field): for field_dict in self.schema['idx_fields']: if field_dict['field_name'] == field: return field_dict['column'] return 0
[ "def column_value(self) -> Any:\n return pulumi.get(self, \"column_value\")", "def _get_column(self, name):\r\n return self.column(name)", "def get_column_value(board, column):\n raise NotImplementedError(\"Not yet implemented\")", "def get_value(self, field):\n field = self.find_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a database and enquire instance, returns the estimated number of matches.
def _get_hit_count(self, database, enquire): return self._get_enquire_mset( database, enquire, 0, database.get_doccount() ).size()
[ "def count_matched(self):\n logger.debug(f'{self.c} Counting matched...')\n if self.control.engine == 'DB':\n table = self.control.result_table\n count = sa.select([sa.func.count()]).select_from(table)\n matched = db.execute(count).scalar()\n logger.debug(f'{sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private utility method that converts Python terms to a string for Xapian terms.
def _marshal_term(term): if isinstance(term, int): term = str(term) return term
[ "def to_unicode(terms):\n unicode_terms = []\n for term in terms:\n if (isinstance(term, str)):\n unicode_terms.append(unicode(term, 'utf-8'))\n else:\n unicode_terms.append(term)\n\n return unicode_terms", "def term_to_tsquery_string(term):\n\n def cleanup(word...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merges query dicts effectively &ing them together.
def _query_conjunction(self, queries): query_ops = set() combined_query = {} for query in queries: ops = set(query.keys()) # Make sure that the same operation isn't applied more than once # to a single field intersection = ops & query_ops ...
[ "def query_add(*query_params):\n d = {}\n for qp in query_params:\n qp = query_unflatten(qp)\n for name, value in qp.items():\n if name in d:\n d[name].extend(value)\n else:\n d[name] = value\n return d", "def merge_result_dictionaries(res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine this node with another node into a QCombination object.
def _combine(self, other, operation): if getattr(other, 'empty'): return self if self.empty: return other return QCombination(operation, [self, other])
[ "def __or__(self, other):\r\n if isinstance(self, Circuit):\r\n if isinstance(other, Circuit):\r\n copy_self = copy(self)\r\n for time_step in other.operations_by_time:\r\n for op in other.operations_by_time[time_step]:\r\n op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
predicts the popularity of a content from a numpy array of its features returns 'popular' string if output is equal to 1 'unpopular' otherwise
def predict(self,X): if (int(self.classifier.predict(self.scaler.transform(X)))==-1): return "popular" else: return "unpopular"
[ "def predict_most_likely(self,sentence):\n best_tag = None\n best_prob = float('-Inf') \n\n predtags=[]\n for token in sentence:\n for tag in self.tags:\n ##### YOUR CODE FROM LAST LECTURE #####\n pass\n\n predtags.append(best_ta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
performs prediction according to self.predict and prints result to standard output
def print_prediction_to_stdout(self,X): sys.stdout.write(self.predict(X)) sys.stdout.flush()
[ "def run_predictions(self):\n print \"Running the Predictions on the test dataset\"\n classifier = Classifier(self.train, self.test, self.targets, self.stratification, self.fts)\n _, y_pred_detail = classifier.classify_predict()\n self.output_file(y_pred_detail)", "def run_prediction(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
performs prediction according to self.predict and prints result to standard output
def print_prediction_to_stdout(self,X): sys.stdout.write(self.predict(X)) sys.stdout.flush()
[ "def run_predictions(self):\n print \"Running the Predictions on the test dataset\"\n classifier = Classifier(self.train, self.test, self.targets, self.stratification, self.fts)\n _, y_pred_detail = classifier.classify_predict()\n self.output_file(y_pred_detail)", "def run_prediction(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preprocess the data further by shuffling inputs and labels randomly
def random_preprocessing(inputs, labels): indices = range(0, labels.shape[0]) shuffled_indices = tf.random.shuffle(indices) inputs = tf.gather(inputs, shuffled_indices) labels = tf.gather(labels, shuffled_indices) return inputs, labels
[ "def apply(self, labeled_data):\n random.shuffle(labeled_data.label)", "def normalize_and_shuffle(data, labels):\n print(\"PRE-PROCESSING DATA...\")\n \n num_samples = data.shape[1]\n \n # Normalize images by mean (contrast)\n image_means = np.mean(data, axis=0)\n norm_data = np.divi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to train the inputted model on the provided training states and actions
def train(model, train_states, train_actions, batch_size): # randomly shuffile input data to increase accuracy shuffled_states, shuffled_actions = random_preprocessing(train_states, train_actions) tl = train_states.shape[0] # training inputs length mod = tl % batch_size # number of batches resul...
[ "def train(self, states, actions, rewards):\r\n self.sess.run(self.train_op, feed_dict={\r\n self.state: states,\r\n self.action: actions,\r\n self.reward: rewards\r\n })", "def train_action(self, state):\n pass", "def action_train_ops(self, sess, state, ru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Using parse_frequency_support, determine the mean primary beam size in each observed band
def approximate_primary_beam_sizes(frequency_support_str, dish_diameter=12 * u.m, first_null=1.220): freq_ranges = parse_frequency_support(frequency_support_str) beam_sizes = [(first_null * fr.mean().to(u.m, u.spectral()) / (dish_diameter)).to(u.arcsec, u.di...
[ "def DSS28_beamwidth(freq):\n return 0.54/freq", "def __call__(self, freq, amp, pdur):\n min_f_size = self.min_rho**2 / self.rho**2\n F_size = self.a5 * amp * self.scale_threshold(pdur) + self.a6\n if self.engine == 'jax':\n return jnp.maximum(F_size, min_f_size)\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a color for a node from the color map
def get_color(node, color_map): if node in color_map: return color_map[node] return "black"
[ "def get_color(self, node: Node) -> str:\n\n idx = hash(node.get_kind_name()) % len(self.colors_)\n return self.colors_[idx]", "def get_color(key):\n if _with_colors:\n return _color_map.get(key, None)\n return None", "def color(node) -> int:\n if node is None:\n return 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obtain a Process Tree representation through GraphViz
def apply(tree, parameters=None): if parameters is None: parameters = {} filename = tempfile.NamedTemporaryFile(suffix='.gv') viz = Digraph("pt", filename=filename.name, engine='dot', graph_attr={'bgcolor': 'transparent'}) image_format = exec_utils.get_param_value(Parameters.FORMAT, param...
[ "def display_process_tree(process_tree: pd.DataFrame):\n build_and_show_process_tree(process_tree)", "def export_graphviz(self):\n terminals = []\n # Assume the geometry is not mirrored at first\n mirror_flag = False\n output = \"\"\"digraph program {\n splines=ortho;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize the wieghts of available sentence Data so that they add upto 1 and can be used for processing further.
def normalize(self): norm_val = self.sum2/self.sum1 self.sum1=0 for sentence in self.data_set: sentence.weight *= norm_val self.sum1 += sentence.weight
[ "def normalize(self):\n for key in self.corpus.keys():\n sum_count = 0\n words = []\n counts = []\n for k, v in self.corpus[key].items():\n sum_count += v\n words.append(k)\n counts.append(v)\n prob = [float(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function is used to get all tags and tags' num from existing ps log
def getTagsNum(self): self.gettags()
[ "def getTags(number=None):", "async def get_tag_stats(db: DB = Depends(get_db), \n logger: Logger = Depends(get_logger)):\n tags = await db.get_all_tags()\n logger.info(\"tags gathered\", extra={\"num_of_tags\": len(tags)})\n\n # format tags to Dict[str, int]\n tags_dict = map(l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute an upper bound on monthlength. Even if we haven't identified all the fields needed for checking leapyears yet, we can still prune if value.d is bigger than the month can ever possibly be.
def valid_day_of_month(value): if value.m == 2: month_length = 29 if value.y is not None: if (value.y % 4) != 0: month_length = 28 elif value.y == 0 and value.C is not None and (value.C % 4) != 0: month_length = 28 else: # Odd-numbe...
[ "def test_month_length():\n assert specs.month_length('January', True) == 31, \"Failed on leap-year Jan\"\n assert specs.month_length('February', True) == 29, \"Failed on leap-year Jan\"\n assert specs.month_length('March', True) == 31, \"Failed on leap-year Jan\"\n assert specs.month_length('April', Tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Are contexts' targets reordered in a consistent way?
def test_context_target_reordering(self): client = IPythonClient() orig_targets = client.ids ctx1 = Context(client, targets=shuffle(orig_targets[:])) ctx2 = Context(client, targets=shuffle(orig_targets[:])) self.assertEqual(ctx1.targets, ctx2.targets) ctx1.close() ...
[ "def exploration_order(targets : [Exp], context : Context, pool : Pool = RUNTIME_POOL):\n\n # current policy (earlier requirements have priority):\n # - visit runtime expressions first\n # - visit low-complexity contexts first\n # - visit small expressions first\n def sort_key(tup):\n e, ct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True, if both words share a synonym set.
def are_words_synonym(self, word1, word2): return self.get_intersection((word1, word2))
[ "def is_synonym( self, name ):\n if Taxonomy.objects.filter(\n name = name, type_name = 'synonym' ).count():\n return True\n return False", "def is_word_common(self, word):\n if word in self.stopwords:\n return True\n if re.match(r'[a-zA-Z]+[a-zA-Z]$', wo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the best matching word in the candidate sentence. These words can occure in a window of a few index left and right, but any offset will come with a penalty.
def get_word_score_in_window(self, gold, candidate, use_synonyms, index): best_score = 0 for offset in range(self.pen.word_window_left * -1, self.pen.word_window_right + 1): new_index = index + offset # iterate over the window if new_index >= 0 and new_index < len(gol...
[ "def get_best_word(point_list, words):\n scores = []\n winners = []\n for word in words:\n count = 0\n for letter in word:\n count = count + point_list[ord(letter) - 65]\n scores.append(count)\n word_dict = list(zip(words, scores))\n scores.sort(reverse=True)\n word...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the score of two frame elements by comparing the text and weighting it depending on a name match.
def get_frame_element_score(self, fe1, fe2): name_match = fe1['name'] == fe2['name'] score = self.get_text_score(fe1['spans'][0]['text'], fe2['spans'][0]['text']) if not name_match: score *= self.pen.factor_name_mismatch return score
[ "def similarity_scores(self, other):\r\n word_score = []\r\n word_score += [compare_dictionaries(other.words, self.words)]\r\n word_score += [compare_dictionaries(other.word_lengths, self.word_lengths)]\r\n word_score += [compare_dictionaries(other.stems, self.stems)]\r\n word_sco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the score for the whole sentence by comparing all frames within them. This will go on recursivly to the frame elements and to the words themselves.
def get_sentence_score(self, gold_sentence, candidate_sentence): # Collect all frames gold_frames = gold_sentence['frames'] candidate_frames = candidate_sentence['frames'] # Check first in the actual order score = 0 length = min(len(gold_frames), len(candidate_frames)) ...
[ "def score(self, words_of_sentence):\n score = 0.0\n\n sign = 1\n count = 1\n for term in words_of_sentence:\n count += 1\n if self.positive_emotions.__contains__(term):\n score += sign * 1.5\n sign = 1\n continue\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing pack, unpacking and the Frame class.
def testFramepack1(self): # Check bad frame generation: frame = stomper.Frame() def bad(): frame.cmd = 'SOME UNNOWN CMD' self.assertRaises(stomper.FrameError, bad) # Generate a MESSAGE frame: frame = stomper.Frame() frame.cmd = 'MESSAGE' fra...
[ "def testFramepack2(self):\n # Check bad frame generation:\n frame = stomper.Frame()\n frame.cmd = 'DISCONNECT'\n result = frame.pack()\n correct = 'DISCONNECT\\n\\n\\x00\\n'\n self.assertEqual(result, correct)", "def testFrameUnpack2(self):\n msg = \"\"\"MESSAGE\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing pack, unpacking and the Frame class.
def testFramepack2(self): # Check bad frame generation: frame = stomper.Frame() frame.cmd = 'DISCONNECT' result = frame.pack() correct = 'DISCONNECT\n\n\x00\n' self.assertEqual(result, correct)
[ "def testFramepack1(self):\n # Check bad frame generation:\n frame = stomper.Frame()\n\n def bad():\n frame.cmd = 'SOME UNNOWN CMD'\n\n self.assertRaises(stomper.FrameError, bad)\n\n # Generate a MESSAGE frame:\n frame = stomper.Frame()\n frame.cmd = 'MESS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing unpack frame function against MESSAGE
def testFrameUnpack2(self): msg = """MESSAGE destination:/queue/a message-id: card_data hello queue a""" result = stomper.unpack_frame(msg) self.assertEqual(result['cmd'], 'MESSAGE') self.assertEqual(result['headers']['destination'], '/queue/a') self.assertEqual(result['header...
[ "def decode_message(message):", "def testFramepack1(self):\n # Check bad frame generation:\n frame = stomper.Frame()\n\n def bad():\n frame.cmd = 'SOME UNNOWN CMD'\n\n self.assertRaises(stomper.FrameError, bad)\n\n # Generate a MESSAGE frame:\n frame = stomper....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }