query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Test Product Template import | def test_0010_product_template_import(self):
with Transaction().start(DB_NAME, USER, context=CONTEXT) as txn:
# Call method to setup defaults
self.setup_defaults()
with txn.set_context(
current_channel=self.channel.id, ps_test=True,
):
... | [
"def test_magento_import_product(self):\n self.instance.import_store()\n self.instance.import_attribute_set()\n self.instance.import_category()\n response = self.instance.import_products()\n product_count = self.env['product.template'].search_count([('magento_id', '!=', False)])\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Authentication using SSH agent Attempt to authenticate to the given transport using any of the private keys available from an SSH agent. | def agent_auth(transport, username):
agent = paramiko.Agent()
agent_keys = agent.get_keys()
if len(agent_keys) == 0:
return
for key in agent_keys:
print('Trying ssh-agent key %s' % hexlify(key.get_fingerprint()))
try:
transport.auth_publickey(username, key)
... | [
"def agent_auth(self, transport, username):\n\n agent = paramiko.Agent()\n agent_keys = agent.get_keys()\n if len(agent_keys) == 0:\n return\n\n for key in agent_keys:\n self.bridge.chan.send('Trying ssh-agent key %s' % hexlify(key.get_fingerprint()))\n t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
run kkr calculation from output of previous calculation but with increased lmax (done with auxiliary voronoi calculation which is imported here). | def test_kkr_increased_lmax(self, clear_database_before_test, kkrhost_local_code, run_with_cache):
from aiida.orm import load_node, CalcJobNode, Dict
from aiida_kkr.calculations import KkrCalculation, VoronoiCalculation
from aiida_kkr.tools import kkrparams
# import previous voronoi cal... | [
"def build_prior_KL(self):\n KL = 0\n for i in np.arange(self.rank): # i is the group id.\n for j in np.arange(self.num_latent_list[i]):\n lat_id = np.sum(self.num_latent_list[:i],dtype = np.int64) + j #id of latent function\n if self.whiten_list[lat_id]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assigns card names according to rank | def _assign_names(rank):
if isinstance(rank, int):
if rank == 1:
return "Ace", (Card.ACE_LOW,Card.ACE_HIGH)
elif rank == 11:
return "Jack", (Card.FACE,Card.FACE)
elif rank == 12:
return "Queen", (Card.FACE,Card.FACE)
elif rank == 13:
return "King", (Card.F... | [
"def set_card_ranks(game):\n players_list = [\"p1\", \"p2\"]\n for player in players_list:\n for card in game[player].cards_in_play:\n try:\n if game[\"lead_suit\"] in card:\n if \"A\" in card:\n game[player].cards_in_play_ranks[game[p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to generate shingles | def generate_shingles(input_path, output_path, w=3):
j = 0
shingles_dict = defaultdict(set)
shingles_identifier = dict()
with open(input_path, 'r') as read_obj:
csv_reader = csv.reader(read_obj)
header = next(csv_reader)
# Check file as empty
if header is not None:
... | [
"def make_shingles_for_each_star():\n partition = partition_by_rating()\n return [make_set_of_shingles(category) for category in partition]",
"def make_set_of_shingles(review_data):\n assert type(review_data) is list, \"must provide a list (of dictionaries)\"\n\n review_text = get_review_text(review_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detect env queue recursively. | def detect_install_queue(env, install_queue=[]):
_env = env()
if _env.done():
print "[info]", env.__name__, "is already done."
return install_queue
else:
if env not in install_queue:
install_queue.insert(0, env)
requires = _env.requires()
if not isinstance(requi... | [
"def cleanup():\r\n assert env.host_string\r\n\r\n # Search for active env.\r\n active_env_rev = active_env()\r\n assert active_env_rev, 'No active env, this could be a problem; aborting.'\r\n active_env_date = hg_revision_timestamp(active_env_rev)\r\n assert active_env_date, 'Could not determine timestamp fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether Index supports a specific attribute. | def supports_index_feature(attr_name):
return supports_indexes and hasattr(_test_index, attr_name) | [
"def is_attribute(self):\n raise NotImplementedError(\n 'operation is_attribute(...) not yet implemented')",
"def is_attribute(self):\r\n return conf.lib.clang_isAttribute(self)",
"def is_attribute(self):\n return conf.lib.clang_isAttribute(self)",
"def has_attr(cls, attr_name:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes given filename containing version, optionally updates the version and saves it, and returns the version. | def ReadAndUpdateVersion(version_filename, update_position=None):
if os.path.exists(version_filename):
current_version = open(version_filename).readlines()[0]
numbers = current_version.split('.')
if update_position:
numbers[update_position] = '%02d' % (int(numbers[update_position]) + 1)
if upd... | [
"def versioned(filename, version, force_version=False, full_path=True):\n if not '.' in filename:\n return None\n\n if USE_VERSIONING or force_version:\n dotindex = filename.rindex('.')\n filename = u'%s.%s%s' % (filename[:dotindex], version, filename[dotindex:])\n\n if full_path:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method updates the calculated rating of a review. It takes the currently assigned ratings for each property, adds them up, then divides by the total points to calculate the percentage of points given. Once that value is calculated, it is divided by 0.2 to the value into a "5 star" rating. | def calculate(self):
rating = 0
props = ['aroma', 'appearance', 'taste', 'palate', 'bottle_style']
for item in props:
rating += getattr(self, item, 0)
self.overall = (rating / self.total) / .2 | [
"def update_rating(self):\n self.rating = self._update_author_comments_rating() + self._update_posts_comments_rating() \\\n + self._update_posts_rating()\n self.save()",
"def updateTripRating():\n\t\tpass",
"def adjust_for_strength_of_schedule(self):\n C = 1.5\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new review for the given beer | def post(id):
try:
beer = Beer.objects.get(id=id)
except mongoengine.DoesNotExist:
return flask.Response('No beer with id {} found'.format(id), 404)
except:
return flask.Response('Invalid id {}'.format(id), 400)
data = flask.request.get_json()
# check to see if a review wa... | [
"def post(self):\r\n self.createReview(self.parseParams())",
"def create_review(supplier, author, rating, content):\n return Review.objects.get_or_create(supplier=supplier, author=author,\n rating=rating, content=content)[0]",
"def addReview(self,user,book,review):\n self.user_id = user... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a sequence of key accesses into a path string representing a path below the top level key in redis | def key_sequence_to_path(sequence: List[str]):
return Path.rootPath() + ".".join(sequence) | [
"def sub_key(dirname):\n return SUB_PREFIX + dirname",
"def _path_to_key(self, path: str) -> str:\n return path",
"def GetKeyByPath(self, key_path):",
"def ConstructFlattenedKey(path):\n buf = cStringIO.StringIO()\n for i in xrange(len(path)):\n if isinstance(path[i], Index):\n buf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a copy of dictionary with the paths formed by key_sequences removed | def copy_dictionary_without_paths(dictionary: Dict, key_sequence: List[List[str]]):
ret = {}
possibles = [ks for ks in key_sequence if len(ks) == 1]
possibles = set(reduce(lambda x, y: x + y, possibles, []))
for k, v in dictionary.items():
if k in possibles:
continue
if type(... | [
"def __drop_depth_0_keys(target_dict):\n ret = [\n copy.deepcopy(target_dict[key])\n for key in target_dict.keys()\n if hasattr(target_dict[key], \"keys\")]\n new_dict = Dict()\n for tmp in ret:\n new_dict += tmp\n return new_dict",
"def extr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a list of paths and a prefix, return the paths that | def filter_paths_by_prefix(paths: Iterable[str], prefix: str):
if prefix == Path.rootPath():
return paths, paths
full_paths, suffixes = [], []
for p in paths:
if p.startswith(prefix):
suffixes.append(p[len(prefix):])
full_paths.append(p)
return full_paths, suffixe... | [
"def get_prefixes(buildout):\n\n prefixes = parse_list(buildout.get('prefixes', ''))\n return [os.path.abspath(k) for k in prefixes if os.path.exists(k)]",
"def get_files_prefix(prefixes, dirname, Lshow=None, Ldir=None):\n matched_files=[]\n for pref in prefixes:\n print(f\"prefix: {pref} in {where... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert value into dictionary at path specified by key_sequence. If the sequence of keys does not exist, it will be made | def insert_into_dictionary(dictionary: Dict, key_sequence: List[str], value):
parent = dictionary
for key in key_sequence[:-1]:
if key not in parent.keys():
parent[key] = {}
parent = parent[key]
parent[key_sequence[-1]] = value | [
"def set_sequence_key(self, filename, sequence_key):\n self.sequence_keys[filename] = sequence_key",
"def insert(self, index, key, value):\n if key in self:\n # FIXME: efficiency?\n del self[key]\n self._sequence.insert(index, key)\n dict.__setitem__(self, key, value)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure the key name provided is legal | def check_valid_key_name(name):
if type(name) not in [str]:
return False
bad_chars = ["*", ".", "&&&&"]
for k in bad_chars:
if k in name:
return False
return True | [
"def _check_key_name(cls, name):\n return (isinstance(name, basestring) and\n re.match('^[A-Za-z][A-Za-z0-9_]*$', name) and\n not hasattr(cls, name))",
"def _validate_key(self, keyname):\r\n if keyname is None:\r\n raise ValueError('You must pass a keyname fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It reduces all buffers across network copies | def average_buffers(network):
size = int(dist.get_world_size())
with torch.no_grad():
for buf in network.buffers():
dist.all_reduce(buf, op=dist.ReduceOp.SUM)
buf.div_(size) | [
"def resizeBuffers(self):\n for i, buffer in enumerate(self.buffers):\n (mul, div, align) = self.sizes[i]\n (xsize, ysize) = self.getScaledSize(mul, div, align)\n buffer.setSize(xsize, ysize)",
"def _refresh_buffers(self) -> None:",
"def pool(self):\r\n\r\n self.bu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Permt de créer la conversation souhaitée (train ou hotel) ou degénérer la reponse appropriée | def create_conv_and_answer(self, infos_in_message : dict, message : str):
possible_info_asked = {
'aller' : ConvTrain,
'retour' : ConvTrain,
'hotel' : ConvHotel,
'voyageur' : ConvNameInfo,
'voyageur_add' : ConvNameInfo,
}
if self.info_a... | [
"def train(self, conversation):\n for conversation_count, text in enumerate(conversation):\n if conversation_count%1000==0:\n print(\"training %d : \"%conversation_count, text[0],\"|\", text[1])\n\n statement = self.get_or_create(text[1])\n statement.add_respon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the data file into dicts. | def get_data(fname: str) -> dict:
with open(fname) as f:
return [rec.split() for rec in f.read().split("\n\n")] | [
"def read_data(self, file_name):\n test_data_dict = {}\n i = 0\n file_handler = open(file_name)\n for data in file_handler.readlines():\n if i == 0:\n pass\n else:\n if data[len(data) - 1] == '\\n':\n data = data[:len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
opens the info window | def open_info_dialog(self):
info_dialog = InfoDialog()
info_dialog.exec_() | [
"def showInfoWindow():\n\treturn 0",
"def on_info_click(self, event):\n def on_close(event, wind):\n wind.Close()\n wind.Destroy()\n event.Skip()\n wind = wx.PopupTransientWindow(self, wx.RAISED_BORDER)\n if self.auto_save.GetValue():\n info = \"'auto-s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a list of unique datasets in a directory | def list_unique_datasets(root, type ='roi'):
import os
lst_dir = os.listdir(root)
lst_datasets = []
for item in lst_dir:
if f".{type}.hdf5" in item:
rt,camera_name,dataset_name,chunk,extension = split_raw_filename(item)
if dataset_name not in lst_datasets:
... | [
"def present_datasets(root):\n datasets = set()\n for fn in glob.glob(op.join(root, '*.sdf')):\n name = op.splitext(op.split(fn)[1])[0].split('_')[0]\n datasets.add(name)\n return sorted(datasets)",
"def get_dataset_ids(clean_folder):\n files = os.listdir(clean_folder... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the primes under 10 and 100 | def test_primes_under_10(self):
self.assertEqual(sieve(10), [2, 3, 5, 7])
self.assertEqual(sieve(100), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]) | [
"def test_with_10_prime_numbers(self):\n numbers = [3,5,7,11,13,17,19,23,29,31]\n for number in numbers:\n self.assertFalse(has_divisors(number, int(math.sqrt(number) // 1) + 1), \"Number {} is a prime number.\".format(number))",
"def test_11(self):\n\t\tself.assertFalse(is_prime(11))",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the lengths of the list of primes up to 1000000 | def test_primes_under_1000000(self):
self.assertEqual(len(sieve(100)), 25)
self.assertEqual(len(sieve(1000)), 168)
self.assertEqual(len(sieve(10000)), 1229)
self.assertEqual(len(sieve(100000)), 9592)
self.assertEqual(len(sieve(1000000)), 78498) | [
"def count_prime():\n nums = []\n for i in range(2, 10000):\n if is_prime(i):\n nums.append(i)\n return nums",
"def all_prime(uplimit):\n primes = [2]\n num = 3\n while num <= uplimit:\n if num % 1000000 == 0:\n print num\n root = int(math.sqrt(num))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Kill any active children, returning any that were not terminated within timeout. | def kill_children(timeout=1) -> List[psutil.Process]:
procs = child_manager.children_pop_all()
for p in procs:
try:
p.terminate()
except psutil.NoSuchProcess:
pass
gone, alive = psutil.wait_procs(procs, timeout=timeout)
for p in alive:
logger.warning("Clea... | [
"def _KillChildren(cls, bg_tasks, log_level=logging.WARNING):\n logging.log(log_level, 'Killing tasks: %r', bg_tasks)\n siglist = (\n (signal.SIGXCPU, cls.SIGTERM_TIMEOUT),\n (signal.SIGTERM, cls.SIGKILL_TIMEOUT),\n (signal.SIGKILL, None),\n )\n first = True\n for sig, timeout in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the total for the given tenant. | def get_total(self, **kwargs):
LOG.warning('WARNING: /v1/report/total/ endpoint is deprecated, '
'please use /v1/report/summary instead.')
authorized_args = [
'begin', 'end', 'tenant_id', 'service', 'all_tenants']
url = self.get_url('total', kwargs, authorized_arg... | [
"def get_total_paid(self):\n return sum(self.paid)",
"def total(self):\n return self.subtotal if not self.tax else self.subtotal + self.total_tax",
"def _total_amount(self, query):\n query = query.values(\"amount\").aggregate(total=models.Sum(\"amount\"))\n return query[\"total\"] or... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the ssc id (default is sscmainnet1) | def set_id(self, ssc_id):
self.ssc_id = ssc_id | [
"def ecs_id(self, ecs_id):\n self._ecs_id = ecs_id",
"def sis_source_id(self, value):\r\n self.logger.warn(\"Setting values on sis_source_id will NOT update the remote Canvas instance.\")\r\n self._sis_source_id = value",
"def srs_id(self, srs_id):\n self.logger.debug(\"In 'srs_id' s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes the wallet account | def change_account(self, account):
check_account = Account(account, steem_instance=self.steem)
self.account = check_account["name"]
self.refresh() | [
"def setaccount(self, vergeaddress, account):\n return self.proxy.setaccount(vergeaddress, account)",
"def update_account(AccountId=None, Name=None):\n pass",
"def setAccount(self,acctId,acctKey):\n\t\tself.auth.update({'APP':'aatt_python','ACCOUNT':acctId,'KEY':acctKey})",
"def put_account(self, ac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transfer a token to another account. | def transfer(self, to, amount, symbol, memo=""):
token_in_wallet = self.get_token(symbol)
if token_in_wallet is None:
raise TokenNotInWallet("%s is not in wallet." % symbol)
if float(token_in_wallet["balance"]) < float(amount):
raise InsufficientTokenAmount("Only %.3... | [
"def token_transfer(ctx, amount, to):\n ocean = ctx.obj['ocean']\n account = ocean.account\n ocean.tokens.transfer(to, int(amount), account)\n echo({\n 'amount': amount,\n 'from': {\n 'address': account.address,\n 'balance': Token.get_instance().get_token_balance(acco... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Issues a specific token amount. | def issue(self, to, amount, symbol):
token = Token(symbol, api=self.api)
if token["issuer"] != self.account:
raise TokenIssueNotPermitted("%s is not the issuer of token %s" % (self.account, symbol))
if token["maxSupply"] == token["supply"]:
raise MaxSupplyR... | [
"def mint(self, token_amount):\n sp.set_type(token_amount, sp.TNat)\n self.fetch_target_price(sp.unit)\n self.update_accrual(sp.unit)\n self.data.sender = sp.sender\n sp.transfer(token_amount, sp.mutez(0), sp.self_entry_point('internal_mint'))",
"def internal_mint(self, token_am... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the buy book for the wallet account. When symbol is set, the order book from the given token is shown. | def get_buy_book(self, symbol=None, limit=100, offset=0):
if symbol is None:
buy_book = self.api.find("market", "buyBook", query={"account": self.account}, limit=limit, offset=offset)
else:
buy_book = self.api.find("market", "buyBook", query={"symbol": symbol, "account": self... | [
"def get_order_book(self, symbol):\n return self.request('book/' + symbol)",
"async def get_orderbook(self, symbol, params={}):\n self.orderbook[symbol] = await self._fetch_orderbook(symbol, params=params)\n return self.orderbook[symbol]",
"def book_ticker(self, symbol=''):\n params ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the sell book for the wallet account. When symbol is set, the order book from the given token is shown. | def get_sell_book(self, symbol=None, limit=100, offset=0):
if symbol is None:
sell_book = self.api.find("market", "sellBook", query={"account": self.account}, limit=limit, offset=offset)
else:
sell_book = self.api.find("market", "sellBook", query={"symbol": symbol, "a... | [
"def get_buy_book(self, symbol=None, limit=100, offset=0):\r\n if symbol is None:\r\n buy_book = self.api.find(\"market\", \"buyBook\", query={\"account\": self.account}, limit=limit, offset=offset)\r\n else:\r\n buy_book = self.api.find(\"market\", \"buyBook\", query={\"symbol\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List a folder. Return a dict mapping unicode filenames to FileMetadata|FolderMetadata entries. | def list_folder(dbx, folder, subfolder):
path = '/%s/%s' % (folder, subfolder.replace(os.path.sep, '/'))
while '//' in path:
path = path.replace('//', '/')
path = path.rstrip('/')
try:
with stopwatch('list_folder'):
res = dbx.files_list_folder(path)
except dropbox... | [
"def filelist(folder):\n file_dict={}\n folderlist = glob.glob(os.getcwd()+\"/\"+folder+\"/*\")\n for i in tqdm(folderlist):\n filelist = glob.glob(i+\"/*\")\n filename = i.rsplit(\"/\")[-1]\n file_dict[filename]= filelist\n\n return file_dict",
"def ListFolder(self, path): # real... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if this operator is a comparison operator. | def is_comparison_op(self):
return self.value in ["=", "!=", "<", "<=", ">", ">="] | [
"def isOperator(self):\n return _libsbml.ASTNode_isOperator(self)",
"def isOperator(self, *args):\n return _libsbml.ASTBasePlugin_isOperator(self, *args)",
"def is_operator(self):\n\n return self.get_type() == TOKEN_TYPE_OPERATOR",
"def is_comparison(node):\n return isinstance(node, Co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if this operator is an arithmetic operator. | def is_arithmetic_op(self):
return self.value in ["+", "-"] | [
"def isOperator(self):\n return _libsbml.ASTNode_isOperator(self)",
"def is_operator(self, token):\n if token['value'] in ['(', ')', '*', '/', '+', '-']:\n return True\n else:\n return False",
"def is_plus_operator(self):\n\n if not self.is_operator():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
La funcion recibe el servicio, la ciudad y la fecha. | def get_precio_de_servicio(**kwargs):
servicio = kwargs.get("servicio")
ciudad = kwargs.get("ciudad")
if ciudad and servicio:
fecha = kwargs.get("fecha") if 'fecha' in kwargs else datetime.date.today()
precios = [precio for precio in
PrecioDeServicio.objects.filter(servic... | [
"def buscarservicioprecio(reserva):\n try:\n\n conexion.cur.execute('Select Servicio, Precio from Servicios where Reserva = ?', (reserva,))\n servicios = conexion.cur.fetchall()\n conexion.conex.commit()\n return servicios\n\n except Exception as e:\n print(\"Error módulo bu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform PoseStamped detection into base_link frame. Returns PoseStamped in base_link frame. | def _transform_to_base_link(self, detection, timeout=3.0):
self.swarmie.xform.waitForTransform(
self.rovername + '/base_link',
detection.pose.header.frame_id,
detection.pose.header.stamp,
rospy.Duration(timeout)
)
return self.swarmie.xform.transfo... | [
"def scan_to_base_link_points(self, scan):\n\n #angles = np.arange(scan.angle_min, scan.angle_max-scan.angle_increment, scan.angle_increment)\n angles = np.linspace(scan.angle_min, scan.angle_max, len(scan.ranges))\n X = scan.ranges * np.cos(angles) # TODO: get distance between laser frame and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform PoseStamped detection into /odom frame. Returns PoseStamped in /odom frame. | def _transform_to_odom(self, detection, timeout=3.0):
self.swarmie.xform.waitForTransform(
self.rovername + '/odom',
detection.pose.header.frame_id,
detection.pose.header.stamp,
rospy.Duration(timeout)
)
return self.swarmie.xform.transformPose(sel... | [
"def build_pose_stamped_msg(self):\n \n # Hand first\n ps_msg = PoseStamped()\n ps_msg.header.stamp = rospy.Time.now()\n ps_msg.header.frame_id = FRAME_ID\n \n if not DEBUG_TEST:\n position = self.hand.palm_position\n\n # Set position values in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if it looks like the rover is inside the ring of home tags and needs to get out! Returns False if no home tags in view. | def is_inside_home_ring(self, detections):
YAW_THRESHOLD = 1.3 # radians
see_home_tag = False
good_orientations = 0
bad_orientations = 0
for detection in detections:
if detection.id == 256:
see_home_tag = True
home_detection = self._t... | [
"def sees_home_tag(self):\n detections = self.swarmie.get_latest_targets().detections\n\n for detection in detections:\n if detection.id == 256:\n return True\n\n return False",
"def _is_rover_inside_home(self, good_yaw_count, bad_yaw_count):\n # type: (float,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The safe driving pathway is defined to be the space between two lines running parallel to the rover's xaxis, at y=0.33m and y=0.33m. Driving between these lines gives the wheels about 10cm of clearance on either side. These lines also conveniently intersect the upperleft and upperright corners of the camera's field of ... | def _get_angle_and_dist_to_avoid(self, detection, direction='left'):
OVERSHOOT_DIST = 0.20 # meters, distance to overshoot target by
base_link_pose = self._transform_to_base_link(detection)
radius = math.sqrt(base_link_pose.pose.position.x ** 2
+ base_link_pose.pose.p... | [
"def _compute_connection(current_waypoint, next_waypoint, threshold=35):\n n = next_waypoint.transform.rotation.yaw\n n = n % 360.0\n\n c = current_waypoint.transform.rotation.yaw\n c = c % 360.0\n\n diff_angle = (n - c) % 180.0\n if diff_angle < threshold or diff_angle > (180 - threshold):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the angle required to turn and face a detection to put it in the center of the camera's field of view. | def get_angle_to_face_detection(self, detection):
base_link_pose = self._transform_to_base_link(detection)
radius = math.sqrt(base_link_pose.pose.position.x ** 2
+ base_link_pose.pose.position.y ** 2)
tag_point = Point(x=base_link_pose.pose.position.x,
... | [
"def get_field_of_view(self):\n assert self.width is not None and self.height is not None\n angle = (\n math.atan(\n max(self.width, self.height) / (self.get_focal_length() * 2.0)\n )\n * 2.0\n )\n return angle",
"def get_angle_to_face_po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn and face the home tag nearest the center of view if we see one. Does nothing if no home tag is seen. | def face_home_tag(self):
home_detections = self._sort_home_tags_nearest_center(
self.swarmie.get_latest_targets().detections
)
if len(home_detections) > 0:
angle = self.get_angle_to_face_detection(home_detections[0])
current_heading = self.swarmie.get_odom_loc... | [
"def set_home_locations(self):\n self.swarmie.set_home_gps_location(self.swarmie.get_gps_location())\n\n current_location = self.swarmie.get_odom_location()\n current_pose = current_location.get_pose()\n home_odom = Location(current_location.Odometry)\n\n detections = self.swarmie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the rover can see a home tag. Returns false otherwise. | def sees_home_tag(self):
detections = self.swarmie.get_latest_targets().detections
for detection in detections:
if detection.id == 256:
return True
return False | [
"def ishome(self):\n return self._plrevgeoloc.isHome",
"def isHomePage(self):\n home = self.getHome(self.url)\n if home == self.url:\n return True\n if home == self.url + '/':\n return True\n return False",
"def is_home_address(self):\n return self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort home tags (id == 256) in view by their distance from the center of the camera's field of view. | def _sort_home_tags_nearest_center(self, detections):
sorted_detections = []
for detection in detections:
if detection.id == 256:
sorted_detections.append(detection)
return sorted(sorted_detections,
key=lambda x: abs(x.pose.pose.position.x)) | [
"def sorteVisibleMark(self, aRobotCurPos6d):\n _rMinDistance = 0.10 # in meters\n _rMaxDistance = 2.50 # in meters\n _rAbsAlphaVertical = math.pi / 4.0\n _rAbsAlphaHorizontal = math.pi / 4.0\n _rAbsBetaHorizontal = math.pi * 2/3.0 # 120 degre\n _rAbsBetaVertical = 0.34 ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort tags in view from left to right (by their x position in the camera frame). Removes/ignores tags close enough in the camera to likely be a block in the claw. | def _sort_tags_left_to_right(self, detections, id=0):
BLOCK_IN_CLAW_DIST = 0.22 # meters
sorted_detections = []
for detection in detections:
if (detection.id == id and
detection.pose.pose.position.z > BLOCK_IN_CLAW_DIST):
sorted_detections.append... | [
"def _sort_home_tags_nearest_center(self, detections):\n sorted_detections = []\n\n for detection in detections:\n if detection.id == 256:\n sorted_detections.append(detection)\n\n return sorted(sorted_detections,\n key=lambda x: abs(x.pose.pose.po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn by 'angle' and then drive 'dist'. | def _go_around(self, angle, dist):
ignore = Obstacle.IS_SONAR
if self.avoid_targets is True:
ignore |= Obstacle.TAG_TARGET
elif self.avoid_home is True:
# Need to ignore both for this because target tags are likely to
# be in view inside the home nest.
... | [
"def turn_move(self, angle_dist):\n self.right(angle_dist[0])\n self.forward(angle_dist[1])",
"def distanceToAngle(self, distance):\n \n return self.angle_to_distance_param_a*distance + self.angle_to_distance_param_b",
"def angleToDistance(self, angle):\n\n return (angle - self.angle_to_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the angle you should turn in order to face a point. | def get_angle_to_face_point(self, point):
start = self.swarmie.get_odom_location().get_pose()
return angles.shortest_angular_distance(
start.theta,
math.atan2(point.y - start.y, point.x - start.x)
) | [
"def get_angle(self, point_x, point_y):\n angle = atan2(point_y - self.player_y, point_x - self.player_x)\n # print(f\"point_x {point_x} point_y {point_x} angle {angle}\")\n return angle",
"def angle(self) -> float:\n return math.degrees(math.atan2(self.y, self.x))",
"def angle(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Have the rover turn to face the nearest block to it. Useful when exiting gohome (when going home without a block) or search. Does nothing if no blocks are seen, if there is a home tag closer to the rover than the nearest block, or if a sonar obstacle prevents the rover from making the turn. Catches any transform except... | def face_nearest_block(self):
try:
block = self.swarmie.get_nearest_block_location(
use_targets_buffer=True
)
except tf.Exception:
# The caller should be about to exit with a normal exit code
# after this call anyway, so the pickup behavior... | [
"def move_to_block_types(self, block_types):\n x0, y0, z0 = self.position\n for x, y, z in self.world.iter_nearest_from_block_types(x0, y0, z0, block_types):\n if euclidean(self.position, (x, y, z)) <= 4:\n return (x, y, z)\n if self.navigate_to(x, y, z, space=3):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get another nav plan and return the first waypoint. Try three times, incrementing self.tolerance by tolerance_step after a failure. | def _get_next_waypoint(self, tolerance_step):
print('\nGetting new nav plan.')
for i in range(4):
try:
self.plan = self.swarmie.get_plan(
self.goal,
tolerance=self.tolerance,
use_home_layer=self.avoid_home
... | [
"def test_find_closest_waypoints_nearest(self):\n planner = WaypointPlanner(make_example_base_waypoints())\n\n planner.position = Vector3(0, 0, 0)\n waypoints = planner.find_closest_waypoints(1)\n self.assertEqual(1, len(waypoints))\n self.assertEqual(0, waypoints[0].pose.pose.pos... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check sonar obstacles over a short period of time, hopefully to weed out some of the noise and let us continue driving if we stopped for a 'fake' obstacle. | def _check_sonar_obstacles(self):
# TODO: what's a good number?
BLOCKED_THRESHOLD = 0.7
rate = rospy.Rate(10) # 10 hz
count = 10
left = 0
center = 0
right = 0
for i in range(count):
obstacle = self.swarmie.get_obstacle_condition()
... | [
"def check_for_obstacles(self):\n obs = False\n obs_p = []\n for point in self.obstacles:\n if -0.15 <= point[1] <= 0.15: # robot is 178mm wide\n # Obstacles should be less than or equal to 0.2 m away before being detected\n if 0 <= point[0] <= .2:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to Planner.drive_to(). Make one attempt to get around a home or target tag. | def _avoid_tag(self, id=0, ignore=Obstacle.IS_SONAR):
sorted_detections = self._sort_tags_left_to_right(
self.swarmie.get_latest_targets().detections,
id=id
)
# if count == 3: # last resort
# self.current_state = Planner.STATE_DRIVE
# angle = sel... | [
"def slew_to_home(self):\n raise NotImplementedError",
"def stopGotoPosture( bForceOldVersion = False ):\n strVersion = system.getNaoqiVersion();\n if( \"1.12\" in strVersion or \"1.10\" in strVersion or bForceOldVersion ):\n global global_gotoPostureMultiversion_currentMove;\n if( glob... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if it's safe for the rover to back up. It is safe to back up if the rover is further than 1.5 meters from the current home location, or if the rover is within 1.5 meters from home, but is facing home. In other words, it's not safe to back up if the rover is close to home and has it's back to home. | def _is_safe_to_back_up(self):
# Only back up if we're far enough away from home for it
# to be safe. Don't want to back up into the nest!
home_loc = self.swarmie.get_home_odom_location()
current_loc = self.swarmie.get_odom_location().get_pose()
dist = math.sqrt((home_loc.x - cur... | [
"def may_climb_up(self) -> bool:\n return self.tile.mytype is TileTypeEnum.STAIRS_UP",
"def is_wall_up(self, location):\n return",
"def _are_we_stuck(Rover):\n recent_positions_np = np.array(Rover.recent_positions)\n delta_x = recent_positions_np[:, 0].ptp()\n delta_y = recent_positions_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn to face a point in the odometry frame. Rover will attempt to turn the shortest angle to face the point, and if it fails (sonar detects something in the way, or the rover saw a type of tag it wants to stop for), it will possibly back up and try to turn in the opposite direction to face the point. | def _face_point(self, point, ignore=Obstacle.PATH_IS_CLEAR):
print('Facing next point...')
# Make sure all sonar sensors are never ignored together here
if ignore & Obstacle.IS_SONAR == Obstacle.IS_SONAR:
ignore ^= Obstacle.IS_SONAR
ignore |= Obstacle.SONAR_BLOCK
# T... | [
"def get_angle_to_face_point(self, point):\n start = self.swarmie.get_odom_location().get_pose()\n return angles.shortest_angular_distance(\n start.theta,\n math.atan2(point.y - start.y, point.x - start.x)\n )",
"def change_face(self, face):\n if self.face is not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to get the rover to goal location. Returns when at goal or if home target is found. !! avoid_targets and avoid_home shouldn't both be set to True. avoid_home will be set to False in this case. !! | def drive_to(self, goal, tolerance=0.0, tolerance_step=0.5,
max_attempts=10, avoid_targets=True, avoid_home=False,
use_waypoints=True, start_location=None,
distance_threshold=None):
print('\nRequest received')
self.fail_count = 0
self.tolerance ... | [
"def search(world_state, robot_pose, goal_pose):\n if world_state.shape[0] == 0 or world_state.shape[1] == 0:\n print(\"Error, empty world_state!!!\")\n return None\n if not is_pos_valid(robot_pose, world_state.shape):\n print(\"Error, invalid robot_pose!!!\", robot_pose)\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience wrapper to drive_to(). Drive the given distance, while avoiding sonar and target obstacles. !! avoid_targets and avoid_home shouldn't both be set to True. avoid_home will be set to False in this case. !! | def drive(self, distance, tolerance=0.0, tolerance_step=0.5,
max_attempts=10, avoid_targets=True, avoid_home=False,
use_waypoints=True):
self.cur_loc = self.swarmie.get_odom_location()
start = self.cur_loc.get_pose()
goal = Point()
goal.x = start.x + distance... | [
"def drive_to(self, goal, tolerance=0.0, tolerance_step=0.5,\n max_attempts=10, avoid_targets=True, avoid_home=False,\n use_waypoints=True, start_location=None,\n distance_threshold=None):\n print('\\nRequest received')\n self.fail_count = 0\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the rover's home locations in the /odom and /map frames. Can be called manually, but is also called from Planner.drive_to() when a home tag is seen. | def set_home_locations(self):
self.swarmie.set_home_gps_location(self.swarmie.get_gps_location())
current_location = self.swarmie.get_odom_location()
current_pose = current_location.get_pose()
home_odom = Location(current_location.Odometry)
detections = self.swarmie.get_latest_... | [
"def home(self, home):\n\n self._home = home",
"def set_current_location_as_home(self):\n response = False\n while (not response) and (not rospy.is_shutdown()):\n response = self._set_home_proxy(True, 0., 0., 0., 0.).success\n self._rate.sleep()\n if response:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of waypoints for the spiral search pattern. Waypoints will be used as goals to planner.drive_to() | def _get_spiral_points(self, start_distance, distance_step, num_legs=10):
start_loc = self.swarmie.get_odom_location().get_pose()
points = []
distance = start_distance
angle = math.pi / 2
prev_point = Point()
prev_point.x = start_loc.x + distance * math.cos(start_loc.the... | [
"def waypoints(self):\n\t\treturn [Star(star_id, galaxy=self.galaxy) for delay, star_id, order, num_ships in self.data.o]",
"def return_list_of_waypoints(self, p1, p2, dp, it):\n waypoints = list()\n current_p = p1\n waypoints.append(current_p)\n p = Pose()\n p.position.x = curr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render a mesh by casting an array of rays from an origin point, finding where they hit the mesh, and using the combination of a color texture function and the normal of the ray collision to color the resulting pixel. | def ray_cast(
mesh: jnp.ndarray,
origin: jnp.ndarray,
directions: jnp.ndarray,
color_fn: Callable[[jnp.ndarray], jnp.ndarray],
batch_size: int = 128,
bg_color: jnp.ndarray = None,
ambient_light: float = 0.0,
) -> jnp.ndarray:
# Normalize the directions so that dot products are meaningful... | [
"def trace(self, ray, scene):\r\n # how many times rays can bounce\r\n depth = 6\r\n # background color\r\n color = ColorRGBA(53/100, 81/100, 92/100, 0)\r\n # Find the nearest object hit by the ray in the scene\r\n dist_hit, obj_hit = self.findNearest(ray, scene)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produce a grid of ray directions to use for ray_cast(). | def ray_grid(
x: jnp.ndarray,
y: jnp.ndarray,
z: jnp.ndarray,
resolution: int,
):
scales = jnp.linspace(-1.0, 1.0, num=resolution)
x_vecs = x * scales[None, :, None]
y_vecs = y * scales[:, None, None]
results = (x_vecs + y_vecs + z).reshape([-1, x.shape[0]])
return jax.vmap(_normaliz... | [
"def trace_directions(self, direction, grid, length=7):\n result = []\n for dx, dy in direction:\n for cell in range(1, length + 1):\n result.append([self.x + dx * cell, self.y + dy * cell])\n if grid.get_piece(self.x + dx * cell, self.y + dy * cell):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shoot a ray from an origin point in a given direction and find the first place it intersects a mesh, if anywhere. | def mesh_ray_collision(mesh: jnp.ndarray, origin: jnp.ndarray, direction: jnp.ndarray):
collides, positions, distances = jax.vmap(
lambda t: _triangle_ray_collision(t, origin, direction)
)(mesh)
idx = jnp.argmin(jnp.where(collides, distances, jnp.inf))
return (
jnp.any(collides),
... | [
"def intersect(self, ray_org, ray_dir):\n num = ray_org.shape[0]\n miss = torch.ones(num, dtype=PRECISION, device=DEVICE) * 1e5\n EPS = 1e-5\n op = (self.center - ray_org)\n b = dot(op, ray_dir)\n det = b * b - dot(op, op) + self.radius * self.radius\n det2 = torch.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads in a .haml file and outputs a list. | def readHaml(fileName: str) -> List[Tuple[str, float]]:
outList = list()
with open(fileName, 'r') as fileIn:
for line in fileIn:
val = (line.split()[0], float(line.split()[1]))
outList.append(val)
return outList | [
"def extract_haml(fileobj, keywords, comment_tags, options):\n\n import haml\n from mako import lexer, parsetree\n from mako.ext.babelplugin import extract_nodes \n\n encoding = options.get('input_encoding', options.get('encoding', None))\n template_node = lexer.Lexer(haml.preprocessor(fileobj.read()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the path to the root directory of the KITTI road dataset, it creates a dictionary of the data as numpy arrays. data_dir = directory containing `testing` and `training` subdirectories | def create_data_dict(data_dir, img_size=[25, 83]):
print("Creating data dictionary")
print("- Using data at:", data_dir)
# Directories
imgs_dir = os.path.join(data_dir, "training/image_2")
labels_dir = os.path.join(data_dir, "training/gt_image_2")
print("- Getting list of files")
# Only ge... | [
"def load_dataset(folder: Pathlike) -> dict:\n folder = Path(folder)\n case_identifiers = get_np_paths_from_dir(folder)\n\n dataset = OrderedDict()\n for c in case_identifiers:\n dataset[c] = OrderedDict()\n dataset[c]['data_file'] = str(folder / f\"{c}.npy\")\n dataset[c]['seg_file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reject the indent form. | def reject(self):
print "This form has been rejected. Current state:", self.state | [
"def leave(self):\n assert(self.indent > 0)\n self.indent -= 1",
"def removeIndent(self):\r\n if self._indents <= 0:\r\n raise Exception(\"Indentation can not be decreased to negative values\")\r\n self._indents -= 1",
"def check_indent_allowed(self) -> bool:\n return F... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
scale crop the image to make every image of the same square size, H = W = crop_size | def _scale_and_crop(self, img, seg, crop_size):
h, w = img.shape[0], img.shape[1]
# if train:
# # random scale
# scale = random.random() + 0.5 # 0.5-1.5
# scale = max(scale, 1. * crop_size / (min(h, w) - 1)) # ??
# else:
# # scale to crop size
... | [
"def _resize_thumbnail_and_crop(self):\n\n logging.debug('Reducing image size and cropping as necessary.')\n return ImageOps.fit(image=self._orig_img, size=self._desired_size,\n centering=self._position)",
"def squareCrop(img):\n new_size = (min(img.shape), min(img.shape))\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create props suitable for plot panel | def create_plot_panel_props(prop_map):
props = {}
for k1, v in prop_map.items():
v = {'edgecolor' : v.get('color', None),
'facecolor' : 'none',
'linewidth' : v.get('width', None),
'alpha' : v.get('alpha', None)}
for k2, _ in prop_map.items():
if... | [
"def make_mpl_properties(n ,prop ='color'): \r\n n=int(_assert_all_types(n, int, float, objname =\"'n'\"))\r\n prop = str(prop).lower().strip().replace ('s', '') \r\n if prop not in ('color', 'marker', 'line'): \r\n raise ValueError (\"Property {prop!r} is not availabe yet. , Expect\"\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a logo from a local or GCS path | def get_logo(img_or_path):
if not isinstance(img_or_path, str):
return np.asarray(img_or_path)
path = img_or_path
if path.startswith('gs://') or path.startswith('gcs://'):
_, path = path.split('//', 1)
local_path = logo_dir / os.path.basename(path)
if not local_path.exists():... | [
"def logo():\n return _load(\"data/logo.png\")",
"def get_image(self):\n return self._get_image('logo.png')",
"def fetch_logo_url(organization):\n return fetch_json(image_url, organization)",
"def logo_url(self):\n return self.get_url(\"logo\", \"images/logo.png\")",
"def get_logo(plugin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the default logos to use with add_logo Either the light logo, the dark logo, or both may be specified. If both, then scale_adj and alpha applies to both. If neither is specified, nothing is done. | def set_default_logos(light_logo=None, dark_logo=None, scale_adj=1, alpha=None):
if light_logo is not None:
light['pyseas.logo'] = get_logo(light_logo)
light['pyseas.logo.scale_adj'] = scale_adj
if alpha is not None:
light['pyseas.logo.alpha'] = alpha
if dark_logo is not None... | [
"def settLogo(self, logo):\n if logo:\n self.firma['logo'] = logo\n else:\n raise f60Feil(u'Ugyldig logo: %s' % logo)",
"def putlogo(figure=None):\n ip = get_ipython()\n if figure is None:\n figure=plt.gcf()\n curraxis= figure.gca()\n logoaxis = figure.add_ax... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete node and all respective relationships | def delete_node(tx, node_value, node_type):
cql = "MATCH(n:" + node_type + "{name:$node_value}) DETACH DELETE(n);"
try:
tx.run(cql, node_value=node_value)
except Exception as e:
print(str(e)) | [
"def delete_node(self, node):",
"def delete(self, node):\n pass",
"def _delete(self):\n\n if not self.node_exists:\n return\n\n for association in self.node._pg_edges:\n setattr(self.node, association, [])\n\n self.transaction.session.delete(self.node)",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete Utterance Relationship, based on input nodes | def delete_relationship(tx, node_value_1=None, node_value_2=None, node_type_1=None, node_type_2=None, relationship=None):
if node_value_1 is None and node_type_1 is None:
cql = "MATCH ()-[u:" + relationship + "]-(w:" + node_type_2 + "{name:$node_value_2}) " \
"DELETE u;"
... | [
"def delete_node(self, node):",
"def delete(self, node):\n pass",
"def _delete(self):\n\n if not self.node_exists:\n return\n\n for association in self.node._pg_edges:\n setattr(self.node, association, [])\n\n self.transaction.session.delete(self.node)",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalizes value to a specified new range by supplying the current range. | def normalizeToRange(value, minVal, maxVal, newMin, newMax, clip=False):
value = float(value)
minVal = float(minVal)
maxVal = float(maxVal)
newMin = float(newMin)
newMax = float(newMax)
if clip:
return np.clip((newMax - newMin) / (maxVal - minVal) * (value - maxVal) + newMax, newMin, ne... | [
"def __normalize(self, value, lower_bound, upper_bound):\n\n min_max_diff = self.max - self.min\n bound_diff = upper_bound - lower_bound\n return (value - self.min) / min_max_diff * bound_diff + lower_bound",
"def _range_normalize(vector, lower=None, upper=None):\n\n if lower is None:\n l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the tight bounding box of a binary mask. | def mask_to_bbox(mask):
xs = np.where(np.sum(mask, axis=0) > 0)[0]
ys = np.where(np.sum(mask, axis=1) > 0)[0]
if len(xs) == 0 or len(ys) == 0:
return None
x0 = xs[0]
x1 = xs[-1]
y0 = ys[0]
y1 = ys[-1]
return np.array((x0, y0, x1, y1), dtype=np.float32) | [
"def binary_mask_to_bbox(binary_mask, tolerance=0):\n # get columns and rows that contain 1s\n rows = np.any(binary_mask, axis=1)\n cols = np.any(binary_mask, axis=0)\n\n # Find the min and max col/row index that contain 1s\n row_min, row_max = np.where(rows)[0][[0, -1]]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert from the COCO polygon segmentation format to a binary mask encoded as a 2D array of data type numpy.float32. The polygon segmentation is understood to be enclosed in the given box and rasterized to an M x M mask. The resulting mask is therefore of shape (M, M). | def polys_to_mask_wrt_box(polygons, box, M):
w = box[2] - box[0]
h = box[3] - box[1]
w = np.maximum(w, 1)
h = np.maximum(h, 1)
polygons_norm = []
for poly in polygons:
p = np.array(poly, dtype=np.float32)
p[0::2] = (p[0::2] - box[0]) * M / w
p[1::2] = (p[1::2] - box[1])... | [
"def get_mask(box, shape):\n tmp_mask = np.zeros(shape, dtype=\"uint8\")\n tmp = np.array(box, dtype=np.int32).reshape(-1, 2)\n cv2.fillPoly(tmp_mask, [tmp], 255)\n# tmp_mask=cv2.bitwise_and(tmp_mask,mask)\n return tmp_mask, cv2.countNonZero(tmp_mask)",
"def binary_mask_to_polygon(binary_mask, tol... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs greedy nonmaximum suppression based on an overlap measurement between masks. The type of measurement is determined by `mode` and can be either 'IOU' (standard intersection over union) or 'IOMA' (intersection over mininum area). | def rle_mask_nms(masks, dets, thresh, mode='IOU'):
if len(masks) == 0:
return []
if len(masks) == 1:
return [0]
if mode == 'IOU':
# Computes ious[m1, m2] = area(intersect(m1, m2)) / area(union(m1, m2))
all_not_crowds = [False] * len(masks)
ious = mask_util.iou(masks,... | [
"def box_non_maximum_suppression(data=None, overlap_thresh=_Null, topk=_Null, coord_start=_Null, score_index=_Null, id_index=_Null, force_suppress=_Null, in_format=_Null, out_format=_Null, out=None, name=None, **kwargs):\n return (0,)",
"def _greedy_nms(predictions, iou_threshold=0.45, coords='corners', border... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the bounding box of each mask in a list of RLE encoded masks. | def rle_masks_to_boxes(masks):
if len(masks) == 0:
return []
decoded_masks = [
np.array(mask_util.decode(rle), dtype=np.float32) for rle in masks
]
def get_bounds(flat_mask):
inds = np.where(flat_mask > 0)[0]
return inds.min(), inds.max()
boxes = np.zeros((len(deco... | [
"def rle_maskes_to_boxes(masks):\n\n\n decoded_masks = [\n np.array(maskUtils.decode(rle), dtype=np.float32) for rle in masks\n ]\n # pdb.set_trace()\n def get_bounds(flat_mask):\n inds = np.where(flat_mask > 0)[0]\n return inds.min(), inds.max()\n\n boxes = np.zeros((len(decoded... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Home redirects to /register | def home_page():
return redirect('/register') | [
"def home_page():\n return redirect ('/register')",
"def homepage():\n\n return redirect(\"/register\")",
"def rediect_register():\n return redirect(\"/register\")",
"def home_page():\n\n return redirect(\"/users\")",
"def home_page():\n return redirect('/users')",
"def register_page(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add feedback for a user | def add_feedback(username):
if 'username' in session:
form = FeedbackForm()
if form.validate_on_submit():
feedback_data = generate_feedback_data(form, username)
new_feedback = Feedback.make_feedback(feedback_data)
db.session.add(new_feedback)
db.sessio... | [
"def show_add_feedback(username):\n\n if \"username\" not in session or username != session['username']:\n flash(\"You do not have permission to view this content.\")\n return redirect(\"/\")\n else:\n form = AddFeedbackForm()\n \n \n \n if form.validate_on_submit():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete feedback and return to user page | def delete_feedback(feedback_id):
if 'username' in session:
# Get username
username = session['username']
# Remove feedback
Feedback.query.filter_by(id=feedback_id).delete()
db.session.commit()
flash('Feedback Deleted!', 'success')
return redirect(f'/users... | [
"def delete_users_feedback(username):\r\n if check_session_status(username) != \"authorized\":\r\n message = common_flashes(check_session_status(username)[0])\r\n flash(message[0],message[1])\r\n return redirect(check_session_status(username)[1])\r\n else:\r\n fb_id = request.form[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays a custom error page when returning a 404 error | def display_404(error):
return render_template('/error.html'), 404 | [
"def error404(self):\n self.render('404.html')",
"def show_404(error):\n return render_template('error_page.html', message = \"This page has melted in the sun\", button = \"Back to Home\"), 404",
"def error_404(error):\n return '404 Error'",
"def error_404(error):\n return 'Sorry, Nothing at thi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a clone of the specified volume. | def create_cloned_volume(self, vol, src_vref):
self.authenticate_user()
name = self._get_volume_name(vol)
srcname = self._get_vipr_volume_name(src_vref)
number_of_volumes = 1
try:
if(src_vref['consistencygroup_id']):
raise vipr_utils.SOSError(
... | [
"def create_cloned_volume(self, volume, src_vref):\n self.common.create_cloned_volume(volume, src_vref)\n self.common.set_volume_tags(volume, ['_obj_volume_type'])",
"def create_cloned_volume(self, volume, src_vref):\n return",
"def create_cloned_volume(self, volume, src_vref):\n LOG... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
expands the volume to new_size specified. | def expand_volume(self, vol, new_size):
self.authenticate_user()
volume_name = self._get_vipr_volume_name(vol)
size_in_bytes = vipr_utils.to_bytes(str(new_size) + "G")
try:
self.volume_obj.expand(
self.configuration.vipr_tenant +
"/" +
... | [
"def extend_volume(self, volume, new_size):",
"def extend_volume(self, volume, new_size):\n spdk_name = self._get_spdk_volume_name(volume.name)\n params = {'name': spdk_name, 'size': new_size * units.Gi}\n self._rpc_call('bdev_lvol_resize', params)",
"def extend_volume(self, volume, new_siz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates volume from given snapshot ( snapshot clone to volume ). | def create_volume_from_snapshot(self, snapshot, volume, volume_db):
self.authenticate_user()
if self.configuration.vipr_emulate_snapshot == 'True':
self.create_cloned_volume(volume, snapshot)
return
ctxt = context.get_admin_context()
src_snapshot_name = None
... | [
"def create_volume_from_snapshot(self, volume, snapshot):\n self.client.clone(snapshot.volume_name, snapshot.name,\n volume.name, volume.size)",
"def create_volume_from_snapshot(self, volume, snapshot):\n return",
"def create_volume_from_snapshot(self, volume, snapshot):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the export group to which the given initiator ports are the same as the initiators in the group | def _find_exportgroup(self, initiator_ports):
foundgroupname = None
grouplist = self.exportgroup_obj.exportgroup_list(
self.configuration.vipr_project,
self.configuration.vipr_tenant)
for groupid in grouplist:
groupdetails = self.exportgroup_obj.exportgroup_sh... | [
"def test_get_port_group_list(self):\n pass",
"def _get_dvs_uplink_portgroup(dvs, portgroup_name):\n for portgroup in dvs.portgroup:\n if portgroup.name == portgroup_name:\n return portgroup\n\n return None",
"def _find_matching_ports(i, j):\n\n i_ports = i.available_ports()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
changes the vpool type | def retype(self, ctxt, volume, new_type, diff, host):
self.authenticate_user()
volume_name = self._get_vipr_volume_name(volume)
vpool_name = new_type['extra_specs']['ViPR:VPOOL']
try:
task = self.volume_obj.update(
self.configuration.vipr_tenant +
... | [
"def instance_vnictype(self, instance_vnictype):\n self._instance_vnictype = instance_vnictype",
"def update_vswitch_type(self, context):\n LOG.info(\"update_vswitch_type\")\n\n personalities = [constants.CONTROLLER]\n config_dict = {\n \"personalities\": personalities,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Will itterate through data to find the index of the oldest and youngest people. | def find_people(data):
youngest_idx = 0
oldest_idx = 0
for index, item in enumerate(data):
if item['age'] < data[youngest_idx]['age'] and item['age'] > 0:
youngest_idx = index
if item['age'] > data[oldest_idx]['age'] and item['age'] < 80:
oldest_idx = index
retur... | [
"def oldest_and_youngest():\n import json\n with open('forbes_billionaires_2016.json') as json_data:\n billionaires = json.load(json_data)\n oldest = None\n youngest = None\n for each in billionaires:\n if oldest is None:\n oldest = each\n if youngest is None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collapses a directed multigraph into a networkx directed graph. In the output directed graph, each node is a number, which contains itself as node_data['node'], while each edge contains a list of the data from the original edges as its attribute (edge_data[0...N]). | def collapse_multigraph_to_nx(graph: Union[gr.MultiDiGraph, gr.OrderedMultiDiGraph]) -> nx.DiGraph:
# Create the digraph nodes.
digraph_nodes: List[Tuple[int, Dict[str, nd.Node]]] = ([None] * graph.number_of_nodes())
node_id = {}
for i, node in enumerate(graph.nodes()):
digraph_nodes[i] = (i, {... | [
"def flatten_graph_data(graph):\n g = nx.MultiDiGraph(**graph.graph)\n\n for node, data in graph.nodes(data=True):\n g.add_node(node, data)\n\n for u, v, key, data in graph.edges(data=True, keys=True):\n g.add_edge(u, v, key=key, attr_dict=flatten_dict(data))\n\n return g",
"def to_netwo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether `node_a` is an instance of the same type as `node_b`, or if either `node_a`/`node_b` is a type and the other is an instance of that type. This is used in subgraph matching to allow the subgraph pattern to be either a graph of instantiated nodes, or node types. | def type_or_class_match(node_a, node_b):
if isinstance(node_b['node'], type):
return issubclass(type(node_a['node']), node_b['node'])
elif isinstance(node_a['node'], type):
return issubclass(type(node_b['node']), node_a['node'])
elif isinstance(node_b['node'], xf.PatternNode):
return... | [
"def same_type(one, two):\n\n return isinstance(one, type(two))",
"def do_types_match(type_a: Type[Any], type_b: Type[Any]) -> bool:\n # TODO [ENG-158]: Check more complicated cases where type_a can be a sub-type\n # of type_b\n return type_a == type_b",
"def sametype(variable1, variable2):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function that tries to instantiate a pattern match into a transformation object. | def _try_to_match_transformation(graph: Union[SDFG, SDFGState], collapsed_graph: nx.DiGraph, subgraph: Dict[int, int],
sdfg: SDFG, xform: Union[xf.PatternTransformation, Type[xf.PatternTransformation]],
expr_idx: int, nxpattern: nx.DiGraph, state_id: int... | [
"def fromPattern(pat: ghidra.app.plugin.processors.sleigh.pattern.DisjointPattern, minLen: int, description: unicode) -> ghidra.app.plugin.assembler.sleigh.sem.AssemblyResolvedConstructor:\n ...",
"def from_regex(cls, regexMatch):\n raise NotImplementedError(\"fromRegex was not implemented\")",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a generator of Transformations that match the input SDFG. Ordered by SDFG ID. | def match_patterns(sdfg: SDFG,
patterns: Union[Type[xf.PatternTransformation], List[Type[xf.PatternTransformation]]],
node_match: Callable[[Any, Any], bool] = type_match,
edge_match: Optional[Callable[[Any, Any], bool]] = None,
permissive: bool... | [
"def tss_generator(gtf):\n\tfor transcript in db.features_of_type('transcript'):\n\t\tyield TSS(asinterval(transcript), upstream=1000, downstream=1000)",
"def get_bfs_seq(G, start_id):\n successors_dict = dict(nx.bfs_successors(G, start_id))\n start = [start_id]\n output = [start_id]\n while len(start... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dwell Time Compute the dwell time for the given symbolic, 1d time series. | def dwell_time(x):
data = x
symbols = np.unique(data)
dwell = {}
dwell_mean = {}
dwell_std = {}
for symbol in symbols:
r = np.where(data == symbol)[0]
r_diff = np.diff(r)
r_diff_without_one = np.where(r_diff != 1)
x = r[r_diff_without_one]
segments = le... | [
"def time_time_step():\n\treturn dsslib.SolutionF(ctypes.c_int32(27), ctypes.c_double(0))",
"def td(days):\n return (days*60.*24.)/timestepM",
"def solve_TDSE(params, wavefunction_initial):\n\n # Initilise density\n density = np.zeros((params.Ntime,params.Nspace))\n density[0,:] = calculate_density_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the URL and directory, download the image page's html for parsing. Parse the full html to find the important bit concerning the image's actual host location but looking in the 'leftside' content div wrapper. Extract the image name and description to be used as the image's name. Download the image and save to the ... | def get_image_qm(html_src, todir):
#print url
img_url, title = img_details(html_src)
r = requests.get(img_url)
with open(todir+title+'.jpg','wb') as f:
f.write(r.content) | [
"def main(url, out_folder=\"/test/\"):\n soup = bs(urlopen(url),features='html.parser')\n parsed = list(urlparse(url))\n\n for image in soup.findAll(\"img\"):\n print(\"Image: %(src)s\" % image)\n image_url = urljoin(url, image['src'])\n filename = image[\"src\"].split(\"/\")[-1]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add vectors to table Should be implemented | def add_vectors(self, table_name, records, ids, timeout, **kwargs):
_abstract() | [
"def register_vectors(self, vectors):\n\n self.vectors.extend(vectors)",
"def add_vectors(self, vectors):\n for v in vectors:\n self.add_v(v)",
"def add_vector(db, vec):\n # type: (FFQramDb, List[complex]) -> None\n import numpy as np\n vector = np.asarray(vec)\n l2_norm = n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query vectors in a table Should be implemented | def search_vectors(self, table_name, top_k, nprobe, query_records, query_ranges, **kwargs):
_abstract() | [
"def _contract_vector_values(columns, datatypes, rows):\n for row in rows:\n contracted_row = list()\n temp_vec = list() # collect the elements of the vectors here\n vector_datatype = None\n\n # iterate over the columns and look for vector columns\n for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query vectors in a table, query vector in specified files Should be implemented | def search_vectors_in_files(self, table_name, file_ids, query_records,
top_k, nprobe, query_ranges, **kwargs):
_abstract() | [
"def search_vectors(self, table_name, top_k, nprobe, query_records, query_ranges, **kwargs):\n _abstract()",
"def bulk_get_vector(self, vec_ids):\n pass",
"def myhtable_index_search(files, index, terms):\n # set_file = set(files)\n # for term in terms:\n # set_file = set_file.intersec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide server version should be implemented | def server_version(self, timeout):
_abstract() | [
"def server_version(self) -> Any:\n return pulumi.get(self, \"server_version\")",
"def server_version(self):\n resp = self._message(b\"host:version\")\n return int(resp, 16)",
"def get_server_version(self):\n return self.__aceQLHttpApi.get_server_version()",
"def get_server_version... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get latitude and longitude from cities in data. | def get_lat_lon(data):
from time import sleep
from geopy import geocoders
from geopy.exc import GeocoderTimedOut
gn = geocoders.GeoNames(username='foobar')
cities = get_cities(data).keys()
coords = {}
for city in cities:
while True:
try:
loc = gn.geocod... | [
"def city_coords(city):\n return (float(city['latitude']), float(city['longitude']))",
"def get_city_coordinates(city):\n from geopy.geocoders import Nominatim\n geolocator =Nominatim(user_agent='meteogram')\n loc = geolocator.geocode(city)\n return(loc.longitude, loc.latitude)",
"def GetCities(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluate the MNIST model | def evaluate(model, iterations, use_cuda=False):
logger.debug("Allocating input and target tensors on GPU : %r", use_cuda)
# create the instance of data loader
data_loader = DataLoaderMnist(cuda=use_cuda, seed=1, shuffle=False, train_batch_size=64, test_batch_size=100)
model.eval()
total = 0
... | [
"def test_model_MNIST(model : neural_network.NeuralNetwork, dataset) -> (float, list):\n print(\"Testing Neural Network on MNIST Test Dataset\")\n total = 10000\n correct = 0\n incorrect_indices = []\n for i in range(10000):\n num = test_single_image_MINST(i, model, dataset)\n if num ==... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function returns a dataframe containing all the FOVs available on LabKey for a particular cell line. | def query_data_from_labkey(cell_line_id):
# Query for labkey data
db = LabKey(contexts.PROD)
# Get production data for cell line
data = db.dataset.get_pipeline_4_production_cells([("CellLine", cell_line_id)])
data = pd.DataFrame(data)
# Because we are querying the `cells` dataset and not the ... | [
"def get_camfiber_table(date, exp_id):\n filename = '/exposures/nightwatch/{}/{:08d}/qa-{:08d}.fits'.format(date, exp_id, exp_id)\n\n tab = None\n if os.path.isfile(filename):\n tab = Table.read(filename, hdu='PER_CAMFIBER')\n tab = tab['FIBER', 'MEDIAN_CALIB_SNR', 'CAM']\n return tab",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks the OS and fixes filepaths for Mac. Mac users should have created a "data" directory in the repo and mounted | def fix_filepaths(df):
if platform in ["linux", "linux2", "darwin"]:
pass
else:
raise NotImplementedError(
"OSes other than Linux and Mac are currently not supported."
)
return df | [
"def check_os():\n\n if platform.system() != \"Darwin\":\n print \"This script only works on macos system\"\n exit(1)",
"def is_mac():\n return guess_os() == 'macosx'",
"def os_is_mac():\n return platform.system() == \"Darwin\"",
"def check_os_and_set_find():\n logger.debug(\"Perform... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function returns a cropped area around an object of interest given the raw data and its corresponding segmentation. | def crop_object(raw, seg, obj_label, isotropic=None):
offset = 16
raw = np.pad(raw, ((0, 0), (offset, offset), (offset, offset)), "constant")
seg = np.pad(seg, ((0, 0), (offset, offset), (offset, offset)), "constant")
_, y, x = np.where(seg == obj_label)
if x.shape[0] > 0:
xmin = x.min()... | [
"def cut(img, left, above, right, down):\n box = (left, above, right, down)\n region = img.crop(box)\n return region",
"def get_cropped_image(self) -> np.ndarray:\n points = self.get_bound_box_points()\n return self.__image__[points[2]:points[3], points[0]:points[1]]",
"def crop_image(ima... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an existing AdminRoleCustom resource's state with the given name, id, and optional extra properties used to qualify the lookup. | def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
description: Optional[pulumi.Input[str]] = None,
label: Optional[pulumi.Input[str]] = None,
permissions: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = Non... | [
"def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n domain_id: Optional[pulumi.Input[str]] = None,\n name: Optional[pulumi.Input[str]] = None,\n region: Optional[pulumi.Input[str]] = None) -> 'Role':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check wether loss is NaN | def _check_loss(self, loss):
assert not np.isnan(loss), "Model diverged with loss = NaN" | [
"def assert_no_nans(x):\n assert not torch.isnan(x).any()",
"def is_nan(tensor: Tensor) -> bool:\n return torch.isnan(tensor).any()",
"def is_nan():\n return IsNan()",
"def contains_nan(w):\n\n return tf.reduce_all(tf.is_nan(w))",
"def pd_isnan(val):\n return val is None or val != val",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add weight decay to the variable | def _add_weight_decay(self, var, wd):
wd_loss = tf.multiply(tf.nn.l2_loss(var),
wd,
name='weight_loss')
tf.add_to_collection(GKeys.LOSSES, wd_loss) | [
"def add_weight_decay(model, weight_decay):\n if weight_decay <= 0.0:\n return\n wd = model.param_init_net.ConstantFill(\n [], 'wd', shape=[1], value=weight_decay\n )\n ONE = model.param_init_net.ConstantFill([], \"ONE\", shape=[1], value=1.0)\n for param in _get_weights(model):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |