query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
create dark mask for adding black box | def create_dark_mask():
black_dx = 60
black_dy = 20
dark_mask = np.zeros((black_dx, black_dy))
for k in range(black_dy):
dark_mask[:, k] = (np.abs(k - black_dy // 2) / (black_dy / 2.)) ** 2
return dark_mask | [
"def _draw_mask_on_image(self, mask):\n mask = self.STANDARD_COLORS_ARRAY[mask]\n cv2.addWeighted(mask,self.config.ALPHA,self.image,1.0,0,self.image)",
"def mask_extract(self):\r\n\r\n # define the background color for mask extraction\r\n lower_green = (30,80,80)\r\n upper_green = (... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create indices for elastic deformation used once at the start epoch | def create_elastic_indices():
# initial values
alpha, alpha2, sigma = 10, 10, 50
shape = (96, 288) # same as shape of input images
x_mesh, y_mesh = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))
# below is used once per epoch for the elastic deformation
g_1d = signal.gaussian(300, sigma... | [
"def create_index():",
"def create_indices(self):\n\t\tself.pg_eng.build_idx_ddl()\n\t\tself.pg_eng.create_indices()",
"def es_indexing(builder) -> int:\n # create index\n if not create_index():\n return 0\n print(\"es is connected and index created succeed, starting indexing the examples...\")... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell how many package langpacks are in a repository. | def _count_langpacks(server_config, repo_id):
keyword = 'Package Langpacks:'
completed_proc = cli.Client(server_config).run((
'pulp-admin repo list --repo-id {} '
'--fields content_unit_counts'
).format(repo_id).split())
lines = [
line for line in completed_proc.stdout.splitlines... | [
"def GetNumberOfRepoMetas(language: scrape_repos_pb2.LanguageToClone) -> int:\n path = pathlib.Path(language.destination_directory)\n if path.is_dir():\n return len([x for x in path.iterdir() if x.suffix == '.pbtxt'])\n else:\n return 0",
"def test_get_number_packages(self):\n\n self.repo.repo = '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload a langpack to the repository. | def test_01_upload_langpacks(self):
cmd = (
'pulp-admin rpm repo uploads langpacks --repo-id {0} '
'--name {1} --install {1}-%s'
).format(self.repo_id, utils.uuid4()).split()
self.client.run(cmd)
num_langpacks = _count_langpacks(self.cfg, self.repo_id)
sel... | [
"def create(self):\n self.parser.add_argument('lp_file',\n help=\"Language pack file.\")\n args = self.parser.parse_args()\n with open(args.lp_file) as lang_pack_file:\n try:\n data = json.load(lang_pack_file)\n except ValueEr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all langpacks from the repository. | def test_02_remove_langpacks(self):
cmd = (
'pulp-admin rpm repo remove langpacks --repo-id {0} '
'--str-eq repo_id={0}'
).format(self.repo_id).split()
self.client.run(cmd)
package_counts = _count_langpacks(self.cfg, self.repo_id)
self.assertEqual(package_... | [
"def clean(self) -> None:\n # remove all *.py and *.pyi files in the folder\n for wc in [\"*.py\", \"*.pyi\", \"modules.json\"]:\n for f in (self.package_path).rglob(wc):\n f.unlink()",
"def delete(self):\n self.parser.add_argument('lp_id',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
E_recoverable = n_rb E_available | def ComputeERecoverable(self):
pass | [
"def Available(self) -> int:",
"def nsbchainallocfailrate(self) :\n\t\ttry :\n\t\t\treturn self._nsbchainallocfailrate\n\t\texcept Exception as e:\n\t\t\traise e",
"def used_recovery (node):\n pass",
"def nsbchainallocfail(self) :\n\t\ttry :\n\t\t\treturn self._nsbchainallocfail\n\t\texcept Exception as e:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Balance the weights between positive and negative class. | def balance_training_weight(w, y):
sample_weight = w.copy()
neg_mask = (y == 0)
pos_mask = (y == 1)
bkg_sum_weight = np.sum(sample_weight[neg_mask])
sig_sum_weight = np.sum(sample_weight[pos_mask])
sample_weight[pos_mask] = sample_weight[pos_mask] / sig_sum_weight
sample_weight[neg_mas... | [
"def test_negative_weights_are_balanced(self):\n w1, w2 = rootIO.balance_weights(self.a - 1, self.b - 1)\n self.assertTrue(np.isclose(np.sum(w1), np.sum(w2)))",
"def test_weights_are_balanced(self):\n w1, w2 = rootIO.balance_weights(self.a, self.b)\n self.assertTrue(np.isclose(np.sum(w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Steps the solution (should be overridden) return True if more work to be done | def step_solution(self):
import time, random
time.sleep(1.0)
print '(step_solution) Implement me!'
return True if random.random() < 0.25 else False | [
"def SolveSolutionStep(self):\n return True",
"def _check_for_completion(self, node):\n dis=0\n for i in range(node.state.size):\n dis+=(node.state[i]-self.goal.state[i])**2\n\n dis=np.sqrt(dis)\n if(dis<=self.step_size):\n return True\n else: return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts the algorithm thread | def start_threading(self):
if self.algorithm_thread == None:
self.reset_algorithm()
self.algorithm_thread = Thread(target=self.run_algorithm)
self.running = True
self.algorithm_thread.start() | [
"def start(self):\n\t\t# pre-fill buffer, before any calculations can take place\n\t\tfor i in range(max(self.bufsize // self.blocksize, 1)):\n\t\t\tself._read()\n\t\t\n\t\tself.run = True\n\t\tself.read_thread.start()\n\t\tself.trig_thread.start()",
"def start(self):\n if self.ownThreadpool:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when run is clicked | def on_run_clicked(self):
self.start_threading()
self.stepping = False
self.step_event.set() | [
"def on_run_button(self, event):\n text = _(u\"Run button pressed.\")\n if self.state == 0:\n self.canvas_2d.render(text)\n else:\n self.canvas_3d.render()\n self.run_command()",
"def click(self):\r\n pass",
"def on_main_button_clicked(self, *args):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when step is clicked | def on_step_clicked(self):
self.start_threading()
self.stepping = True
self.step_event.set() | [
"def step(self, action):",
"def on_next_clicked(self):\r\n self.signal_step.emit()",
"def on_run_clicked(self):\n self.start_threading()\n self.stepping = False\n self.step_event.set()",
"def step(self, state):",
"def click(self):\r\n pass",
"def step(self, step):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Puts the buttons into the layout, this lets additional buttons to be inserted | def pack_buttons(self):
button_layout = QtGui.QHBoxLayout()
for button in self.buttons:
button_layout.addWidget(button)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.costmap_widget)
layout.addLayout(button_layout)
# layout.addStretch(1)
s... | [
"def add_side_buttons(self):\n # Top and bottom buttons\n for col in range(self._grid.width):\n top_button = widgets.HExitButton('^', -1, col)\n bottom_button = widgets.HExitButton('v', self._grid.height, col)\n self._graphic_grid.addWidget(top_button, 1, 2 + col)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that the put_template is called when a Distllery is saved. | def test_distillery_saved(self, mock_template):
distillery = Distillery.objects.get_by_natural_key(
'elasticsearch.test_index.test_docs')
distillery.save()
self.assertEqual(mock_template.call_count, 1) | [
"def test_update_template(self):\n pass",
"def test_no_template(self):\n distillery = Distillery.objects.get_by_natural_key(\n 'mongodb.test_database.test_docs')\n try:\n distillery.save()\n except AttributeError:\n self.fail('put_template() raised Attr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that the put_template is called when a Collection is saved. | def test_collection_saved(self, mock_template):
collection = Collection.objects.get_by_natural_key(
'elasticsearch', 'test_index', 'test_docs')
collection.save()
self.assertEqual(mock_template.call_count, 1) | [
"def test_collections_upsert_collection(self):\n pass",
"def test_update_collection(self):\n pass",
"def test_create_collection(self):\n pass",
"def test_collection_put(testapp, execute_counter):\n initial = {\n 'title': \"Testing\",\n 'type': \"object\", # include a non-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that the put_template is called when a Distllery is saved. | def test_no_template(self):
distillery = Distillery.objects.get_by_natural_key(
'mongodb.test_database.test_docs')
try:
distillery.save()
except AttributeError:
self.fail('put_template() raised AttributeError unexpectedly') | [
"def test_distillery_saved(self, mock_template):\n distillery = Distillery.objects.get_by_natural_key(\n 'elasticsearch.test_index.test_docs')\n distillery.save()\n self.assertEqual(mock_template.call_count, 1)",
"def test_update_template(self):\n pass",
"def test_update_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return offset of local zone from GMT | def _local_time_offset():
if time.localtime().tm_isdst and time.daylight:
return -time.altzone
else:
return -time.timezone | [
"def local_time_zone_offset(self) -> str:\n return pulumi.get(self, \"local_time_zone_offset\")",
"def find_by_offset(self):\n offset = int(self.timezone)*-1\n if offset < -14 or offset > 12:\n raise ValueError(f\"{offset} is not a valid offset\")\n if offset > 0:\n offset = \"+\" + str(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the ants image is LPI | def is_lpi(image: ANTsImage) -> bool:
return ants.get_orientation(image) == "LPI" | [
"def have_pil(self):\n return HAVE_PIL",
"def pil_available():\n out = False\n try:\n from PIL import Image # noqa\n out = True\n except ImportError:\n pass\n return out",
"def has_legacy_image(self):\n pass",
"def verify_image(filename_or_obj, format, resolutio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A convenient function to throw an error if all threads are not closed | def verify_all_threads_closed(allowable_threads=None):
if allowable_threads is None:
allowable_threads = []
allowable_threads += ['pydevd.Writer',
'pydevd.Reader',
'pydevd.CommandThread',
'profiler.Reader',
... | [
"def _TryCloseThreads(self):\n for thread in self._threads:\n thread.should_exit = True\n for thread in self._threads:\n if thread.isRunning():\n thread.wait(2000)\n if thread.isRunning():\n self._PrintError('Could not terminate {:s}'.format(thread))\n self.close()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays the list of computers currently owned by the company with links to details for each one. | def computers(request):
computers = Computer.objects.all().order_by("make", "model")
context = {
"computers": computers
}
return render(request, 'agileHR/computers.html', context) | [
"def list_collaborators(request):\n log.debug(\"List collaborators\")\n users = User.objects.all().exclude(id=request.user.id)\n collaborators = get_collaborator(request)\n return render(request, 'integrator/collaborators.html', {'users': users,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays search results when a user searches for a computer by make or model | def computer_search(request):
if request.method == "POST":
search_text = request.POST["search_text"]
if search_text is not "":
by_make = Computer.objects.filter(make__contains=search_text).order_by("make", "model")
by_model = Computer.objects.filter(model__contains=search_... | [
"def search():\n keyword = request.form['search']\n # https://www.bookdepository.com/search?searchTerm=Machine+LEArning&search=Find+book\n url = search_url + keyword.replace(' ', '+') + '&search=Find+book' # convert url\n books = crawl_bookrepo(url)\n cate = 'Search result for \"%s\"' % keyword\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays the details about a single computer owned by the company. | def computer_detail(request, computer_id):
computer = get_object_or_404(Computer, pk=computer_id)
current_assignment = EmployeeComputer.objects.filter(computer_id=computer_id).filter(date_revoked=None)
assignment_history = EmployeeComputer.objects.filter(computer_id=computer_id).exclude(date_revoked=None).... | [
"def get_computer(self, info):\n pass",
"def computers(request):\n\n computers = Computer.objects.all().order_by(\"make\", \"model\")\n context = {\n \"computers\": computers\n }\n return render(request, 'agileHR/computers.html', context)",
"def displayProfile(companyID):\n a = comp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes a computer ONLY if it has NEVER been assigned to an employee. | def delete_computer(request, computer_id):
if request.method == "POST":
computer = Computer.objects.get(pk=computer_id)
computer.delete()
return HttpResponseRedirect(reverse("agileHR:computers"))
else:
computer = Computer.objects.get(pk=computer_id)
assignments = Employ... | [
"def delete_computer(self):\n delete_button = self.driver.find_element_by_xpath(locators.delete_computer_button)\n delete_button.click()",
"def del_co_worker(self, employee):\n self.co_worker_list.remove(employee)",
"def delete_machine(args):\n session = Session()\n # the following is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assigns a random amount of lives for each new target that is created. Lives can increase as the score increases | def generate_lives(self, score, shooter):
self.lives = random.randint(1, (score.score * shooter.damage // 4 + 1)) | [
"def create_target(self):\n\n # I used a random number variable (rand_target) in order to randomize the target created each time this function\n # is called.\n stand = StandardTarget()\n strong = StrongTarget()\n safe = SafeTarget()\n bird = Bird()\n\n rand_target = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes Random Walk Controversy Polarization | def random_walk_pol(G, ms, n_influencers, n_sim, n_walks):
left_nodes = [node for node in ms if ms[node] == 0]
right_nodes = [node for node in ms if ms[node] == 1]
left_influencers, right_influencers = get_influencer_nodes(G, left_nodes, right_nodes, n_influencers)
rwc_dist = []
... | [
"def random_walk(n):\n x, y=0,0\n for i in range(n):\n (dx,dy)=random.choice([(0,1),(0,-1),(1,0),(-1,0)])\n x+=dx\n y+=dy\n return(x,y)",
"def random_walk(n, p):\n random_array = np.random.uniform(0, 1, n)\n left = random_array[random_array > p].size\n right = n - left\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a pyll graph with hyperparameters that will construct a sklearn.ensemble.AdaBoostClassifier model. | def ada_boost_classifier(name: str, algorithm: typing.Union[str, Apply] = None, **kwargs):
def _name(msg):
return f"{name}.ada_boost_{msg}"
hp_space = _weight_boosting_hp_space(_name, **kwargs)
hp_space["algorithm"] = _weight_boosting_algorithm(_name("algorithm")) if algorithm is None else algorit... | [
"def modelAdaBoost():\n num_estimators = [1,5,10,50,100,150]\n learning_rate = 0.1\n max_depth = 3\n base_estimate = DecisionTreeClassifier(max_depth=max_depth)\n random_state = 20 # Do not change this random_state\n \n obj_boost = []\n \n \"\"\" \n Create a list of objects for the cla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the day of the week (Monday, Tuesday, Wednesday, etc) | def day_of_week():
return calendar.day_name[datetime.date.today().weekday()] | [
"def _get_weekDay(self):\n return self.datetime.weekday()",
"def get_weekdigit():\n return date.today().weekday()",
"def weekday(self):\n return (int(self.day+.5) + 1) % 7 + 1",
"def weekday(day):\n return (day % 7) - 1",
"def weekday() -> str:\n weekday_num = date.today().isocalendar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the day of the month (1, 2, 3, 4, 5, etc) | def day_of_month():
return datetime.date.today().day | [
"def date_day_of_month(date):\n return date.day",
"def date_day(date):\n return date_day_of_month(date)",
"def day_of_month(self):\n return self._day_of_month",
"def days_in_month(self):\n return calendar.monthrange(self.year, self.month)[1]",
"def _get_day(self):\n return self.da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a song based on the day of the week | def get_weekday_song():
current_day = day_of_week()
print(f"WEEKDAY:{current_day}")
if (current_day == "Monday"):
return random.choice([ \
"Monday - Imagine Dragons", \
"Monday Morning - Quinn XCII", \
"Monday Mornin... | [
"def set_week_day(self, wday):\r\n\t\twdays = ['Domingo', 'Lunes', 'Martes', 'Miercoles',\r\n\t\t\t\t 'Jueves', 'Viernes', 'Sabado']\r\n\t\tfor i in range(7):\r\n\t\t\tif wday == i: \r\n\t\t\t\treturn wdays[i]",
"def say_day(self, *args):\n\n if self.layout.ids.week.collide_point(*args[1].pos): #pylint:dis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a song based on the day of the month | def get_monthday_song():
current_day = day_of_month()
print(f"MONTHDAY:{current_day}")
if (current_day == 1):
return random.choice([ \
"One of Us", \
"One - Harry Nilsson", \
"One More Night ", \
... | [
"def day_of_month():\n return datetime.date.today().day",
"def events_of_the_day(month: str, day: int):\n url = _generate_url(month, day)\n page = _get_page(url)\n raw_events = page.find_all(class_=\"event\")\n events = [event.text for event in raw_events]\n print(events)\n return events",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the xpath associated with the element tag as described in the elements file. | def get_element_xpath(self, element_tag):
try:
return self.__ui_data[element_tag]
except KeyError:
return None | [
"def _get_xpath(elem, root_xpath):\n if elem.classes._get_class_value():\n return '//%s[@class=\"%s\"]' % (elem.tag, elem.classes._get_class_value())\n else:\n return '%s/%s' % (root_xpath, str(elem.tag))",
"def get_xpath(el):\n ret = []\n parent = el.getparent()\n cur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creating a log transformed target matrix. | def _create_target_matrix(A, tranmat):
A = A.dot(tranmat)
# TODO: add lambda parameter to math.log
scores = np.log(A.data) - math.log(A.shape[0])
A.data[scores >= 0] = 0.
A.eliminate_zeros()
return A | [
"def log(self: Float[LinearOperator, \"*batch M N\"]) -> Float[LinearOperator, \"*batch M N\"]:\n return self.__class__(self._diag.log())",
"def transform_natural_log(self):\n data = self.values[\"X\"]\n self.values[\"X\"] = np.log(data)\n\n return self",
"def log(inputs):\n return torch.log(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns ``True`` if the proband is a reported male, ``False`` if reported female, and ``None`` if no sex is defined. | def is_male(self):
if self._is_female is None:
return None
return self._is_female is False | [
"def is_female(self):\n\n if self._is_female is None:\n return None\n\n return self._is_female is True",
"def is_female_gender(gender: Union[Gender, CommonGender, int]) -> bool:\n if gender is None:\n return False\n return int(gender) == int(Gender.FEMALE)",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns ``True`` if the proband is a reported female, ``False`` if reported male, and ``None`` if no sex is defined. | def is_female(self):
if self._is_female is None:
return None
return self._is_female is True | [
"def is_male(self):\n\n if self._is_female is None:\n return None\n\n return self._is_female is False",
"def is_female(sim_info: SimInfo) -> bool:\n return CommonGenderUtils.is_female_gender(CommonGenderUtils.get_gender(sim_info))",
"def is_female_gender(gender: Union[Gender, Com... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a PLINK .fam file and return a pedigree object. Examples >>> ped = hl.Pedigree.read('data/test.fam') Notes | def read(cls, fam_path, delimiter='\\s+') -> 'Pedigree':
trios = []
missing_sex_count = 0
missing_sex_values = set()
with Env.fs().open(fam_path) as file:
for line in file:
split_line = re.split(delimiter, line.strip())
num_fields = len(split_... | [
"def load_pedigree_file(\n pedigree_filename, pedigree_params=None) -> FamiliesData:\n if pedigree_params is None:\n pedigree_params = {}\n ped_df = FamiliesLoader.flexible_pedigree_read(\n pedigree_filename, **pedigree_params\n )\n return FamiliesLoader.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of trio objects in this pedigree. | def trios(self):
return self._trios | [
"def get_torpedo_lst(self):\r\n return self.__torpedo_lst",
"def get_trios(family):\n \n trios = []\n for x in family:\n mom = family.get_mother(x)\n dad = family.get_father(x)\n \n if mom is None and dad is None:\n continue\n \n # ignore people... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter the pedigree to a given list of sample IDs. Notes | def filter_to(self, samples):
sample_set = set(samples)
filtered_trios = []
for trio in self._trios:
restricted_trio = trio._restrict_to(sample_set)
if restricted_trio is not None:
filtered_trios.append(restricted_trio)
return Pedigree(filtered_t... | [
"def get_filtered_pedigree_with_samples(self):\n # TODO: unit test me\n return [x for x in self.pedigree if x[\"has_gt_entries\"]]",
"def filter_selected_ids(s, ids):\n nop = [s.particle[i] for i in ids]\n for p in nop:\n s.particle.remove(p)\n return s",
"def sample_ids(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a .fam file to the given path. Examples >>> ped = hl.Pedigree.read('data/test.fam') >>> ped.write('output/out.fam') Notes | def write(self, path):
lines = [t._to_fam_file_line() for t in self._trios]
with Env.fs().open(path, mode="w") as file:
for line in lines:
file.write(line + "\n") | [
"def gguf_write_to_file(ctx: ffi.CData, fname: ffi.CData, only_meta: bool) -> None:\n ...",
"def write(self, path):\n file_loader = infer_format(path)\n pref_path = f\"designer::{file_loader.name.lower()}\"\n pref.set_default(pref_path, {})\n with open(path, 'w') as dump:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
grab_dates parses through the data log and returns a pandas data frame containing all of the data for the days within start_date to stop_date. | def grab_dates(self, start_date, stop_date):
if isinstance(start_date, datetime.datetime):
start_date = start_date.date()
if isinstance(stop_date, datetime.datetime):
stop_date = stop_date.date()
if not self.quiet:
print(f'Grabbing data for dates '
... | [
"def get_dates(self):\n print(\"Prepare Date.\")\n src_conn = self.get_src_conn()\n cur = src_conn.cursor()\n sql = \"SELECT * FROM dbo.TradeDate WHERE exchange = 'sh'\"\n cur.execute(sql)\n arr = cur.fetchall()\n\n arr = np.array(arr)[:, :]\n days = pd.DataFr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
refresh_data parses through the data log returning a pandas data frame which contains all of the data from start_datetime.date() through the present moment. The Loader class keeps track of which data has previously been loaded by saving previously loaded data in self.data and keeping track of how many lines of data hav... | def refresh_data(self, start_datetime):
start_date = start_datetime.date()
stop_datetime = datetime.datetime.now()
stop_date = stop_datetime.date()
if not self.quiet:
print(f'Refreshing data from '
f'{start_datetime.strftime(self.datetime_format)} through '... | [
"def _load_data(self):\n data_file = self._get_data_file()\n tmp_file = data_file+'_temp'\n\n if os.path.isfile(data_file):\n df = pd.read_csv(data_file)\n df2 = df.iloc[[0, -1]]\n first_date = self._convert_date_str_to_datetime(df2.at[0,'date'])\n last_date = self._convert_date_str_to_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log the path, headers and body of the HTTP request on a key value store db, key is heroku request id. | def log_request(self, key, path, headers, body):
if not body:
body = {}
# Build a dict with key, headers and body.
now = datetime.datetime.now().isoformat()
data = {'request_id': key, 'body': body, 'path': path, 'created': now}
for k, v in headers.items():
... | [
"def log_request_info():\n app.logger.debug('Headers: %s', request.headers)\n app.logger.debug('Body: %s', request.get_data())",
"def log_request(task_request, request):\n msg = \"{0.method} {0.url}: {0.body}\".format(request)\n log_info(task_request, msg)",
"def really_log_r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searches for content items who use content items which are deprecated. | def find_items_using_deprecated_items(self, file_paths: List[str]) -> List[dict]:
with self.driver.session() as session:
return session.execute_read(get_items_using_deprecated, file_paths) | [
"def validate_deprecated_items_usage(self):\n is_valid = True\n new_files = GitUtil(repo=Content.git()).added_files()\n items: List[dict] = self.graph.find_items_using_deprecated_items(\n self.file_paths\n )\n for item in items:\n deprecated_command = item.ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searches and retrieves core packs who depends on content items who are not core packs. | def find_core_packs_depend_on_non_core_packs(
self,
pack_ids: List[str],
marketplace: MarketplaceVersions,
core_pack_list: List[str],
) -> List[BaseContent]:
with self.driver.session() as session:
results: Dict[str, Neo4jRelationshipResult] = session.execute_read(... | [
"def getMissingLangPacks(self):\n missing = []\n for langInfo in self._cache.getLanguageInformation():\n #print langInfo.languageCode\n trans_package = \"language-pack-%s\" % langInfo.languageCode\n # we have a langpack installed, see if we have all of them\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves all the packs that are dependent on hidden packs | def find_mandatory_hidden_packs_dependencies(
self, pack_ids: List[str]
) -> List[BaseContent]:
with self.driver.session() as session:
results = session.execute_read(validate_hidden_pack_dependencies, pack_ids)
self._add_nodes_to_mapping(result.node_from for result in results... | [
"def validate_hidden_packs_do_not_have_mandatory_dependencies(self):\n is_valid = True\n\n if dependant_packs := self.graph.find_mandatory_hidden_packs_dependencies(\n pack_ids=self.pack_ids\n ):\n hidden_pack_id_to_dependant_pack_ids: dict = defaultdict(set)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a anonymized url. Updates the dictionary inplace if a new ip is encountered | def _anonymize_url(url: str, ip_dict: Dict[str, int]) -> str:
regex_match = re.match(r"(?i)(^https?://)(.*?)([/:].*$)", url)
ip = regex_match.group(2)
try:
num = ip_dict[ip]
except KeyError:
ip_dict[ip] = len(ip_dict.values()) + 1
num = ip_dict[ip]
return f"{regex_match.gro... | [
"def _find_anonymized_match(self, request):\n request.url = _anonymize_url(request.url, ip_lookup)\n return _BASE_FIND_MATCH(self, request)",
"def anonymize_url(url: str, remove_username: bool = False) -> str:\n parse = urlsplit(url)\n if remove_username and parse.username is not None:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a file path for API response logs for a given test and test parameters | def _build_response_log_path(
*, test_func: Callable, response_logs_dir: Optional[Union[str, Path]], **kwargs,
) -> Path:
# Convert test arguments and their values to a string, skipping ignored arguments
test_params = "_".join([f"{k}={v}" for k, v in {**kwargs}.items()])
# Remove reserved characters fro... | [
"def tcex_log_file(self):\n try:\n test_data = os.getenv('PYTEST_CURRENT_TEST').split(' ')[0].split('::')\n test_feature = test_data[0].split('/')[1].replace('/', '-')\n test_name = test_data[-1].replace('/', '-').replace('[', '-')\n except AttributeError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allows responses library to match requests for an ip address to match to an anonymized ip address | def _find_anonymized_match(self, request):
request.url = _anonymize_url(request.url, ip_lookup)
return _BASE_FIND_MATCH(self, request) | [
"def match_api_keys(key, ip):",
"def _analyze_ips(self, ip_address_list, fuzzable_request):\n bing_wrapper = bing(self._uri_opener)\n \n # This is the best way to search, one by one!\n for ip_address in ip_address_list:\n results = bing_wrapper.get_n_results('ip:' + ip_addre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs a test function against a Tamr instance and saves the API responses to a file | def _run_online_test(response_log_path: Path, test_function: Callable, **kwargs) -> None:
LOGGER.info(
f"Online test running against Tamr instance. "
f"Creating new file at {response_log_path}. This may take a while ..."
)
os.makedirs(response_log_path.parent, exist_ok=Tr... | [
"def run_test(test_data_instance):\n if not test_data_instance.waiting_to_run:\n return\n script = 'python' if sys.platform == \"win32\" else 'python3'\n solution_file = os.path.join(settings.BASE_DIR, settings.MEDIA_ROOT,\n str(test_data_instance.solution.file))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs the response from BASE_SEND_REAL | def _send_real_with_log(*args, **kwargs) -> Response:
response = _BASE_SEND_REAL(*args, **kwargs)
# Prevent recursion
with mock.patch("responses._real_send", new=_BASE_SEND_REAL):
_log_response(log_path=response_log_path, response=response, ip_dict=ip_lookup)
... | [
"def log_response(response):\n logging.debug(\"URL: %s\", str(response.url))\n logging.debug(\"Status Code: %s\", str(response.status_code))\n logging.debug(\"Response: %s\", response.text if response.text else 'Empty')\n logging.debug(\"Json: %s\", response.json() if response.json() else 'Empty')",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find largest streak of largest element | def problem_a(n, a):
largest = max(a)
i = 0
old_streak_begin = 0
old_streak_end = 0
while i < n:
if a[i] == largest:
streak_begin = i
while i < n and a[i] == largest:
i += 1
streak_end = i - 1
i -= 1 # adjust index ba... | [
"def longest_streak(tracker_data):\n max_streak = 0\n streak = 0\n streak_start = None\n streak_end = None\n current_start = None\n last_day = None\n for entry in tracker_data:\n entry_day = str_to_date(entry[1])\n next_day = (entry_day - timedelta(days=1))\n if last_day ==... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes as input a tuple that represents a color in HSV format, and optionally a scale factor. Return an RGB string that is the converted HSV color, scaled by the given factor. | def scale_color((h, s, v), factor=1.):
if (h < 0.) or (h > 360.):
raise Exception('[scale_color()] Hue value out of range (0, 360): ' + str(h))
if (s < 0.) or (s > 100.):
raise Exception('[scale_color()] Saturation value out of range (0, 100): ' + str(s))
if (v < 0.) or (v > 100.):
... | [
"def hsv(h, s, v):\n return Color(\"hsv\", h, s, v)",
"def hsv2rgb(h, s, v):\n s = clamp(s)\n v = clamp(v)\n\n r, g, b = hsv_to_rgb(h % 1, s, v)\n return (\n int(r * 255),\n int(g * 255),\n int(b * 255),\n )",
"def hsv_2_rgb(h, s, v):\n h = float(h) / 359.0\n s = flo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort by the abundance level all the taxonomy that represent at least two levels. Return the first ``xxx`` most abundant. | def get_most_abundant(abundances, xxx):
abundant = []
for a in abundances:
if a.count('|') > 0:
abundant.append((float(abundances[a]), a.replace('|', '.')))
elif a.count('.') > 0:
abundant.append((float(abundances[a]), a))
abundant.sort(reverse=True)
return abun... | [
"def test_make_most_abundant(self):\r\n ids = \\\r\n \"R27DLI_4812 R27DLI_600 R27DLI_727 U1PLI_403 U1PLI_8969\".split(\r\n )\r\n seqs = dict(parse_fasta(dna_seqs.splitlines(),\r\n label_to_name=label_to_name))\r\n f = make_most_abu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the value of ``abu`` scaled to ``max_abu`` logarithmically, and then map from ``minn`` to ``maxx``. | def scale_clade_size(minn, maxx, abu, max_abu):
return minn + maxx * log10(1. + 9. * (abu/max_abu)) | [
"def u_max(self):\n if self._u_max is None:\n return self.uv_max\n else:\n return self._u_max",
"def normalize(a, newmax):\n return (float(newmax) * a) / np.amax(a)",
"def maximum(self,va):\n vmax = 1.0e-10 # need to change\n for v in va:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter a distribution of logits using topk and/or nucleus (topp) filtering | def top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):
if logits.dim() == 2:
logits = torch.stack([top_k_top_p_filtering(p, top_k, top_p) for p in logits])
# print(logits.shape)
return logits
assert logits.dim() == 1 # batch size 1 for now - could be updated... | [
"def top_k_top_p_filtering(self, logits, filter_value=-float('Inf')):\n top_k = min(self.top_k, logits.size(-1)) # Safety check\n if top_k > 0:\n # Remove all tokens with a probability less than the last token of the top-k\n indices_to_remove = logits < torch.topk(logits, top_k)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Negation. >>> M=mat4(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) >>> print M [ 1.0000, 2.0000, 3.0000, 4.0000] [ 5.0000, 6.0000, 7.0000, 8.0000] [ 9.0000, 10.0000, 11.0000, 12.0000] [ 13.0000, 14.0000, 15.0000, 16.0000] | def __neg__(self):
return mat4(map(lambda x: -x, self.mlist)) | [
"def negate(matrix):\r\n for rowVectors in matrix._matrix:\r\n for i in range(len(rowVectors)):\r\n rowVectors[i] = (-1) * float(rowVectors[i])",
"def inverse(self):\r\n \r\n Mi=mat4()\r\n d=self.determinant()\r\n for i in range(4):\r\n for j in range(4)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list containing the matrix elements. By default the list is in columnmajor order (which can directly be used in OpenGL or RenderMan). If you set the optional argument rowmajor to 1, you'll get the list in rowmajor order. >>> M=mat4(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) >>> print M.toList() [1, 5, 9, 13, 2, 6... | def toList(self, rowmajor=0):
if rowmajor:
return copy.copy(self.mlist)
else:
return self.transpose().mlist | [
"def tolist(self):\n ret = [0]*self.rows\n for i in xrange(self.rows):\n ret[i] = self.mat[i*self.cols:(i+1)*self.cols]\n return ret",
"def toList(self):\n\n return self.matrix.matrixToList()",
"def as_list_of_lists(self):\n return self._matrix_data",
"def matrix2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return identity matrix. >>> print mat4().identity() [ 1.0000, 0.0000, 0.0000, 0.0000] [ 0.0000, 1.0000, 0.0000, 0.0000] [ 0.0000, 0.0000, 1.0000, 0.0000] [ 0.0000, 0.0000, 0.0000, 1.0000] | def identity(self):
return mat4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0) | [
"def identity_matrix():\r\n return numpy.identity(4)",
"def identity_matrix():\n return numpy.identity(4)",
"def identity(self):\r\n return mat3(1.0, 0.0, 0.0,\r\n 0.0, 1.0, 0.0,\r\n 0.0, 0.0, 1.0)",
"def IdentityMatrix():\n return RotationMatrix([\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transpose matrix. >>> M=mat4(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) >>> print M.transpose() [ 1.0000, 5.0000, 9.0000, 13.0000] [ 2.0000, 6.0000, 10.0000, 14.0000] [ 3.0000, 7.0000, 11.0000, 15.0000] [ 4.0000, 8.0000, 12.0000, 16.0000] | def transpose(self):
m11,m12,m13,m14,m21,m22,m23,m24,m31,m32,m33,m34,m41,m42,m43,m44 = self.mlist
return mat4(m11,m21,m31,m41,
m12,m22,m32,m42,
m13,m23,m33,m43,
m14,m24,m34,m44) | [
"def transpose(self): \r\n m, n = self.n, self.m\r\n mat = Matrix(m,n)\r\n mat.rows = [list(item) for item in zip(*self.rows)]\r\n return mat",
"def matrix_transpose(matrix):\n pass",
"def transpose(self):\n self.matrix = self.matrix.transpose()",
"def transpose(m):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return inverse matrix. >>> M=mat4(0,2.0,0,0, 2.0,0,0,0, 0,0,2,0, 0,0,0,2) >>> print M.inverse() [ 0.0000, 0.5000, 0.0000, 0.0000] [ 0.5000, 0.0000, 0.0000, 0.0000] [ 0.0000, 0.0000, 0.5000, 0.0000] [ 0.0000, 0.0000, 0.0000, 0.5000] | def inverse(self):
Mi=mat4()
d=self.determinant()
for i in range(4):
for j in range(4):
sign=1-((i+j)%2)*2
m3=self._submat(i,j)
Mi[j,i]=sign*m3.determinant()/d
return Mi | [
"def mat4_inverse(matrix):\n return np.linalg.inv(matrix)",
"def getInverseMatrix(self) -> CMatrix4:\n ...",
"def inverse(mat): # pylint: disable=R1710\n return mat.inverse()",
"def inverse(self):\n\t\tif not self.is_square():\n\t\t\traise(ValueError, \"Non-square Matrix does not have an inverse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
equivalent to the OpenGL command glFrustum() | def frustum(self, left, right, bottom, top, near, far):
return mat4( (2.0*near)/(right-left), 0.0, float(right+left)/(right-left), 0.0,
0.0, (2.0*near)/(top-bottom), float(top+bottom)/(top-bottom), 0.0,
0.0, 0.0, -float(far+near)/(far-near), -(2.0*far*near)... | [
"def visible( self, frust, matrix=None, occlusion=0, mode=None ):\n if matrix is None:\n matrix = frustum.viewingMatrix( )\n points = self.getPoints()\n points = dot( points, matrix )\n points[:,-1] = 1.0\n if frust:\n for plane in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Look from pos to target. The resulting transformation moves the origin to pos and rotates so that The zaxis points to target. The yaxis is as close as possible to the up vector. | def lookAt(self, pos, target, up=_vec3(0,0,1)):
dir = (target - pos).normalize()
up = up.normalize()
up -= (up * dir) * dir
try:
up = up.normalize()
except:
# We're looking along the up direction, so choose
# an arbitrary direction th... | [
"def move_to_origin(self) -> None:\n\n _bb = self.bb()\n if _bb.x < 0:\n self.translate(abs(_bb.x), 0.0)\n else:\n self.translate(-abs(_bb.x), 0.0)\n\n if _bb.y < 0:\n self.translate(0.0, abs(_bb.y))\n else:\n self.translate(0.0, -abs(_b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decomposes the matrix into a translation, rotation and scaling part. Returns a tuple (translation, rotation, scaling). The translation and scaling parts are given as vec3's, the rotation is still given as a mat4. | def decompose(self):
dummy = self.ortho()
dummy.setRow(3,_vec4(0.0, 0.0, 0.0, 1.0))
x = dummy.getColumn(0)
y = dummy.getColumn(1)
z = dummy.getColumn(2)
xl = x.length()
yl = y.length()
zl = z.length()
scale = _vec3(xl,yl,zl)
... | [
"def decompose_transformation_matrix(\n matrix: numpy.ndarray,\n) -> Tuple[\n Tuple[float, float, float], Tuple[float, float, float], Tuple[float, float, float]\n]:\n assert isinstance(matrix, numpy.ndarray), \"Matrix must be an ndarray\"\n assert matrix.shape == (4, 4), \"Expected a 4x4 numpy array\"\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert to mat3 by discarding 4th row and column. | def getMat3(self):
m11,m12,m13,m14,m21,m22,m23,m24,m31,m32,m33,m34,m41,m42,m43,m44 = self.mlist
return _mat3(m11,m12,m13,
m21,m22,m23,
m31,m32,m33) | [
"def _mat3(self):\n if self.frame.orientation == HillFrame.DEFAULT_ORIENTATION:\n return np.identity(3)\n else:\n return self.QSW2TNW",
"def toMatrix33(self):\n\n mat3 = Matrix33()\n\n xx = self.v.x * self.v.x\n xy = self.v.x * self.v.y\n xz = self.v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds several channels to the NIDAQ Task object. | def add_channels(self, channels):
for i in range(len(channels)):
self.task.ai_channels.add_ai_voltage_chan(channels[i]) | [
"def add(self, channels):\n self._channels.add(channels)",
"def channels(self, channels):\n self._client.set_job_channels(self.id, channels)",
"def addchan(channel):",
"def add_global_channels(self, global_channels):\r\n cfunc = lib_importer.windll.DAQmxAddGlobalChansToTask\r\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is added as a testing helper, not actually as part of the parser tests. Since the same particles will be used for the driver test it is helpful to write them to .yml in the same form they need in the results.yml files here. | def particle_to_yml(self, particle):
particle_dict = particle.generate_dict()
# open write append, if you want to start from scratch manually delete this file
fid = open('particle.yml', 'a')
fid.write(' - _index: 0\n')
fid.write(' internal_timestamp: %f\n' % particle_dict.get... | [
"def particle_to_yml(self, particles, filename, mode='w'):\n # open write append, if you want to start from scratch manually delete this fid\n fid = open(os.path.join(RESOURCE_PATH, filename), mode)\n\n fid.write('header:\\n')\n fid.write(\" particle_object: 'MULTIPLE'\\n\")\n fid... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test changing to a new state after initializing the parser and reading data, as if new data has been found and the state has changed | def test_set_state(self):
self.stream_handle = open(os.path.join(RESOURCE_PATH, 'adcpt_20130929_091817.DAT'))
self.parser = AdcpsJlnStcParser(self.config, self.start_state, self.stream_handle,
self.state_callback, self.pub_callback, self.exception_callback)
... | [
"def test_set_state(self):\r\n\r\n # Using the default mspack test file.\r\n file_path = os.path.join(RESOURCE_PATH, 'state_test.mpk')\r\n stream_handle = open(file_path, 'rb')\r\n\r\n # Moving the file position to the end of the first chunk\r\n state = {StateKey.PARTICLES_RETURNE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure that bad data is skipped when it exists. | def test_bad_data(self):
# Bad checksum
# If checksum is bad, skip the record and continue parsing.
self.stream_handle = StringIO(AdcpsJlnStcParserUnitTestCase.BAD_CHECKSUM)
self.parser = AdcpsJlnStcParser(self.config, self.start_state, self.stream_handle,
... | [
"def test_separate_good_bad_data(self):\n self.c = CmdFunction()\n self.c.processor.validator.set_raw_data([\"T109,M,74,861,-,22\"])\n self.c.processor.validator.parse_data()\n self.c.processor.database.add_people(self.c.processor.validator.export_good_data())\n self.assertTrue(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes the hidden and memory cell with given batch size. | def init_hidden(self, batch_size, use_cuda=False):
# The axes semantics are (num_layers, minibatch_size, hidden_dim)
# The tuple reprensents hidden cell and memory cell.
hidden = [
autograd.Variable(
torch.zeros(self.n_layers, batch_size, self.hidden_dim),
... | [
"def initHidden(self, batch_size):\n zero_hidden = torch.zeros(self.n_layers, batch_size, self.hidden_size)\n return zero_hidden",
"def reset(self, batch_size: Optional[int] = 1):\n self.hidden = self.get_hidden(batch_size)",
"def init_batch(self):\n pass",
"def set_cell_state(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use this decorator to have another method run for dealing with validation errors. For example, you have a method '/new' which features a form and a method '/create' which actually processes its data (after an POST request). The latter has validators set and thus yields an exception if they fail. By having set for '/new... | def error_handler(call_on_errors):
assert callable(call_on_errors)
def entangle(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
try:
return method(self, *args, **kwargs)
except InputInvalidException:
return call_on_err... | [
"def handler(method):\n @wraps(method)\n def wrapped(self, *args, **kwargs):\n if not self.check_headers():\n return responses.client_error(400, 'Wrong format request')\n else:\n return method(self, *args, **kwargs)\n return wrapped",
"def form_invalid(self, *args, **k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensures both operands of a binary operation are safe (int limit). | def _check_binop_operands(self, a, b):
if isinstance(a, int) and (a < self._config.min_int or a > self._config.max_int):
_raise_in_context(NumberTooHigh, "This number is too large")
if isinstance(b, int) and (b < self._config.min_int or b > self._config.max_int):
_raise_in_contex... | [
"def apply_binaryop(binop, lhs, rhs, out):\n args = (lhs._cffi_view, rhs._cffi_view, out._cffi_view)\n # apply binary operator\n binop(*args)\n # validity mask\n if out.has_null_mask:\n return apply_mask_and(lhs, rhs, out)\n else:\n return 0",
"def _binaryop(self, other, op: str):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Like zip(a, b), but zips the element at ``a[star_index]`` with a list of 0..len(b) elements such that every other element of ``a`` maps to exactly one element of ``b``. >>> zip_star(['a', 'b', 'c'], [1, 2, 3, 4], star_index=1) like a, b, c = [1, 2, 3, 4] [('a', 1), ('b', [2, 3]), ('c', 4)] >>> zip_star(['a', 'b', 'c'],... | def zip_star(a: Sequence, b: Sequence, star_index: int):
if not 0 <= star_index < len(a):
raise IndexError("'star_index' must be a valid index of 'a'")
if not len(b) >= len(a) - 1:
raise ValueError("'b' must be no more than 1 shorter than 'a'")
length_difference = len(b) - (len(a) - 1)
... | [
"def forward_star(self, node_index):\r\n return self.__star(node_index, link_inner_index=0)",
"def zip_iterables():\n from sys import version_info as python_version\n a_list = [0, 1, 2, 3]\n b_list = [\"a\", \"b\", \"c\", \"d\"]\n zipper = zip(a_list, b_list)\n if python_version >= (3,):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalize featurex in x Uses convolution operator | def normalize_conv(self, x):
x = self.normalize_global(x)
if self.right_context is None and self.left_context is None:
return x
if self.left_context is None:
left_context = x.shape[0]
else:
left_context = self.left_context
if self.r... | [
"def featureNormalize(X):\n \n X_norm = X.copy()\n mu = np.zeros(X.shape[1])\n sigma = np.zeros(X.shape[1])\n \n mu = np.mean(X, axis=0)\n sigma = np.std(X, axis=0)\n X_norm = (X_norm-mu)/sigma\n \n return X_norm",
"def featureNormalize(X):\n mu = np.mean(X)\n sigma = np.std(X)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalize featurex in x Uses cumsum | def normalize_cumsum(self, x):
x = self.normalize_global(x)
if self.right_context is None and self.left_context is None:
return x
if self.left_context is None:
left_context = x.shape[0]
else:
left_context = self.left_context
if self.right_c... | [
"def normalize(x):\n sumx = sum(x)\n y = []\n for xi in x:\n xi = xi*(1./sumx)\n y.append(xi)\n return y",
"def featureNormalize(X):\n \n X_norm = X.copy()\n mu = np.zeros(X.shape[1])\n sigma = np.zeros(X.shape[1])\n \n mu = np.mean(X, axis=0)\n sigma = np.std(X, ax... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the version attribute from an HDF5 file dataset | def get_version(self, dataset_name=None):
if dataset_name is None:
return self._version
else:
# resolve dataset name
dataset = self.__getitem__(dataset_name)
try:
# dataset can be either an HDF5 dataset or numpy.ndarray
vers... | [
"def _get_version(name):\n from mne.datasets._fetch import fetch_dataset\n\n if not has_dataset(name):\n return None\n dataset_params = MNE_DATASETS[name]\n dataset_params[\"dataset_name\"] = name\n config_key = MNE_DATASETS[name][\"config_key\"]\n\n # get download path for specific dataset... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the version attribute from an HDF5 file dataset Provide a portable way to set the global schema version or the version of a specific dataset. | def set_version(self, version, dataset_name=None):
if dataset_name is None:
self._version = version
return self._version
# resolve dataset name
dataset = self.__getitem__(dataset_name)
if dataset is None:
raise KeyError("Dataset %s does not exist" % d... | [
"def update_dataset_version(): \n global args\n \n logger.info('Updating CKAN dataset version')\n \n # Initialize CKAN client\n ckan = ckanclient.CkanClient(base_location=args.ckan_api,api_key=args.ckan_api_key)\n \n # Create the name of the dataset on the CKAN instance\n dataset_id = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the column names of an h5lmt dataset | def _get_columns_h5lmt(self, dataset_name):
dataset = self.__getitem__(dataset_name)
orig_dataset_name = dataset_name.lstrip('/')
dataset_name = dataset.name.lstrip('/')
if dataset_name == 'MDSOpsGroup/MDSOpsDataSet' and orig_dataset_name != dataset_name:
return numpy.array([... | [
"def dataset_headers(dataset):\n return list(dataset.columns.values)",
"def column_names(self):\n return self.data.columns.values",
"def get_grid_names(fname):\r\n with h5py.File(fname, 'r') as f:\r\n vnames = [k for k in f.keys() if f[k].ndim == 2]\r\n return vnames",
"def printAllColu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cache or calculate the timestep for a dataset | def get_timestep(self, dataset_name, timestamps=None):
if dataset_name not in self._timesteps:
if timestamps is None:
timestamps = self.get_timestamps(dataset_name)[0:2]
self._timesteps[dataset_name] = timestamps[1] - timestamps[0]
return self._timesteps[dataset_n... | [
"def method_compute_timestep(self):",
"def compute_time_step():\n\n dt = Hydro.compute_time_step()\n\n return dt",
"def time_step():\n return TimeStep()",
"def timestep(self):\n return NotImplementedError",
"def _compute_time_inside_step(self, metric_timeline, step_time_list):\n per_step_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return timestamps dataset corresponding to given dataset name This method returns a dataset, not a numpy array, so you can face severe performance penalties trying to iterate directly on the return value! To iterate over timestamps, it is almost always better to dereference the dataset to get a numpy array and iterate ... | def get_timestamps(self, dataset_name):
return get_timestamps(self, dataset_name) | [
"def get_timestamps(hdf5_file, dataset_name):\n return hdf5_file[get_timestamps_key(hdf5_file, dataset_name)]",
"def to_timeseries(self, dataset_name, light=False):\n timeseries = tokio.timeseries.TimeSeries()\n timeseries.dataset_name = dataset_name\n\n try:\n dataset = self[da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the FSMissingGroup dataset from an H5LMT file Encodes a hot mess of hacks to return something that looks like what `get_missing()` would return for a real dataset. | def _get_missing_h5lmt(self, dataset_name, inverse=False):
dataset = self.__getitem__(dataset_name)
missing_dataset = self.get('/FSMissingGroup/FSMissingDataSet')
if len(dataset.shape) == 1:
result = numpy.zeros((dataset.shape[0], 1), dtype=numpy.int8)
elif dataset.shape == m... | [
"def test_extract_metadata_with_hdu_span_no_spanext(self):\n modelfile = resource_filename('desidatamodel.test', 't/fits_file_hduspan_no_spanext.rst')\n model = DataModel(modelfile, os.path.dirname(modelfile))\n with self.assertRaises(DataModelError) as e:\n meta = model.extract_meta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a dataset into a dataframe via H5LMT native schema | def _to_dataframe_h5lmt(self, dataset_name):
normed_name, modifier = reduce_dataset_name(dataset_name)
if not modifier:
normed_name = dataset_name.lstrip('/')
else:
normed_name = normed_name.lstrip('/')
col_header_key = H5LMT_COLUMN_ATTRS.get(normed_name)
... | [
"def h5ToDf(filename):\n log.info(f\"Import data from: {filename}\")\n with h5py.File(filename, \"r\") as hf :\n d = {}\n for name in list(hf.keys()):\n d[name] = np.array(hf[name][:])\n df = pd.DataFrame(data=d)\n return(df)",
"def h5_to_df(h5_file, group_name):\n col_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a TimeSeries representation of a dataset Create a TimeSeries dataset object with the data from an existing HDF5 dataset. Responsible for setting timeseries.dataset_name, timeseries.columns, timeseries.dataset, timeseries.dataset_metadata, timeseries.group_metadata, timeseries.timestamp_key | def to_timeseries(self, dataset_name, light=False):
timeseries = tokio.timeseries.TimeSeries()
timeseries.dataset_name = dataset_name
try:
dataset = self[dataset_name]
except KeyError:
# can't attach because dataset doesn't exist; pass this back to caller so it c... | [
"def init_datasets(self, dataset_names, columns):\n for dataset_name in dataset_names:\n hdf5_dataset_name = self.schema.get(dataset_name)\n if hdf5_dataset_name is None:\n warnings.warn(\"Skipping %s (not in schema)\" % dataset_name)\n else:\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given new timestamps and an existing series of timestamps, find the indices overlap so that new data can be inserted into the middle of an existing dataset | def get_insert_indices(my_timestamps, existing_timestamps):
existing_timestep = existing_timestamps[1] - existing_timestamps[0]
my_timestep = my_timestamps[1] - my_timestamps[0]
# make sure the time delta is ok
if existing_timestep != my_timestep:
raise Exception("Existing dataset has different... | [
"def matching_time_indices(stamps_1, stamps_2, max_diff=0.01, offset_2=0.0):\n matching_indices = []\n stamps_2 = copy.deepcopy(stamps_2)\n stamps_2 += offset_2\n for stamp in stamps_1:\n diffs = np.abs(stamps_2 - stamp)\n argmin = np.argmin(diffs)\n if diffs[argmin] <= max_diff:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates new tile (either 2 or 4) in empty tile (val=0) returns True if there are no empty tiles, returns False | def genNewTile(self):
# Find which tiles are empty
emptyList = []
for i in range(4):
for j in range(4):
tileKey = 4*i + j
if self.isTileEmpty(i, j):
emptyList.append(tileKey)
# If there's no empty tiles, return false
... | [
"def new_tile(self):\n two_or_four = random.random();\n if two_or_four < 0.9:\n value = 2\n else:\n value = 4\n empty = False\n all_cells = 0\n while empty == False:\n all_cells += 1 \n row = random.choice(range(self._height))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Slides tile[i,j] in given direction until it hits another tile or the wall if it hits another tile theat's the same, they combine. | def slideTile(self, i, j, direct):
tile = self.getTile(i,j)
if direct==Move.UP: # if the direction is up
iRange = list(range(i - 1, -1, -1)) # list the squares above i,j
jRange = [j]*len(iRange) # in iRange,jRange
elif direct==Move.DO... | [
"def move(self, direction):\r\n way = OFFSETS[direction]\r\n my_tiles = self._initial_tiles[direction]\r\n changed = False\r\n for list_starts in my_tiles:\r\n curr_idx = list(list_starts)\r\n curr_list = []\r\n within_height = True\r\n within_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate_mil_hdbk_217f_part_count() should return an error message when the subcategory ID is missing. | def test_calculate_mil_hdbk_217f_part_count_missing_subcategory():
ATTRIBUTES['subcategory_id'] = 0
ATTRIBUTES['type_id'] = 1
ATTRIBUTES['quality_id'] = 1
_attributes, _msg = Connection.calculate_217f_part_count(**ATTRIBUTES)
assert isinstance(_attributes, dict)
assert _msg == ('RAMSTK WARNING... | [
"def test_calculate_mil_hdbk_217f_part_count_missing_subcategory():\n ATTRIBUTES['subcategory_id'] = 0\n ATTRIBUTES['quality_id'] = 1\n ATTRIBUTES['family_id'] = 1\n ATTRIBUTES['type_id'] = 1\n ATTRIBUTES['environment_active_id'] = 1\n\n _attributes, _msg = Relay.calculate_217f_part_count(**ATTRIB... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate_mil_hdbk_217f_part_count() should return an error message when the type ID is missing and needed. | def test_calculate_mil_hdbk_217f_part_count_missing_type():
ATTRIBUTES['subcategory_id'] = 1
ATTRIBUTES['type_id'] = 0
ATTRIBUTES['quality_id'] = 1
_attributes, _msg = Connection.calculate_217f_part_count(**ATTRIBUTES)
assert isinstance(_attributes, dict)
assert _msg == ('RAMSTK WARNING: Base ... | [
"def test_calculate_mil_hdbk_217f_part_count_missing_type():\n ATTRIBUTES['subcategory_id'] = 1\n ATTRIBUTES['quality_id'] = 1\n ATTRIBUTES['type_id'] = 10\n ATTRIBUTES['quality_id'] = 1\n ATTRIBUTES['environment_active_id'] = 1\n\n _attributes, _msg = Relay.calculate_217f_part_count(**ATTRIBUTES)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate_mil_hdbk_217f_part_count() should return an error message when the active environment ID is missing. | def test_calculate_mil_hdbk_217f_part_count_missing_environment():
ATTRIBUTES['subcategory_id'] = 1
ATTRIBUTES['type_id'] = 1
ATTRIBUTES['environment_active_id'] = 100
ATTRIBUTES['quality_id'] = 1
_attributes, _msg = Connection.calculate_217f_part_count(**ATTRIBUTES)
assert isinstance(_attribu... | [
"def test_calculate_mil_hdbk_217f_part_count_missing_environment():\n ATTRIBUTES['subcategory_id'] = 1\n ATTRIBUTES['quality_id'] = 1\n ATTRIBUTES['type_id'] = 1\n ATTRIBUTES['environment_active_id'] = 100\n ATTRIBUTES['quality_id'] = 1\n\n _attributes, _msg = Relay.calculate_217f_part_count(**ATT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate_mil_hdbk_217f_part_stress() should return a dictionary of updated values on success. | def test_calculate_mil_hdbk_217f_part_stress():
ATTRIBUTES['hazard_rate_method_id'] = 2
ATTRIBUTES['environment_active_id'] = 3
ATTRIBUTES['subcategory_id'] = 1
ATTRIBUTES['type_id'] = 1
ATTRIBUTES['specification_id'] = 1
ATTRIBUTES['temperature_active'] = 32.0
ATTRIBUTES['quality_id'] = 2
... | [
"def calculate_217f_part_stress(**attributes): # pylint: disable=R0912, R0914\n _dic_ref_temp = {\n 1: 343.0,\n 2: {\n 1: 343.0,\n 2: 343.0,\n 3: 398.0,\n 4: 398.0\n },\n 3: 298.0,\n 5: 398.0,\n 6: 298.0,\n 7: 298.0,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the calculate_insert_temperature() function. | def test_calculate_insert_temperature():
ATTRIBUTES['subcategory_id'] = 1
ATTRIBUTES['current_operating'] = 2.65
ATTRIBUTES['contact_gauge'] = 20
_attributes = Connection.do_calculate_insert_temperature(**ATTRIBUTES)
assert isinstance(_attributes, dict)
assert pytest.approx(_attributes['temper... | [
"def test_store_temperature(self):\n timestamp = datetime.datetime(\n 2016, 7, 23, 10, 51, 9, 928000, tzinfo=pytz.utc)\n temperature = 21.1\n mock_cursor = mock.Mock()\n store = db_store.TemperatureStore(mock_cursor)\n store.store_temperature(timestamp, temperature)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
overstressed() should return True when active temperature is within 10C of rated temperature in a harsh environment and False otherwise. | def test_temperature_overstress_harsh_environment(temperature_active,
environment_active_id):
ATTRIBUTES['voltage_rated'] = 40.0
ATTRIBUTES['voltage_ac_operating'] = 0.005
ATTRIBUTES['voltage_dc_operating'] = 10.0
ATTRIBUTES['temperature_rated_max'] = 12... | [
"def is_high_temp(self):\n status = self.get_status_response()\n return ((status[1] & 0x20) == 0x20)\n #end is_power_limited()",
"def is_heating(self) -> bool:\r\n self._logger.debug(log_message_formatter(\r\n \"get\", f\"{self}\", \"is_heating\"))\r\n return (self._a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Quick Select algorithm This is basically a modified quicksort algorithm to find kth largest/smallest element. | def quick_select(arr: list, k: int) -> int:
start, end = 0, len(arr) - 1
while start <= end:
pivot = randint(start, end)
arr[pivot], arr[end] = arr[end], arr[pivot] # important in case of random pivot
pivot = end
i, j = start - 1, start
while j < end:
if ar... | [
"def select(dataset, k):\n limit = len(dataset)\n if k > limit:\n raise IndexError(\"k should always be leq len(dataset)\")\n original_limit = limit\n \n partition_start = 0\n partition_limit = len(dataset)\n partition_index = -1\n start = 0\n print(\"Virgin: \" + str(dataset))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Preprocess the raw iris data. | def preprocess_iris(self):
print('[ INFO ]: Preprocessing iris data...')
# Rename headers of data frame
iris_data = pd.read_csv(self.iris_path, header=None)
iris_data.columns = ['sepal_length','sepal_width','petal_length','petal_width', 'iris_class']
df_columns = [iris_data.co... | [
"def data_preprocess(self):\n pass",
"def preprocess(self, dataset: Dataset) -> Dataset:\n\n # Dataset preprocessing\n dataset = dataset.map(self._add_eos)\n dataset = dataset.map(self._to_features, batched=True)\n\n return dataset",
"def preprocess(self, preproc):\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute the program runner over the iris dataset. | def iris_runner(self):
print('[ INFO ]: Initializing the iris program runner...')
data, features, classes = self.preprocess_iris()
iris = alg()
selected_features, selected_clusters, basePerformance = iris.stepwise_forward_selection(data, features, len(classes))
return selected... | [
"def iris():\n print(\"Iris.exe - generate code and mask for every image\")\n iris_arg = []\n iris_results = []\n for image in imagesCompare:\n iris_arg.append([irisExePath, databaseCompare, image])\n\n if multithreading:\n p = Pool(processes=threads)\n iris_results = p.map(run_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
process pred data for voc | def voc_pred_process(pred_data, val_cls, recs):
num_classes = config.num_classes
cls_img_ids = {}
cls_bboxes = {}
cls_scores = {}
classes = {}
cls_npos = {}
for cls in val_cls:
if cls == 'background':
continue
class_recs = {}
npos = 0
for imagename... | [
"def _preprocess(self):\n self.data['sentences'] = self.data['text'].apply(self._tokenize_sent)\n self.data['nouns'] = self.data['sentences'].apply(self._get_nouns)\n # self._get_frequent_features()\n # self._compactness_pruning()\n # self._redundancy_pruning()\n # self._ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetches an image from the webcam | def get_from_webcam(self):
print "try fetch from webcam..."
stream=urllib.urlopen('http://192.168.0.20/image/jpeg.cgi')
bytes=''
bytes+=stream.read(64500)
a = bytes.find('\xff\xd8')
b = bytes.find('\xff\xd9')
if a != -1 and b != -1:
jpg = bytes[a:b+2]... | [
"def get_from_webcam():\n print \"try fetch from webcam...\"\n stream=urllib.urlopen('http://192.168.0.20/image/jpeg.cgi')\n bytes=''\n bytes+=stream.read(64500)\n a = bytes.find('\\xff\\xd8')\n b = bytes.find('\\xff\\xd9')\n\n if a != -1 and b != -1:\n jpg = bytes[a:b+2]\n bytes=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For each contour in contours approximate the contours such that small variations are removed calulate the area of the contour if the area is within the desired range we append the box points to the bricks. | def get_bricks(self, contours):
bricks = []
for cnt in contours:
epsilon = 0.04*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
if len(approx) >= 4:
rect = cv2.minAreaRect(approx)
area = cv2.contourArea... | [
"def __bound_contours(roi):\n\n roi_copy = roi.copy()\n roi_hsv = cv2.cvtColor(roi, cv2.COLOR_RGB2HSV)\n # filter black color\n mask1 = cv2.inRange(roi_hsv, np.array([0, 0, 0]), np.array([180, 255, 125]))\n mask1 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract the contours of the image by first converting it to grayscale and then call findContours | def contours(self, image,debug=False):
imgray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
if debug: cv2.imwrite('debug_pics/gray_scale_contour.jpg',imgray) # cv2.imshow('gray_scale_contour',imgray)
im2, contours, hierarchy = cv2.findContours(imgray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
re... | [
"def detect_contours(self):\r\n (contours, _) = cv2.findContours(self.image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n return [DbugContour(cv_contour=contour) for contour in contours]",
"def get_contour(img):\n contours,_ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPRO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main methods for processing an image and detect rectangles in the given hsv color range set debug to True in order to show the intermediate images | def do_full(self, image,hsv,upper,lower,debug=False):
single_color_img = self.extract_single_color_range(image,hsv,lower,upper)
if debug:
# cv2.imshow('single_color_img',single_color_img)
cv2.imwrite('debug_pics/single_color_img.jpg',single_color_img)
single_channel = sel... | [
"def color_segmentation(self):\n cv.namedWindow(\"Segmentation parameters\")\n self.create_trackbar(\"h-u\", \"Segmentation parameters\")\n self.create_trackbar(\"h-l\",\"Segmentation parameters\")\n self.create_trackbar(\"s-u\",\"Segmentation parameters\")\n self.create_trackbar(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates Laplace(f), using the inverse metric g_inv, the determinant of the metric g_det, all in variables X. | def laplace(f, g_inv, g_det, X):
r = 0
for i in range(len(X)):
for j in range(len(X)):
r += g_inv[i, j]*f.diff(X[i]).diff(X[j])
for sigma in range(len(X)):
for alpha in range(len(X)):
r += g_det.diff(X[sigma]) * g_inv[sigma, alpha] * \
f.diff(X[alpha])... | [
"def test_laplace():\n f = np.asarray([\n [0.99, 1.0, 0.5],\n [0.69, 0.6, 0.6]])\n R = common_metrics.laplace(f, maximise=True)\n expected = np.asarray(\n [0.83, 0.63])\n assert np.allclose(R, expected)\n R = common_metrics.laplace(f, maximise=False)\n expected = np.asarray(\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transforms from cartesian coordinates X to any curvilinear coordinates Y. It printing useful information, like Jacobian, metric tensor, determinant of metric, Laplace operator in the new coordinates, ... g_correct ... if not None, it will be taken as the metric this is useful if sympy's trigsimp() is not powerful enoug... | def transform(name, X, Y, *, g_correct=None, recursive=False):
print("_"*80)
print("Transformation:", name)
for x, y in zip(X, Y):
pprint(Eq(y, x))
J = X.jacobian(Y)
print("Jacobian:")
pprint(J)
g = J.T*eye(J.shape[0])*J
g = g.applyfunc(expand)
print("metric tensor g_{ij}:")... | [
"def transform(self, x1, y1):\n\n # parametry przesunięcia (współrzędne środków ciężkości) \"translation parameters (centroids)\"?:\n # xs1, ys1 - układ pierwotny - \"original coordinate system\"?\n # xs2, ys2 - układ wtórny - \"secondary/resultant coordinate system\"?\n # scale: ska... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the list of files to be downloaded, and store the parsed list in file_list | def parse_file_list(self, file_path=None, file_name_id='Producer Granule ID', url_id='Online Access URLs'):
# read in and maintain the raw csv file as df
df = pd.read_csv(file_path)
# record the number of files
self.file_num = df.__len__()
# initiate the data frame
sel... | [
"def list_files(self, url, location):",
"def parse_files(self):\n parsed_files = []\n for fname in self.filenames:\n parsed_files.append(bs4.BeautifulSoup(open(fname, encoding=\"utf-8\"), \"lxml-xml\"))\n return parsed_files",
"def get_file_list(self):\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |