query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Calculate the bouding rectangle. It is a straight rectangle, it doesn't consider the rotation of the object. So area of the bounding rectangle won't be minimum. It is found by the function cv2.boundingRect().
def __CalculateBoundingBox(self, contour): return cv2.boundingRect(contour)
[ "def boundingRect(self):\r\n bias_x_1 = 50\r\n bias_y_1 = 20\r\n i = self.x - 14\r\n j = self.y - 9\r\n\r\n parity_ind = self.y % 2\r\n side_size = 10\r\n\r\n return QRectF(bias_x_1 + int((i*1.732 + parity_ind*0.866 + 0) * side_size), bias_y_1 + int((j * 1.5 + 0) * s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the centroid of the contour. Moments up to the third order of a polygon or rasterized shape.
def __CalculateCentroid(self, contour): moments = cv2.moments(contour) centroid = (-1, -1) if moments["m00"] != 0: centroid = (int(round(moments["m10"] / moments["m00"])), int(round(moments["m01"] / moments["m00"]))) return centroid
[ "def contour_centroid(contour):\n\n moments = cv2.moments(contour)\n centroid = np.array(\n [moments['m10'] / moments['m00'], moments['m01'] / moments['m00']])\n\n return centroid[0], centroid[1]", "def centroid(self):\n A = 1 / (6*self.area)\n cx,cy = 0,0\n for ind in xrange(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the circumcircle of an object using the function cv2.minEnclosingCircle(). It is a circle which completely covers the object with minimum area.
def __CalculateCircle(self, contour): return cv2.minEnclosingCircle(contour)
[ "def boundingCircle(self):\n\n try:\n import cv2\n except:\n logger.warning(\"Unable to import cv2\")\n return None\n\n # contour of the blob in image\n contour = self.contour()\n\n points = []\n # list of contour points converted to suitabl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the countour extend.
def __CalculateExtend(self, contour): area = self.__CalculateArea(contour) boundingBox = self.__CalculateBoundingBox(contour) return area / (boundingBox[2] * boundingBox[3])
[ "def calc_base_eff_and_infl(self):\n return 2 + (self.level - 1)", "def life_insurance_to_recive_total(self):\n pass", "def calcular_incremento_costo_base(self):\n pass #TODO: Reemplazar \"pass\" y completar el método según la documentación", "def estimate_incumbent(self, startpoints):\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a curve is convex or not.
def __IsConvex(self, contour): return cv2.isContourConvex(contour)
[ "def isConvex(self):\n \n pass", "def convex(self):\n # Convex has positive curvature (2nd derivative)\n # f\"(x) = 2a, so a > 0 corresponds to convex\n return (self.a > 0)", "def isConvex(self):\n\n target = None\n for i in range(self.n):\n # Check every ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the contour moments to help you to calculate some features like center of mass of the object, area of the object etc.
def __CalculateMoments(self, contour): return cv2.moments(contour)
[ "def moments2e(image):\n assert len(image.shape) == 2 # only for grayscale images\n x, y = mgrid[:image.shape[0],:image.shape[1]]\n moments = {}\n moments['mean_x'] = sum(x*image)/sum(image)\n moments['mean_y'] = sum(y*image)/sum(image)\n\n # raw or spatial moments\n moments['m00'] = sum(image)\n moments['m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates a contour perimeter or a curve length.
def __CalculatePerimeter(self, curve): return cv2.arcLength(curve, True)
[ "def perimeter(self):\r\n option = input('Lengths or coordinate points? \\'l\\' for lengths, \\'c\\' for coordinates')\r\n if option == 'l':\r\n x = float(input('Input length1: '))\r\n y = float(input('Input length2: '))\r\n return 2 * (x + y)\r\n elif option ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the ElasticSearch index every hour.
def update_es_index(): for job in scheduler.get_jobs(): if 'task_type' in job.meta and job.meta['task_type'] == "update_index": scheduler.cancel(job) scheduler.schedule( scheduled_time=datetime.now(), func='haystack.management.commands.update_index.Command().handle()', ...
[ "def refresh(self, timesleep=0):\n get_es().refresh(self.index_name, timesleep=timesleep)", "def index_later(self):\n return", "def refresh(self):\n now = datetime.now()\n an_hour_from_now = now + timedelta(hours=1)\n if self.expire_time < an_hour_from_now:\n self.u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
JavaProcess.__init__(self, class_loc, args=[]) Initializes an external Java process.
def __init__(self, config, class_loc, args=[]): JavaProcess.config = JavaProcessConfig.configFrom_dict(config) self._cp = self._construct_classpath_str() self.class_loc = class_loc self.args = args self._process = None self._stdout = None ...
[ "def __init__(self, process=None, parent=None, **kwargs):\n super(ProcessIO, self).__init__(**kwargs)\n self.process = process\n self.parent = parent\n self.default_output = process.default_output", "def _start_process(self):\n\t\tself._proc = subprocess.Popen(self.argv)", "def __ini...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
slick solution in python ONLY zeros = [0 for i in range(zeros_and_ones.count(0))] ones = [1 for j in range(zeros_and_ones.count(1))] return zeros + ones
def zeros_before_ones(zeros_and_ones): index_i = 0 last_index = len(zeros_and_ones) - 1 while index_i < last_index: if zeros_and_ones[index_i] == 1 and zeros_and_ones[last_index] == 0: zeros_and_ones[index_i], zeros_and_ones[last_index] = zeros_and_ones[last_index], zeros_and_ones[index...
[ "def _ones_and_zero_pows(self, element, index):\n # Compute win_lst, sqr_lst\n b, n = arith1.vp(index, 2)\n win_lst, sqr_lst = [], [b]\n maxa = 1\n while True:\n ones = 0\n while n & 1:\n n >>= 1\n ones += 1\n win_lst....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers all the JRPC overloaders in the jrpc server
def register_overloaders(jrpc_server: JRPCServer, receiver) -> None: jrpc_server.register_overloader( 'Application.GetProperties', lambda server: GetPropertiesOverloader(server, receiver)) jrpc_server.register_overloader( 'Application.SetMute', lambda server: SetMuteOverloader(receiver)) jrp...
[ "def start_rpc_listeners(self):\n pass", "def cb_xmlrpc_register(args):\n args['methods'].update({'pingback.ping': pingback })\n return args", "def registerMethodForRpc(self, uri, obj, proc):\r\n self.procs[uri] = (obj, proc, False)\r\n if self.debugWamp:\r\n log.msg(\"registered ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accumulate observed stars on the same dates.
def accumulate_dates(dates, stars): start = min(dates) stop = max(dates) t_range = (stop - start).days a_dates = [start + timedelta(days = n) for n in range(t_range + 1)] a_stars = [0 for n in range(t_range + 1)] for i in range(len(dates)): idx = (dates[i] - start).days a_stars[i...
[ "def _update_rating_history(self, rating: float, date: Union[str, float]):\n self.rating_history.append((date, rating))", "def average_continuous_readings_on_same_day(d):\n print(\"Prior to averaging together readings on the same day, %i rows\" % len(d))\n assert list(d.columns) == list(['user_id_has...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate estimated number of stars observed during VLASS observation Assume 4.2 sec per pointing as estimated by Paul.
def vlass_stars(duration, n_beams): n_pointings = duration//4.2 n_observed = n_pointings*n_beams return n_observed
[ "def update_nps(self):\n self.avg_nps = (self.pos_index/(self.pos_index+1))*self.avg_nps + (1/(self.pos_index+1))*wait_for(self.info_handler,\"nps\")", "def articulation_rate(self):\r\n objects = self.__get_objects()\r\n z1 = str(objects[1]).strip().split()\r\n return int(z1[3])", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queries a nearby weather underground station for temp data and rain data
def get_weather_data(weather_station): now = datetime.datetime.now() then = now - datetime.timedelta(days=7) query_date_start = ("%d%02d%02d" % (then.year, then.month, then.day)) query_date_end = ("%d%02d%02d" % (now.year, now.month, now.day)) api_key = '/api/%s' % WUNDERGROUND_KEY history_key...
[ "def get_underground_weather(lat, long, date, key):\n response = requests.get(\"http://api.wunderground.com/api/\" + key + \"/history_\" + str(date) + \"/q/\" + str(lat) + \",\" + str(long) +\".json\")\n response = response.json()\n\n rain = response['history']['dailysummary'][0]['rain'] # Binary indicato...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all zip streams and their positions in file.
def zipstreams(filename): with open(filename, 'rb') as fh: data = fh.read() i = 0 while i < len(data): try: zo = zlib.decompressobj() yield i, zo.decompress(data[i:]) i += len(data[i:]) - len(zo.unused_data) except zlib.error: ...
[ "def zip_streams(\n fileobject=\"/data/marble/nemweb/ARCHIVE/DispatchIS_Reports/PUBLIC_DISPATCHIS_20140208.zip\",\n):\n with ZipFileStreamer(fileobject) as zf:\n for filename in zf.namelist():\n yield filename, zf.extract_stream(filename)", "def get_zips(self):\n return self.zips", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an enumeration member with a value matching `value`.
def get_member( cls, value: str, ): if not value: return None members = [ (member, member.value) for member in cls.__members__.values() ] for member, member_value in members: if member_value == value: r...
[ "def enum_by_value(cls, enum_value):\n d = cls.enum_dict_by_value()\n return d[enum_value]", "def get_enum_by_value(enum_class, value):\n try:\n return enum_class(value)\n except ValueError:\n return None", "def get_value(name, value):\n try:\n return get_enum(name)[v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator that can be used to return the first item of a callable's `list` return.
def return_first_item(func): # Define the wrapper function. def wrapper(self, *args, **kwargs): # Execute the decorated method with the provided arguments. result = func(self, *args, **kwargs) # If the function returned a result and that result is a list then # return the firs...
[ "def first(func, *args, **kwargs):\n item = next(iter(func(*args, **kwargs)), DEFAULT_SENTINEL)\n if item is DEFAULT_SENTINEL:\n raise IterableEmpty('Iterable did not yield any items')\n\n return item", "def filter_first(func: Callable, data: Iterable[Any]) -> Optional[Any]:\n return (list(filt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator that ensures all ``list`` objects in a method's arguments have the same length
def lists_equal_length(func): # Define the wrapper function. def wrapper(self, *args, **kwargs): # Collect all `list` objects from `args`. lists_args = [arg for arg in args if isinstance(arg, list)] # Collecgt all `list` object from `kwargs`. lists_kwargs = [arg for arg in kwarg...
[ "def list_check(default_return=nan):\n\n def decorate(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n for i in args:\n if not i and isinstance(i, list) and len(i) == 0:\n return default_return\n return func(*args, **kwargs)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the screen and draw the alien.
def draw(): screen.fill((0, 0, 0)) alien.draw()
[ "def clear(self):\n self.virt_screen.fill((0, 0, 0))", "def clear(self):\n\n self.screen.fill((255, 255, 255))", "def redraw(self):\n self.main_loop.draw_screen()", "def clear_screen(self):\n self.__screen.fill(self.get_config([\"board_background_color\"]), (0, self.get_config([\"t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the alien around using the keyboard.
def update(): if keyboard.left: alien.x -= 2 elif keyboard.right: alien.x += 2 if keyboard.space: alien.y = GROUND - 50 animate(alien, y=GROUND, tween='bounce_end', duration=.5) # If the alien is off the screen, # move it back on screen if alien.right > WIDTH: alien.rig...
[ "def joystick_move(self, emphasis=1):\n step = int(20*emphasis)\n self.display.ship.move_vertical(step=step)", "def joy_callback(self, msg):\n mappings = gamepad_mappings.set_gamepad_mappings(msg)\n self.move_vertical = mappings[\"button_vertical\"] # up: +1.0, down: -1.0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the Categorical feature class.
def test_categorical_feature(): feature = Categorical("abc") for element in "abc": feature.set(element) feature.set("ignore this") feature.push() for element in "abc": getattr(feature, "set_" + element)() feature.push() array = feature.array() assert array...
[ "def test_get_categorical_features_helper(self):\n (\n series,\n past_covariates,\n future_covariates,\n ) = self.inputs_for_tests_categorical_covariates\n (\n indices,\n column_names,\n ) = self.lgbm_w_categorical_covariates._get_ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the Hashed feature class.
def test_hashed_feature(): def mock(c): return ord(c) - ord('a') group = Group({"a": Hashed(buckets=3, hash=mock), "b": Hashed(buckets=5, hash=mock), }) for i in range(10): group.set_a("abcde" [i % 3]) group.set_b("abcde" [i % 5]) group.push() array = group.array() ...
[ "def test_all_features_with_data(self):\n feature1 = Feature('looktest1')\n feature1.set_percentage(5)\n\n feature2 = Feature('looktest2')\n feature2.activate()\n feature2.add_to_whitelist(3)\n\n feature3 = Feature('looktest3')\n feature3.activate()\n feature3...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if array concatenation works.
def test_array_concat(): array = Array(columns="abc") for i in range(10): array.append([1, 2, 3]) # Any 2-dimensional array witht the same number of rows should work. other = [[4, 5, 6]] * len(array) array.concat(other) assert array.shape == (10, 6) assert len(array.columns) == 6 ...
[ "def main():\n assert concat([1, 2, 3], [4, 5], [6, 7]) == [1, 2, 3, 4, 5, 6, 7]\n assert concat([1], [2], [3], [4], [5], [6], [7]) == [1, 2, 3, 4, 5, 6, 7]\n assert concat([1, 2], [3, 4]) == [1, 2, 3, 4]\n assert concat([4, 4, 4, 4, 4]) == [4, 4, 4, 4, 4]\n assert concat(['a'], ['b', 'c']) == ['a', ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
KNearest Neighbors classifier. Return the most frequent class among the k nearest points
def knn(p, k, x, t): # Number of instances in data set N = x.shape[0] Euclidean_Distance = numpy.square(x - p) #Euclidean distance dis = numpy.sum(Euclidean_Distance, axis=1) #sum of the euclidean distance inds = numpy.argsort(dis)[:k] #sort the indices of the distance array tgt_cat = ...
[ "def knn_classify_point(point, data, k, distance_metric):\n k_closest_points = get_k_closest_points(point, data, k, distance_metric)\n classification_counts = {}\n for item in k_closest_points:\n classification_type = item.classification\n if classification_type not in classification_counts:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given data (observed x and labels t) and choice k of nearest neighbors, plots the decision boundary based on a grid of classifications over the feature space.
def plot_decision_boundary(k, x, t, granularity=100, figures_root='../figures', data_name=None): print(f'KNN for K={k}') # Initialize meshgrid to be used to store the class prediction values # this is used for computing and plotting the decision boundary contour pointsX = numpy.linspace(numpy.mi...
[ "def draw_knn_boundaries(knn, h=0.02): # h = Step size in the mesh\n ax = plt.gca()\n [xmin, xmax] = ax.get_xlim()\n [ymin, ymax] = ax.get_ylim()\n # Generate the axis associated to the first feature: \n x_axis = np.arange(xmin, xmax, h)\n # Generate the axis associated to the 2nd feature: \n y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a nova client instance.
def get_nova(self, version='2.1'): if self.nova is None: self.nova = novaclient.Client(version, session=self.get_session()) return self.nova
[ "def _get_nova_client(self):\n region_name = CONF.region_name\n session = self._get_keystone_session()\n return novaclient.client.Client(2, session=session, region_name=region_name)", "def get_nova_v2_client(self):\n from novaclient import client as nova\n return nova.Client(NOV...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a glance client instance.
def get_glance(self, version='2'): if self.glance is None: self.glance = glanceclient(version, session=self.get_session()) return self.glance
[ "def _get_glance_client(self):\n session = self._get_keystone_session()\n return glanceclient.client.Client(2, session=session)", "def get_client_instance(opts={}, api_version=None):\n return get_client_class(api_version)(**opts)", "def _get_client(cls):\n\n try:\n key = os.en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a swift client.Connection instance.
def get_swift(self): if self.swift is None: self.swift = swiftclient.Connection( auth_version='3', authurl=self.auth_kwargs["auth_url"], user=self.auth_kwargs["username"], key=self.auth_kwargs["password"], tenant_name=se...
[ "def get_connection(self):\n try:\n return swift_client.Connection(\n preauthurl=self.swift_url,\n preauthtoken=self.auth_token,\n retries=5,\n auth_version='1',\n insecure=True)\n except Exception as e:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
'voltage' should be a dict of numpy arrays of floatingpoint numbers. The keys of 'voltage' are integers, 03. Each element of 'voltage' should start and end near zero. 'repetitions' and 'rate' should be integers.
def __init__( self, voltage={0:(0, 0)}, rate=500, repetitions=1, board_name='cDAQ1Mod1', voltage_limits=None, num_channels=7): self.board_name = board_name #Check Measurement and Automation Explorer self._taskHandle = ctypes.c_void_p(0) self.num_channels = num_channels DA...
[ "def update_voltages(self):\n for i in range(7):\n j = self.voltChannelLookup[0][i]\n self.voltages_raw[i] = int(self.ad7998[1].read_input_raw(j) & 0xfff)\n self.voltages[i] = self.voltages_raw[i] * 3 / 4095.0\n for i in range(6):\n j = self.voltChannelLooku...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given rows of normal vectors to line L, return points (rows) that are somewhere on each line Just find intersection with some basis line.
def points_on_lines(hyperplanes): intersections = [] for row in hyperplanes: intersections.append(an_intersection(row[:-1], -row[-1])) return np.array(intersections)
[ "def get_intersect_points(line1, line2):\n intersect_points = matrix.matrix_sol([line1, line2])\n return intersect_points", "def find_line_intersection(vm, iref, l1, l2):\n # grid between the points\n xi = np.sort(vm.x2x([l1[0] - vm.dx, l2[0] + vm.dx]))\n yi = np.sort(vm.y2y([l1[1] - vm.dx, l2[1] +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the scheduler to poll every five minutes and start it
def _init_scheduler(self): self._sched = BackgroundScheduler() self._sched.add_job(self._check_rain, trigger='cron', minute='*/5') self._sched.start()
[ "def initialize_scheduler(self):\n scheduler = BackgroundScheduler()\n scheduler.add_job(self.do, 'interval', minutes=1)\n scheduler.start()\n self.do()", "def init_scheduler():\n sched = BackgroundScheduler(daemon=True)\n sched.add_job(populate_stats,\n 'interva...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the maximum amount of rain between now and now+minute Remote procedure to be called by the core of Domos
def rain_max(self, key=None, name=None, lat=None, lon=None, minute=0): self.logger.info("added sensor for rain max %s : %s for %s minutes" % (lat, lon, minute)) if key and lat and lon and minute: try: minute = int(minute) except: return False ...
[ "async def rain_rate(self, value):\n if not value:\n return 0\n return await self.rain(value * 60)", "def max_humidity(self):\n return 60", "def find_tim(self):\n start_max = 0\n finish_max = 0\n op_mode = self.op_number + ',' + self.mode_number\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all the session names for a participant
def filter_by_participant (self, participant): sparql_results = self.query (""" select distinct ?rs ?session ?name ?number ?pid ?sitename where { BIND (<%s> AS ?participant) ?rs rdf:type austalk:RecordedSession . ?rs o...
[ "def filtered_session_names(self):\n return list(self.stage.filtered_sessions.keys())", "def search_sessions(name: str, provider: Optional[str] = None) -> List[str]:\n sessions = session_list(provider=provider).sessions\n name = name.lower()\n return [s.id for s in sessions if s.id.lower().startsw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all the session names for a site identified by site label
def filter_by_site (self, label): sparql_results = self.query (""" select distinct ?rs ?session ?name ?number ?pid WHERE { ?rs rdf:type austalk:RecordedSession . ?rs olac:speaker ?participant . ?participant austalk...
[ "def siteNames(self):\n sqlStr = \"\"\" SELECT site_name FROM rc_site;\"\"\"\n Session.execute(sqlStr)\n results = Session.fetchall()\n result = [ x[0] for x in results]\n return result", "def filtered_session_names(self):\n return list(self.stage.filtered_sessions.keys()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete one or more keys specified by ``keys``
async def delete(self, *keys, **kwargs): def gen_keys(keys): all_keys = [] for key in keys: if isinstance(key, list): all_keys += gen_keys(keys=key) else: all_keys.append(key) return all_keys al...
[ "def delete_many(self, keys):\n raise NotImplementedError()", "def delete_multi(self, keys):\n return self.run(\n lambda txn: {key: txn.delete(key) for key in keys},\n write=True)", "def delete_many(self, keys):\n return self.delete_many_values(keys)", "def delete_ke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates data_points random points between 0 and max_value and dumps them to filename Crashes my MacBook Air at the moment, only runs on my Linux desktop 😅
def create_random_dataset( # Starting with 1 billion data points data_points: int = 1_000_000_000, # ms-accuracy timestamp over a month max_value: int = 1000 * 60 * 60 * 24 * 31, # default filename: str = os.path.join("data", "random_points.json"), ): print("Starting random dataset generatio...
[ "def construct_data(model,num_pts,seed=None):\n num_dims = model.num_dims\n rv_trans = define_random_variable_transformation_hydromad(model)\n rng = numpy.random.RandomState( seed )\n pts = rng.uniform( -1., 1., ( num_dims, num_pts ) )\n pts = rv_trans.map_from_canonical_distributions( pts )\n val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Descarga la base de datos, del día de hoy, sobre covid 19 y la descomprime
def descarga_base_covid(fecha): zipname = "data/"+fecha+"COVID19MEXICO.zip" filename = fecha+"COVID19MEXICO.csv" if os.path.exists(zipname): print("La base de datos se encuentra en la carpeta") else: start_time = time() url = "http://datosabiertos.salud.gob.mx/gobmx/salud/datos_a...
[ "def descarga_base_covid_antigua(fecha):\n zipname = \"data/\"+fecha+\"COVID19MEXICO.zip\"\n filename = fecha+\"COVID19MEXICO.csv\"\n if os.path.exists(zipname):\n print(\"La base de datos se encuentra en la carpeta\")\n else:\n start_time = time()\n url = \"http://datosabiertos.sal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Descarga la base de datos de una fecha anterior a la del día actual
def descarga_base_covid_antigua(fecha): zipname = "data/"+fecha+"COVID19MEXICO.zip" filename = fecha+"COVID19MEXICO.csv" if os.path.exists(zipname): print("La base de datos se encuentra en la carpeta") else: start_time = time() url = "http://datosabiertos.salud.gob.mx/gobmx/salud...
[ "def descarga_base_covid(fecha):\n zipname = \"data/\"+fecha+\"COVID19MEXICO.zip\"\n filename = fecha+\"COVID19MEXICO.csv\"\n if os.path.exists(zipname):\n print(\"La base de datos se encuentra en la carpeta\")\n else:\n start_time = time()\n url = \"http://datosabiertos.salud.gob.m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It should create color shapes in the given data directory.
def test_create_shapes(data_dir): dataset.create_shapes(10, 10, 1, data_dir=data_dir) img_path = os.path.join(data_dir, "ellipse/0.png") assert os.path.exists(img_path) img = imageio.imread(img_path) assert img.shape == (10, 10, 4)
[ "def test_create_shapes_grayscale(data_dir):\n dataset.create_shapes(10, 10, 1, channels=1, data_dir=data_dir)\n img_path = os.path.join(data_dir, \"ellipse/0.png\")\n assert os.path.exists(img_path)\n img = imageio.imread(img_path)\n assert img.shape == (10, 10)", "def __createDataFolderStruct(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It should create grayscale shapes in the given data directory.
def test_create_shapes_grayscale(data_dir): dataset.create_shapes(10, 10, 1, channels=1, data_dir=data_dir) img_path = os.path.join(data_dir, "ellipse/0.png") assert os.path.exists(img_path) img = imageio.imread(img_path) assert img.shape == (10, 10)
[ "def test_create_shapes(data_dir):\n dataset.create_shapes(10, 10, 1, data_dir=data_dir)\n img_path = os.path.join(data_dir, \"ellipse/0.png\")\n assert os.path.exists(img_path)\n img = imageio.imread(img_path)\n assert img.shape == (10, 10, 4)", "def preprocess_directory(data_path, label_path, dam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate by how many cells the moving window should be moved. If this is nonzero, shift the fields on the interpolation grid, and add new particles.
def move_grids(self, fld, comm, time): # To avoid discrepancies between processors, only the first proc # decides whether to send the data, and broadcasts the information. dz = comm.dz if comm.rank==0: # Move the continuous position of the moving window object sel...
[ "def move_grids(self, fld, ptcl, comm, time):\n # To avoid discrepancies between processors, only the first proc\n # decides whether to send the data, and broadcasts the information.\n dz = comm.dz\n if comm.rank==0:\n # Move the continuous position of the moving window object...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate new particles at the right end of the plasma (i.e. between z_end_plasma nz_injectdz and z_end_plasma) Return them in the form of a particle buffer of shape (8, Nptcl)
def generate_particles( self, species, dz, time ) : # Shortcut for the number of integer quantities n_int = species.n_integer_quantities n_float = species.n_float_quantities # Create new particle cells if (self.nz_inject > 0) and (species.continuous_injection == True): ...
[ "def createparticles():\n if topography == \"Digital elevation model\": #Selected in GUI\n z = 276 # The elevation in the DEM at the bomb site is 200m\n else:\n z = 76 \n \n for i in range(num_of_particles):\n x = xb\n y = yb\n ws = wind_speed\n particles.appen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shift the spectral fields by n_move cells (with respect to the spatial grid). Shifting is done either on the CPU or the GPU, if use_cuda is True. (Typically n_move is positive, and the fields are shifted backwards)
def shift_spect_grid( self, grid, n_move, shift_rho=True, shift_currents=True ): if grid.use_cuda: shift = grid.d_field_shift # Get a 2D CUDA grid of the size of the grid tpb, bpg = cuda_tpb_bpg_2d( grid.Ep.shape[0], grid.Ep.shape[1] ) # ...
[ "def shift_spect_grid( self, grid, n_move,\n shift_rho=True, shift_currents=True ):\n if grid.use_cuda:\n shift = grid.d_field_shift\n # Get a 2D CUDA grid of the size of the grid\n tpb, bpg = cuda_tpb_bpg_2d( grid.Ep.shape[0], grid.Ep.shape[1] )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shift the field 'field_array' by n_move cells on CPU. This is done in spectral space and corresponds to multiplying the fields with the factor exp(ikz_truedz)n_move .
def shift_spect_array_cpu( field_array, shift_factor, n_move ): Nz, Nr = field_array.shape # Loop over the 2D array (in parallel over z if threading is enabled) for iz in prange( Nz ): power_shift = 1. + 0.j # Calculate the shift factor (raising to the power n_move ; # for negative ...
[ "def shift_spect_array_gpu( field_array, shift_factor, n_move ):\n # Get a 2D CUDA grid\n iz, ir = cuda.grid(2)\n\n # Only access values that are actually in the array\n if ir < field_array.shape[1] and iz < field_array.shape[0]:\n power_shift = 1. + 0.j\n # Calcula...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shift the field 'field_array' by n_move cells on the GPU. This is done in spectral space and corresponds to multiplying the fields with the factor exp(ikz_truedz)n_move .
def shift_spect_array_gpu( field_array, shift_factor, n_move ): # Get a 2D CUDA grid iz, ir = cuda.grid(2) # Only access values that are actually in the array if ir < field_array.shape[1] and iz < field_array.shape[0]: power_shift = 1. + 0.j # Calculate the shift...
[ "def shift_spect_array_cpu( field_array, shift_factor, n_move ):\n Nz, Nr = field_array.shape\n\n # Loop over the 2D array (in parallel over z if threading is enabled)\n for iz in prange( Nz ):\n power_shift = 1. + 0.j\n # Calculate the shift factor (raising to the power n_move ;\n # f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Note the camelcase name and unused variable. Bad bad bad.
def camelCaseFunc(): unused = 1
[ "def test_unusedVariable(self):\r\n self.flakes('''\r\n def a():\r\n b = 1\r\n ''', m.UnusedVariable)", "def test_magicGlobalsName(self):\r\n self.flakes('__name__')", "def check_for_unused_names(self):\n for s in self.unused_names:\n self.warning(\"'%s' ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether or not the Window supports user resizing
def resizable(self): return self._frame._root.resizable() == '1 1'
[ "def IsResizeable(self):\r\n \r\n return self.HasFlag(self.optionResizable)", "def _check_window_size(self):\n desktop = QtGui.QDesktopWidget()\n screensize = desktop.availableGeometry()\n width = screensize.width()\n height = screensize.height()\n min_pixel_size =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The list of all turtles attached to this Window This attribute may not be altered directly
def turtles(self): return self._turtles[:]
[ "def turtles(self):\n return self._turtles", "def turbines(self) -> List[floris.simulation.Turbine]:\n return self._farm.turbines", "def getturtle(self):\n return self", "def thermostats(self):\n\n return self._thermostats", "def lights(self):\n return list(self.GetLights(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The list of all pens attached to this Window This attribute may not be altered directly
def pens(self): return self._pencils[:]
[ "def drawables(self):\n\treturn self._Widget__w['drawables']", "def get(self):\n return list(self.pixels.values())", "def getPixels(self):\n\t\treturn self.strip.ledsColorBuffer", "def pixdimWidgets(self):\n return (self.__pixdimx, self.__pixdimy, self.__pixdimz)", "def getPixelsBuffer(self):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a turtle to this window.
def _addTurtle(self,turt): assert (type(turt) == Turtle), "Parameter %s is not a valid Turtle object" % `turt` self._turtles.append(turt)
[ "def add(self, turtle):\n\n self.start_turtles.append(turtle.position)\n self.turtles.append(turtle)\n self.items[turtle] = self.canvas.create_polygon(0, 0)\n self.update(turtle)", "def setTurtle(t):\r\n t.pu()\r\n t.goto(initialCoordinates())", "def init_turtle():\n turtle....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a pen to this window.
def _addPen(self,pen): assert (type(pen) == Pen), "Parameter %s is not a valid graphics pen" % `turt` self._pencils.append(pen)
[ "def addPen(self, name, pen=AUTO_GENERATE_PEN, updateCaption=True):\n if isinstance(pen, AutoPen):\n pen = copy.deepcopy(pen)\n pen.color = Colors.colors[self.colorIndex]\n self.colorIndex += 1\n if self.colorIndex >= len(Colors.colors):\n self.color...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a pen from this window.
def _removePen(self,pen): if pen in self._pencils: self._pencils.remove(pen)
[ "def __del__(self):\n self._screen._removePen(self)\n del self._turtle", "def remove(self) -> None:\n self.map.remove_brush(self)", "def remove_brush(self, brush: 'Solid') -> None:\n try:\n self.brushes.remove(brush)\n except ValueError:\n pass # Already...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the maximum size for this window Any attempt to resize a dimension beyond the maximum size will fail.
def setMaxSize(self,width,height): assert (type(width) == int), "width %s is not an int" % `width` assert (width > 0), "width %s is negative" % `width` assert (type(height) == int), "height %s is not an int" % `height` assert (height > 0), "height %s is negative" % `height` self....
[ "def set_maximum_size(self, max_size):\n # QWidget uses 16777215 as the max size\n if -1 in max_size:\n max_size = (16777215, 16777215)\n self.widget.setMaximumSize(QSize(*max_size))", "def SetMaxSize(*args, **kwargs):\n return _core_.Window_SetMaxSize(*args, **kwargs)", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the minimum size for this window Any attempt to resize a dimension below the minimum size will fail.
def setMinSize(self,width,height): assert (type(width) == int), "width %s is not an int" % `width` assert (width > 0), "width %s is negative" % `width` assert (type(height) == int), "height %s is not an int" % `height` assert (height > 0), "height %s is negative" % `height` self....
[ "def SetMinimumPaneSize(self, minSize):\n self._minimumPaneSize = minSize", "def set_minimum_size(self, min_size):\n # QWidget uses (0, 0) as the minimum size.\n if -1 in min_size:\n min_size = (0, 0)\n self.widget.setMinimumSize(QSize(*min_size))", "def min_size(self, min...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The heading of this turtle in degrees. Heading is measured counter clockwise from due east.
def heading(self): return float(self._turtle.heading())
[ "def heading(self):\n current_x, current_y = self._orient\n result = round(math.atan2(current_y, current_x)*180.0/math.pi, 10) % 360.0\n result /= self._degrees_per_au\n return (self._angle_offset + self._angle_orient*result) % self._fullcircle", "def heading(self):\r\n print(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Indicates whether the turtle's icon is visible. Drawing commands will still work while the turtle icon is hidden. There will just be no indication of the turtle's current location on the screen.
def visible(self): return self._turtle.isvisible()
[ "def is_visible():\n return self.turtle.visible", "def is_visible(sim_info: SimInfo) -> bool:\n return not CommonSimStateUtils.is_hidden(sim_info)", "def is_visible(self):\n return self.container['is_visible']", "def Visible(self) -> bool:", "def is_ruler_visible(self):\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Indicates whether the turtle is in draw mode. All drawing calls are active if an only if this mode is True
def drawmode(self): return self._turtle.isdown()
[ "def GetDrawMode(self):\n return self._drawmode", "def isdrawn(self):\n return hasattr(self, 'drawn')", "def isDraw(win):\n return E_DRAW_MIN <= win <= E_DRAW_MAX", "def get_drawing_mode(self) -> int:\n return self._drawing_mode", "def draw(self, canvas) -> bool:\n return Fals...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes this turtle object.
def __del__(self): self.clear() self._screen._removeTurtle(self) del self._turtle
[ "def __del__(self):\n self._screen._removePen(self)\n del self._turtle", "def delete(self):\n del self.shx.atoms[self.index]", "def delete(self):\n self.__parent__.remove(self)", "def delete(self):\n Pet.data.remove(self)", "def delete(self):\n if self.shape is not ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves the turtle forward by the given amount.
def forward(self,distance): assert (type(distance) in [int, float]), "parameter distance:%s is not a valid number" % `distance` self._turtle.forward(distance)
[ "def advance(self, amount=1):\n self._current += amount\n self.redraw()", "def advance_by(self, amount: float):\n if amount < 0:\n raise ValueError(\"cannot retreat time reference: amount {} < 0\"\n .format(amount))\n self.__delta += amount", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves the turtle backward by the given amount.
def backward(self,distance): assert (type(distance) in [int, float]), "parameter distance:%s is not a valid number" % `distance` self._turtle.backward(distance)
[ "def move_backward(self, distance):\r\n return self.move('back', distance)", "def move_backward_for_angle(self, angle, **kwargs):\n\t\tself._set_speed(kwargs)\n\t\tself.step_direction = BACKWARD\n\t\tself._move(self._calculate_steps(angle))", "def move_backward(self):\n self.at(at_pcmd, True, 0, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The pen color of this pen. The pen color is used for drawing lines and circles. All subsequent draw commands draw using this color. If the color changes, it only affects future draw commands, not past ones. This color is only used for lines and the border of circles. It is not the color used for filling in solid areas ...
def pencolor(self): return self._pencolor
[ "def penColor( self ):\n return self._penColor", "def get_color(self):\n return(self.pen_color)", "def set_pen_color(self, color: tuple) -> Rectangle:\n self.pen.color = color\n return self", "def set_color(self, color):\n self.pen_color = color", "def linecolor(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The fill color of this turtle. The fill color is used for filling in solid shapes. If the ``fill`` attribute is True, all subsequent draw commands fill their insides using this color. If the color changes, it only affects future draw commands, not past ones. This color is only used for filling in the insides of solid s...
def fillcolor(self): return self._fillcolor
[ "def fillColor(self, clr=None):\n if clr is None: return self.fill\n self.fill = clr", "def getFillColor(self):\n return getColor() if (fillColor == None) else fillColor", "def fill(self) -> int:\n return self._fill_color", "def sparkline_fill_color(self, sparkline_fill_color):\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Indicates whether the pen's icon is visible. Drawing commands will still work while the pen icon is hidden. There will just be no indication of the pen's current location on the screen.
def visible(self): return self._turtle.isvisible()
[ "def is_visible():\n return self.turtle.visible", "def is_visible(self):\n return self.container['is_visible']", "def strokeVisible(self):\n return self._strokeVisible", "def is_visible(self):\n return self._switcher.isVisible()", "def IsByPen(self) -> bool:", "def GetGripp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes this pen object.
def __del__(self): self._screen._removePen(self) del self._turtle
[ "def delete(self, obj):\n super(Canvas, self).delete(obj)", "def delete(self):\n Pet.data.remove(self)", "def delete(self):\n del self.shx.atoms[self.index]", "def delete(self):\n self.__parent__.remove(self)", "def delX(self):\n del self.components[0]", "def delete_curr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws a line segment (dx,dy) from the current pen position
def drawLine(self, dx, dy): assert (type(dx) in [int, float]), "parameter x:%s is not a valid number" % `dx` assert (type(dy) in [int, float]), "parameter y:%s is not a valid number" % `dy` x = self._turtle.xcor() y = self._turtle.ycor() self._turtle.setposition(x+dx, y+dy)
[ "def draw_line(x1, y1, x2, y2):\n penup()\n setposition(x1,y1)\n pendown()\n setposition(x2,y2)\n update()", "def draw(self, pen):\r\n lines = []\r\n vertices = self.vertices\r\n print(vertices)\r\n if vertices:\r\n for i in range(len(vertices)-1):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw a circle of radius r centered on the pen.
def drawCircle(self, r): assert (type(r) in [int, float]), "parameter r:%s is not a valid number" % `r` x = self._turtle.xcor() y = self._turtle.ycor() # Move the pen into position fstate = self._turtle.pendown() if fstate: self._turtle.penup(...
[ "def drawCircle(x, y, r):\n pen1.up()\n pen1.goto(x,y)\n pen1.down()\n pen1.circle(r)", "def circle(self, x, y, r):\n # Render units to points.\n xpt, ypt, rpt = upt(x, y, r)\n self.b.oval(xpt-rpt, ypt-rpt, 2*rpt, 2*rpt)", "def draw_circle(c):\n turtle.circle(c.radius)", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fills in the current drawing, but retains state. Normally, an object is not filled until you set the state to False. Calling this method executes this fill, without setting the state to False. If fill is False, this method does nothing.
def flush(self): if self.fill: self._turtle.fill(False) self._turtle.fill(True)
[ "def setFilled(self, fill):\n isFilled = fill\n repaint()", "def update_fill(self, event):\n if event.type == 'FILL':\n self.update_positions_from_fill(event)\n self.update_holdings_from_fill(event)", "def fill():\n # Switch in edit mode\n bpy.ops.object....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hgtStartData is the source data from the NASA JPL topological data
def __init__(self, hgtStartData): self.data = [] for row in hgtStartData: toAdd = [] for height in row: toAdd.append([height, 0]) self.data.append(toAdd) self.maxX = len(hgtStartData[0]) - 1 self.maxY = len(hgtStartData) - 1 ...
[ "def test_data_source_soaps_id_head(self):\n pass", "def prep_data_JLP(path):\n journeys_all = pd.read_csv(\n path,\n parse_dates=['Start_Date_of_Route', 'Start_Time_of_Route',\n 'End_Time_of_Route'],\n dayfirst=True)\n branches = gv.STORE_SPEC.keys()\n jou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the topological height at (x, y)
def getHeight(self, x, y): if x > self.maxX or y > self.maxY or x < 0 or y < 0: return 10000000 # effectively infinity return self.data[y][x][0]
[ "def find_height(self, x, z):\n x_index = bisect_left(self.x_terrain, x)\n z_index = bisect_left(self.z_terrain, z)\n if x_index < len(self.x_terrain)-2:\n x_finded = self.x_terrain[x_index+1]\n else :\n x_finded = self.x_terrain[-1]\n if z_index < len(self.z...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the level of water at the point (x, y)
def getWater(self, x, y): if x > self.maxX or y > self.maxY or x < 0 or y < 0: raise Exception("accessed an invalid position in method getWater") return self.data[y][x][1]
[ "def water_depth(self,x,y):\n bed=self.bed_topo(x,y)\n D = -bed*(bed<0.0)\n \n return D", "def get_water_level(self):\n return self.water_level", "def water_depth(self,x):\n bed=self.bed_topo(x)\n D = -bed*(bed<0.0)\n return D", "def get_water_depth_at(x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to check if a number is very small.
def isSmall(number): return abs(number) < epsilon
[ "def is_small(a:int, b:int) -> bool:\n return a <= b", "def is_int(num):\n\n return abs(num - round(num)) < 1e-09", "def checkImgSize(img_size, number=4):\n if all([x >= 2**number for x in img_size]):\n return number\n else:\n return int(np.min(np.floor(np.log2(img_size))))", "def ha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the crossProduct of the vectors p2 p1 and p3 p1.
def crossProduct(p1, p2, p3): return ( -(p1[1]*p2[0]) + p1[0]*p2[1] + p1[1]*p3[0] - p2[1]*p3[0] - p1[0]*p3[1] + p2[0]*p3[1] )
[ "def cross_product(p0,p1,p2):\n\treturn (((p1[0]-p0[0])*(p2[1]-p0[1]))-((p2[0]-p0[0])*(p1[1]-p0[1])))", "def crossProduct(self, *args):\n return _almathswig.Position3D_crossProduct(self, *args)", "def cross(p1, p2):\n return p1[0]*p2[1] - p1[1]*p2[0]", "def cross_product(v1, v2):\r\n x3 = v1[1] *...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update employment history for given profile id.
def update_work_history(work_history_list, profile_id): saved_work_history_ids = set() for work_history in work_history_list: work_history_id = work_history.get("id") work_history_instance = None if work_history_id: try: work_history_instance = Employment.obje...
[ "def update(self,employment=None,access=None):\n\n if employment != None:\n self.employment.value = employment\n if access != None:\n self.access.value = access\n self.save.click()", "def update_profits(self, next_profit):\n self.profit = next_profit\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate through fields in serializer and set all to required except ignore_fields
def set_fields_to_required(serializer, ignore_fields=None): if ignore_fields is None: ignore_fields = [] for field in serializer.fields.values(): if field.field_name not in ignore_fields: field.required = True field.allow_null = False field.allow_blank = False
[ "def filter_required_fields(self, document):\n document.json = {\n field: value for field, value in document.json.items() if field in required_fields\n }\n return document", "def _required_fields(self, *fields):\n missing_fields = []\n for field in fields:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an instance for a given Jenkins URL. The returned instance is usually a instance of a PlatformJenkins subclass (this allows to switch to a different Jenkins API.
def get_jenkins(cls, url, template_dir=None): return PlatformJenkinsJavaCLI(template_dir, url)
[ "def get_object(session, path_or_url):\n parsed = urlparse.urlparse(path_or_url)\n url = urlparse.urljoin(session.jenkins_url, '%s/api/json' % parsed.path)\n resp = session.get(url)\n resp.raise_for_status()\n return resp.json()", "def get_from_url(url, base_path, api_version, credentials):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if a given view exists.
def view_exists(self, view): with open("/dev/null", "w") as devnull: call = subprocess.Popen(self.cli + [PlatformJenkinsJavaCLI.GET_VIEW, view], stdout=devnull, stderr=devnull) call.wait() return call.returncode == 0
[ "def has_view(view_type, meta_type):", "def viewExists(self, objType, viewname):\n sql = \"select distinct schemaname, tablename from pg_tables where schemaname = '%s' and tablename = '%s'\"%(objType, viewname)\n result = self.__executeQuery(sql)\n if result:\n return True\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a View, defined by XML in view_xml_filename. If the file exists, it will be update using the provided definition.
def set_view(self, view, view_xml_filename): if self.view_exists(view): command = PlatformJenkinsJavaCLI.UPDATE_VIEW else: command = PlatformJenkinsJavaCLI.CREATE_VIEW with open(view_xml_filename) as view_xml_file: view_xml = view_xml_file.read() cal...
[ "def _view(template, filename):\n\n if \".\" in template:\n template = os.path.join(*(template.split(\".\")))\n\n view = os.path.join(current.request.folder, \"modules\", \"templates\",\n template, \"views\", filename)\n\n try:\n # Pass view as f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if the given job exists.
def job_exists(self, job): with open(os.devnull, 'w') as devnull: result = subprocess.call(self.cli + [PlatformJenkinsJavaCLI.GET_JOB, job.name], stdout=devnull) return result == 0
[ "def job_exists(self, job_id):\n\n return True if self.get_status(job_id) else False", "def job_exists(self, job_name):\n return os.path.exists(self.jobs_path + '/' + job_name)", "def has_job(self, job_name) -> bool:\n self.log.info(\"Checking if job already exists: %s\", job_name)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes a given job from Jenkins.
def delete_job(self, job): subprocess.call(self.cli + [PlatformJenkinsJavaCLI.DELETE_JOB, job.name])
[ "def delete_job(session, name):\n url = urlparse.urljoin(session.jenkins_url, '/job/%s/doDelete' % name)\n resp = session.post(url)\n resp.raise_for_status()", "def _delete_job(self, job):\n if self.jenkins.job_exists(job):\n self.jenkins.delete_job(job)", "def delete(job_id):\n\t_job...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Triggers given job, providing a set of parameters to it.
def trigger_job(self, job, parameters=None): parameters = parameters or {} parameter_list = [] for key in parameters: parameter_list.append("-p") parameter_list.append("%s=%s" % (key, parameters[key])) if subprocess.call(self.cli + [PlatformJenkinsJavaCLI.BUILD_JO...
[ "def trigger_job(self, job_id, auth_token=RUNDECK_AUTH_TOKEN, argString=None):\n self.headers['X-Rundeck-Auth-Token'] = auth_token\n if argString:\n payload = {\"argString\": argString}\n self.job_response = requests.post(json=payload,\n url= \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables given job on Jenkins.
def enable_job(self, job): if subprocess.call(self.cli + [PlatformJenkinsJavaCLI.ENABLE_JOB, job.name]) != 0: raise PlatformJenkinsException("Enabling job failed: " + job.name)
[ "def _enable_job(self, job):\n if self.jenkins.job_exists(job):\n self.jenkins.update_job(job)\n self.jenkins.enable_job(job)\n else:\n self.jenkins.create_job(job)", "def toggle_job(session, job_name, enable):\n url = urlparse.urljoin(session.jenkins_url,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disables given job on Jenkins.
def disable_job(self, job): if subprocess.call(self.cli + [PlatformJenkinsJavaCLI.DISABLE_JOB, job.name]) != 0: raise PlatformJenkinsException("Disabling job failed: " + job.name)
[ "def _disable_job(self, job):\n if self.jenkins.job_exists(job):\n self.jenkins.disable_job(job)", "def DisableJob(self, job_urn, token=None):\n cron_job = aff4.FACTORY.Open(job_urn, mode=\"rw\", aff4_type=\"CronJob\",\n token=token)\n cron_job.Set(cron_job....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a given job on Jenkins.
def create_job(self, job): call = subprocess.Popen(self.cli + [PlatformJenkinsJavaCLI.CREATE_JOB, job.name], stdin=subprocess.PIPE) out, err = call.communicate(input=platform_ci.jjb.get_job_as_xml(job, self.template_dir)) call.wait() if call.returncode != 0: logging.info(out)...
[ "def createJob(self, name):\n self._server.create_job(name, jenkins.EMPTY_CONFIG_XML)\n return self.job(name)", "def create(cfg, jobs):\n server = jenkins_utils.server_factory(cfg)\n libjobs.createJobs(server, jobs)", "def create_job():\n data = request.json\n job = {\n \"reposi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update a given job on Jenkins.
def update_job(self, job): call = subprocess.Popen(self.cli + [PlatformJenkinsJavaCLI.UPDATE_JOB, job.name], stdin=subprocess.PIPE) call.communicate(input=platform_ci.jjb.get_job_as_xml(job, self.template_dir)) call.wait() if call.returncode != 0: raise PlatformJenkinsExcepti...
[ "def update(cfg, jobs):\n server = jenkins_utils.server_factory(cfg)\n libjobs.updateJobs(server, jobs)", "def update(self, job_name, param_name, value, description=None):\n if job_name in self._jobs:\n getattr(self._jobs[job_name], param_name).update(value, description)\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates a job build description.
def set_build_description(self, job_name, build, description): try: subprocess.check_call(self.cli + [PlatformJenkinsJavaCLI.SET_DESCRIPTION, job_name, build, description]) except subprocess.CalledProcessError: message = "Setting build description failed (job={0}, build={1}, desc...
[ "def set_current_build_description(self, description):\n job_name = os.environ.get(\"JOB_NAME\", None)\n build_id = os.environ.get(\"BUILD_NUMBER\", None)\n if job_name is not None and build_id is not None:\n self.set_build_description(job_name, build_id, description)", "def job_de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates a job build description for the current build. This method is intended to be run in an environment where JOB_NAME and BUILD_NUMBER are set in the environment, such as from within the job build itself. If either of the environment variables is not set, setting the description is not attempted at all.
def set_current_build_description(self, description): job_name = os.environ.get("JOB_NAME", None) build_id = os.environ.get("BUILD_NUMBER", None) if job_name is not None and build_id is not None: self.set_build_description(job_name, build_id, description)
[ "def set_build_description(self, job_name, build, description):\n try:\n subprocess.check_call(self.cli + [PlatformJenkinsJavaCLI.SET_DESCRIPTION, job_name, build, description])\n except subprocess.CalledProcessError:\n message = \"Setting build description failed (job={0}, build...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loop through the exposure list and construct an observation table.
def _buildtable(self): tabrows = [] for i, (expid, exfiles) in enumerate(self._exposure_files.items()): specflux_b, specflux_r, specflux_z = [], [], [] tab = None if len(exfiles) == 0: continue print(expid) for exfile in exf...
[ "def buildExposureTable(exposures, fields, instruments):\n name = []\n ra = []\n dec= []\n field= []\n inst = []\n airmass = []\n mjd = []\n exptime = []\n epoch = []\n apcorr = []\n index = 0\n for k,e in exposures.items():\n name.append(e.name)\n ra.append(getDegr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
String representation of the exposure sequence.
def __str__(self): output = ['Tile ID {}'.format(self._tileid)] for ex, files in self._exposure_files.items(): filenames = '- exposure {:08d}\n'.format(ex) for f in files: filenames = '{} + {}\n'.format(filenames, f) output.append(filenames) ...
[ "def to_string(self):\n return self.sequence", "def get_sequence_str(self):\n return self.sequence.get_sequence()", "def __str__(self):\n return str(self._seq)", "def __str__(self):\n return '{},{},{},{},{},{},{},{},{}'.format(self.video_filename, self.driver_id, self.which_map, se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns source that matches the user provided source_id or display_name.
def ExtractMatchingSourceFromResponse(response, args): for source in response: if ((args.source and source.name.endswith(args.source)) or (args.source_display_name and source.displayName == args.source_display_name)): return source raise core_exceptions.Error( "Source: %s not found....
[ "def find_source(self, name):\n t = filter( lambda x: x.name==name, self.point_sources+self.extended_sources)\n return t[0] if len(t)==1 else None", "def getSourceForId(context, identifier):\n nearest = getattr(context, identifier, None)\n if IExternalSource.providedBy(nearest):\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure that the specified node is visible.
def ensure_visible(self, node): try: components = node.namespace_name.split('/') # Make sure that the tree is expanded down to the context that # contains the node. binding = self.root for atom in components[:-1]: binding = binding.ob...
[ "def assertVisible(self, element):\n return self.assertTrue(element.is_displayed())", "def Visible(self) -> bool:", "def ensure_visible(self):\n self.widget.setVisible(True)\n action = self._widget_action\n if action is not None:\n action.setVisible(True)", "def setVisib...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method test the endpoint for getting bucketlist items
def test_get_bucketlist_items(self): email = "test@test.com" _pword = "test" user = User.query.filter_by(email=email).first() bucketlist = BucketList.query.filter_by(user_id=user.id, id=1).first() items_no = len(bucketlist.bucketlist_items) headers = self.authentica...
[ "def test_get_bucketlist_items(self):\n resp = self.client.post('/bucketlists',\n data=json.dumps(self.bucketlist),\n content_type=\"application/json\", headers={\n \"Authorization\": self.token\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method test the endpoint for adding bucketlist item
def test_add_bucketlist_items(self): email = "test@test.com" _pword = "test" user = User.query.filter_by(email=email).first() bucketlist = BucketList.query.filter_by(user_id=user.id, name="test bucketlist").first() item_no = BucketListItem.query.filter_by(bucketlist_id=bucke...
[ "def test_create_bucketlist_item(self):\n resp = self.client.post('/bucketlists',\n data=json.dumps(self.bucketlist),\n content_type=\"application/json\", headers={\n \"Authorization\": self.token\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method tests that there can not be more than one bucketlist item added with the same name. We will use one of the already existing bucketlist names 'test item'
def test_fail_repeated_buckelist_item(self): user = User.query.filter_by(email="test@test.com").first() bucketlist = BucketList.query.filter_by(user_id=user.id, name="test bucketlist").first() item_no = BucketListItem.query.filter_by(bucketlist_id=bucketlist.id).count() response = se...
[ "def test_add_bucketlist_item(self):\n self.test_store.add_bucketlist('travel', 'visit london')\n test_bucketlist = self.test_store.get_single_bucketlist(1)\n # import pdb; pdb.set_trace()\n initial_bucketlist_items = len(test_bucketlist['items'])\n self.test_store.add_bucketlist_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method tests the end point for updating a bucket list item using put
def test_put_bucketlist_item(self): data = {"name": "bucketlist item name", "completed": "true"} email = "test@test.com" _pword = "test" user = User.query.filter_by(email=email).first() bucketlist = BucketList.query.filter_by(user_id=user.id, name="test bucketlist").first() ...
[ "def test_put_bucketlists_detail(self):\n\n update_bucketlist_item = {\"title\": \"Item Three\"}\n\n # Asserting no access without token\n response = self.client.put(url_one, update_bucketlist_item)\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response.data, me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method tests the error raised when end point for updating a bucket list item using put contains the wrong id
def test_put_item_wrong_id(self): data = {"name": "bucketlist item name", "completed": "true"} email = "test@test.com" _pword = "test" user = User.query.filter_by(email=email).first() bucketlist = BucketList.query.filter_by(user_id=user.id, name="test bucketlist").first() ...
[ "def test_id_of_bucket_to_be_edited_is_invalid(self):\n with self.client:\n # Get an auth token\n token = self.get_user_token()\n # Update the bucket name\n res = self.client.put(\n '/bucketlists/bucketid',\n headers=dict(Authorization...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method tests the request to delete a bucketlist item
def test_delete_bucketlist_item(self): email = "test@test.com" _pword = "test" user = User.query.filter_by(email=email).first() bucketlist = BucketList.query.filter_by(user_id=user.id, name="test bucketlist").first() item = BucketListItem.query.filter_by(bucketlist_id=bucket...
[ "def bucketlist_item_delete():\n pass", "def test_bucketlist_item_deletion(self):\n resp = self.client.post(\"/auth/register/\", data=self.user_details)\n self.assertEqual(resp.status_code, 201)\n result = self.client.post(\"/auth/login/\", data=self.user_details)\n\n access_token =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method tests the error raised when end point for delete a bucket list item contains the wrong id
def test_delete_item_wrong_id(self): email = "test@test.com" _pword = "test" user = User.query.filter_by(email=email).first() bucketlist = BucketList.query.filter_by(user_id=user.id, name="test bucketlist").first() item = BucketListItem.query.filter_by(bucketlist_id=bucketli...
[ "def test_deletion_handles_no_bucket_found_by_id(self):\n with self.client:\n response = self.client.delete(\n '/bucketlists/1',\n headers=dict(Authorization='Bearer ' + self.get_user_token())\n )\n data = json.loads(response.data.decode())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method is used to send request for put for the bucketlist item to the api
def put_bucketlist_item(self, email, password, bucketlist_id, item_id, data): headers = self.authentication_headers(email=email, password=password) return self.client.put( '/api/v1/bucketlist/{}/items/{}'.format(bucketlist_id, item_id), content_type="application/json", ...
[ "def test_put_bucketlist_item(self):\r\n data = {\"name\": \"bucketlist item name\", \"completed\": \"true\"}\r\n email = \"test@test.com\"\r\n _pword = \"test\"\r\n user = User.query.filter_by(email=email).first()\r\n bucketlist = BucketList.query.filter_by(user_id=user.id, name=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if model uses submodules
def defined_submodule(arr): return any([el.endswith('_module]') for el in arr])
[ "def model_from_timm(model: Module) -> bool:\n if \"timm\" in model.__module__.split(\".\"):\n return True\n\n is_fisrt = True\n for sub_module in model.modules():\n if is_fisrt: # First module is the module itself.\n is_fisrt = False\n continue\n\n if model_from...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fills up the ReplayBuffer memory with PRETRAIN_LENGTH number of experiences before training begins.
def initialize_memory(self, pretrain_length, env): if self.memlen >= pretrain_length: print("Memory already filled, length: {}".format(len(self.memory))) return interval = max(10, int(pretrain_length/25)) print("Initializing memory buffer.") obs = env.states ...
[ "def __initialize_buffers(self):\n obs = self.env.reset()\n\n bar = (range(MIN_REPLAY_SIZE))\n for _ in bar:\n action = self.env.sample()\n\n new_obs, rew, done, _ = self.env.step(action)\n transition = (obs, action, rew, done, new_obs)\n obs = new_ob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }