query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Test case for team_builder_config_product_groups_id_exists_get Check whether a model instance exists in the data source. | def test_team_builder_config_product_groups_id_exists_get(self):
pass | [
"def test_team_builder_config_product_groups_find_one_get(self):\n pass",
"def test_team_builder_config_product_groups_id_get(self):\n pass",
"def test_team_builder_config_product_groups_id_product_group_get(self):\n pass",
"def test_team_builder_config_product_groups_id_builder_config_ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for team_builder_config_product_groups_id_get Find a model instance by {{id}} from the data source. | def test_team_builder_config_product_groups_id_get(self):
pass | [
"def test_team_builder_config_product_groups_id_product_group_get(self):\n pass",
"def test_team_builder_config_product_groups_find_one_get(self):\n pass",
"def test_team_builder_config_product_groups_id_exists_get(self):\n pass",
"def test_team_builder_config_product_groups_id_builder_co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for team_builder_config_product_groups_id_head Check whether a model instance exists in the data source. | def test_team_builder_config_product_groups_id_head(self):
pass | [
"def test_team_builder_config_product_groups_id_exists_get(self):\n pass",
"def test_team_builder_config_product_groups_find_one_get(self):\n pass",
"def test_team_builder_config_product_groups_id_get(self):\n pass",
"def test_team_builder_config_product_groups_id_product_group_get(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for team_builder_config_product_groups_id_patch Patch attributes for a model instance and persist it into the data source. | def test_team_builder_config_product_groups_id_patch(self):
pass | [
"def test_team_builder_config_product_groups_id_put(self):\n pass",
"def test_team_builder_config_product_groups_id_replace_post(self):\n pass",
"def test_team_builder_config_product_groups_post(self):\n pass",
"def test_team_builder_config_product_groups_id_get(self):\n pass",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for team_builder_config_product_groups_id_product_group_get Fetches belongsTo relation productGroup. | def test_team_builder_config_product_groups_id_product_group_get(self):
pass | [
"def test_team_builder_config_product_groups_id_get(self):\n pass",
"def test_team_builder_config_product_groups_find_one_get(self):\n pass",
"def test_team_builder_config_product_groups_get(self):\n pass",
"def test_team_builder_config_product_groups_id_builder_config_get(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for team_builder_config_product_groups_id_put Replace attributes for a model instance and persist it into the data source. | def test_team_builder_config_product_groups_id_put(self):
pass | [
"def test_team_builder_config_product_groups_id_replace_post(self):\n pass",
"def test_team_builder_config_product_groups_id_patch(self):\n pass",
"def test_put_groups_id(self):\n pass",
"def test_team_builder_config_product_groups_post(self):\n pass",
"def test_team_builder_conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for team_builder_config_product_groups_id_replace_post Replace attributes for a model instance and persist it into the data source. | def test_team_builder_config_product_groups_id_replace_post(self):
pass | [
"def test_team_builder_config_product_groups_id_put(self):\n pass",
"def test_team_builder_config_product_groups_id_patch(self):\n pass",
"def test_team_builder_config_product_groups_post(self):\n pass",
"def test_team_builder_config_product_groups_id_delete(self):\n pass",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for team_builder_config_product_groups_post Create a new instance of the model and persist it into the data source. | def test_team_builder_config_product_groups_post(self):
pass | [
"def test_team_builder_config_product_groups_id_put(self):\n pass",
"def test_team_builder_config_product_groups_id_replace_post(self):\n pass",
"def test_team_builder_config_product_groups_change_stream_post(self):\n pass",
"def test_team_builder_config_product_groups_id_patch(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds all integers multiples. | def find_multiples(integer, limit):
return [x for x in range(1, limit + 1) if x % integer == 0] | [
"def get_all_multiples(n):\n i = 0\n multiple_list = []\n for i in range(n):\n if is_multiple_of_3(i) | is_multiple_of_5(i):\n multiple_list.append(i)\n return multiple_list",
"def filter_multiples(\n mult: _Iterable[int],\n xs: _Iterable[int]\n ) -> _Iterable[in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate list of dicts. Where each dict contain 1 pair of key/value key letter from alphabet value random int value from 0 to 100 | def generate_alphabet() -> Alphabet:
alpha = []
for letter in string.ascii_lowercase:
alpha.append(dict([(letter, random.randint(0, 100))]))
return alpha | [
"def generate_dictionary(num_lists):\n dictionary = {}\n for i in range(num_lists):\n dictionary[i] = random.sample(range(8), 8)\n\n return dictionary",
"def make_cipher_dict(alphabet):\n L = list(string.ascii_lowercase)\n new_cipher_dict = {}\n for i in alphabet:\n random.shuffle(L)\n ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a UUUID by searching for a realname | def get_user_by_realname(rn):
# try to return the requested user
try:
users.execute('''
SELECT UUUID FROM users WHERE realname=?;
''',(rn,)
)
return users.fetchall()
except BaseException as e:
print(e)
print("A fatal error occured while selecting the requested user")
return 500 | [
"def read_uuid(node):\n muuid = cmds.ls(node, uuid=True)\n if not len(muuid):\n raise RuntimeError(\"Node not found.\")\n elif len(muuid) > 1:\n raise RuntimeError(\"Found more then one node, use long name.\")\n\n return muuid[0]",
"def udn_from_usn(usn: str, device_type: str):\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set a single attribute of a user | def set_user_attr(u,attr,val):
# sanity check the attribute we were asked to set
if attr not in users_schema:
print("That attribute does not exist!")
return 400
# try to set the value
try:
users.execute('''
UPDATE users
SET '''+attr+'''=?
WHERE UUUID=?;
''',(val,u)
#| doing string catenati... | [
"def edit_user(self, user: User, attribute: dict[str, Any]) -> None:\n\t\tpass",
"def set_attr(self, user, key, value):\n query1 = \"\"\"SELECT attr_value FROM attributes WHERE attr_uid = ?\n AND attr_key = ?\"\"\"\n query2 = \"INSERT INTO attributes VALUES (?, ?, ?)\"\n qu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if uuid pool exists | def uuid_pool_exists(handle, name=None,
org_dn="org-root", **kwargs):
try:
mo = uuid_pool_get(handle=handle, name=name, org_dn=org_dn,
caller="uuid_pool_exists")
except UcsOperationError:
return (False, None)
mo_exists = mo.check_prop_match(**... | [
"def check_for_pool(host, uuid):\n pool_dir = \"/mnt/daos/{}\".format(uuid)\n result = check_file_exists(host, pool_dir, directory=True, sudo=True)\n if result[0]:\n print(\"{} exists on {}\".format(pool_dir, host))\n else:\n print(\"{} does not exist on {}\".format(pool_dir, host))\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates block of uuid addresses | def uuid_block_create(handle, pool_name=None, org_dn="org-root",
start_uuid=None, end_uuid=None,
**kwargs):
obj = handle.query_dn(org_dn)
dn = org_dn + "/uuid-pool-" + pool_name
pool = handle.query_dn(dn)
if not obj:
raise UcsOperationError("uuid_bloc... | [
"def _create_address_list():\n if len(admin.get_model(model='address', _filter='merchant_id', value=user1.merchant1.id)) < 5:\n print('Start creating list address. ')\n user1.merchant1.address_create(params={'in_curr': 'BTC', 'out_curr': None, 'comment': None})\n user1.merchant1.address_crea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if uuid block exists | def uuid_block_exists(handle, pool_name, org_dn="org-root", start_uuid=None,
end_uuid=None, **kwargs):
try:
mo = uuid_block_get(handle=handle, pool_name=pool_name, org_dn=org_dn,
start_uuid=start_uuid, end_uuid=end_uuid,
caller="... | [
"def test_non_existing_uuid(self):\n\n jsmith = api.add_identity(self.ctx, 'scm', email='jsmith@example')\n\n client = graphene.test.Client(schema)\n\n params = {\n 'uuid': 'FFFFFFFFFFFFFFF',\n }\n executed = client.execute(self.SH_UNLOCK_INDIVIDUAL,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
plots only the influntial users. | def influential_users_slot(self, coords, users):
influential_coordinates = []
for index, user in enumerate(users):
# Get the distance from the influential and uninfluential centroid
influential_dist, uninfluential_dit = self._get_distances_helper(user)
# if closer to... | [
"def userplot(user_place):\n\tname=str(data[user_place][\"name\"])\n\n\tindex=data[user_place][\"current_index\"]\n\tresponselist=data[user_place][\"responses\"]\n\tresponselist=list(map(function, responselist))\n\n\tx_list = []\n\tfor i in range(1, index+1):\n\t\tx_list.append(i)\n\n\tplt.plot(x_list, responselist... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if we want to optimize our python code we need to write the code in a way that we could run it in the less time as possible To do this we need to use the IPython builtin command "%timeit" One advantage in using %timeit is that it provides an average of timing statistics. Also %timeit needs to be runned outside this fun... | def runtime_example1():
# this need to be runned outside of this function
%timeit rand_nums = np.random.rand(1000)
# here we save the runtime to a variable using "-o" after
# the %timeit clause
times = %timeit -o rand_nums = np.random.rand(1000)
return times | [
"def timeit(get_ipython, fn, *args, **kwargs):\n timeit_result = get_ipython().run_line_magic(\n \"timeit\", \"-o -q fn(*args, **kwargs)\"\n )\n return timeit_result",
"def time_optimization(self, interface):\n hyperparams = {\"interface\": interface}\n benchmark_optimization(hyperpa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a string to drops. A drop is the smallest unit in the Ripple currency (0.000001 XRP) | def drop(drops):
if not drops.isdigit():
raise ValueError(
'Value must be a positive integer: {drops}'.format(
drops=drops,
)
)
# Python will automatically cast to a long integer for any x such
# that x < -sys.maxint-1 or x > sys.maxint
drops = int... | [
"def remove_money_symbols(string):\n string = string.replace('$', '')\n return float(string[1:])",
"def parse_money(string):\n return float(string[1:])",
"def _parse_dropout_string(dropout_str):\n dropout_values = []\n parts = dropout_str.strip().split(',')\n\n try:\n if len(parts) < 2:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Commands for handling the RPBridge. | async def rpb(self, ctx):
pass | [
"def handler(self, sub_command, args):\n pass",
"def _process_command(self):\n raise DriverLaunchException(\"_process_command must be overloaded\")",
"def run_commands(config):\n c = Client(config)\n\n print \"\\n=> Registering client using register_site()\"\n oxd_id = c.register_site()\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete the message ID from the channel and the search database. Good for accidental leaks of GM secrets. | async def remove(self, ctx, message_id):
self.db.remove(self.search.message == int(message_id))
message = await ctx.channel.fetch_message(int(message_id))
await message.delete()
await ctx.message.add_reaction("👍") | [
"def channel_message_delete(channel_message_id):\n if not current_user.is_authenticated:\n return {'errors': ['Unauthorized']}\n\n channel_message = ChannelMessage.query.get(channel_message_id)\n db.session.delete(channel_message)\n db.session.commit()\n\n return {'channel_message':channel_mes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search the database by campaign and bycharacter. Alternative to Discord search which can't handle webhook author. | async def search(self, ctx, campaign, user, *, contents):
results = self.db.search((self.search.doctype == "rpbridge") &
(self.search.user == user) &
(self.search.campaign == campaign))
results_formatted = ""
embed = Embed(title="... | [
"def search():\n channel_schema = ChannelSchema() # Read the marshmallow above\n q = request.args.get(\"q\") \n qTokens = nltk.word_tokenize(q) # Extract all the word\n queryInput = '%'.join(qTokens) + '%' # Join them with * in between and at the end. For example, \"ac ri\" will become ac*ri*\n\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/embed POST This is called by the REST API to send embeds. Embeds are handled separately because they are not logged. The input argument is a json object cast to a dict by the webserver. It must contain all the fields that _send messages must. In addition, it must contain a nested object called embed. Embed must contai... | async def _embed(self, json):
campaign_entry = self.db.search((self.search.doctype == "campaigns") &
(self.search.campaign
== json["campaign"]))
campaign_entry = campaign_entry[0]
if not campaign_entry:
r... | [
"async def embed_post(self, ctx, embed_id, channel: TextChannel = None):\n try:\n embed = self.EmbedDB.query_one(id=embed_id)\n message = await embed.post(channel.id if channel else None)\n await ctx.send('Embed Posted ' + message.jump_url)\n except (ModelError, DBErro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Commands for handling the Campaigns. | async def campaign(self, ctx):
pass | [
"def test_get_ad_campaigns(self):\n pass",
"def test_admin_campaign_view_list(self):\n response = self.client.get('/admin/dialer_campaign/campaign/')\n self.failUnlessEqual(response.status_code, 200)",
"def send(self):\n result = self.client.campaigns.actions.send(self.campaign['id']... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a campaign and all its messages from the search tool. You must delete the channel's messages yourself. | async def delete(self, ctx, campaign: str):
webhook = self.db.search((self.search.doctype == "campaign") &
(self.search.campaign == campaign))
webhooky = await self.bot.fetch_webhook(webhook[0]["webhook"])
await webhooky.delete()
self.db.remove((self.sear... | [
"def clear_recent_campaigns(self):\n campaign_paths = self.qsettings.remove('recentCampaigns/paths')\n campaign_titles = self.qsettings.remove('recentCampaigns/titles')\n self.update_recent_campaigns()",
"async def remove(self, ctx, channel: discord.TextChannel, *messages: str):\r\n fa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new campaign. The campaign with the matching Title given will post here. | async def add(self, ctx, campaign: str):
new_webhook = await ctx.channel.create_webhook(
name=f"FVTT Bridge - {campaign}")
self.db.insert({"doctype": "campaign",
"campaign": campaign,
"channel": ctx.channel.id,
"webhook"... | [
"def add_campaign(self, name=\"\", tags=[], description=\"\", **kwargs):\n return self.__entity_add(\n name=name,\n entity_type=\"campaign\",\n tags=tags,\n description=description,\n **kwargs\n )",
"def insert(self, campaign):\n self.que... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves a campaign to the channel you use this command in. | async def move(self, ctx, campaign: str):
webhook = self.db.search((self.search.doctype == "campaigns") &
(self.search.campaign == campaign))
webhooky = await self.bot.fetch_webhook(webhook[0]["webhook"])
await webhooky.delete()
new_webhook = ctx.channel.... | [
"async def campaign(self, ctx):\n pass",
"async def move_bot_to_channel(channel_name):\n guild = client.get_guild(GUILD_ID)\n\n channel = discord.utils.get(guild.voice_channels, name=channel_name)\n if channel is None:\n print(f'Cannot move user: Invalid Channel {channel_name}')\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enregistre dans "DateTrie" uniquement les Dates comprises entre la "DateDepart" et "DateDepart" + "Jours" | def TriDates(self, UneDate, DateDepart, Jours):
UneDate = self.ConvertieDate(UneDate)
DateFin = self.ajoutDate(DateDepart, Jours)
if UneDate <= DateFin and UneDate >= DateDepart:
self.DateTrie.append(UneDate)
print("Ajouté !") | [
"def search_date(self):",
"def date_parser():",
"def jdate(njour,s):\n global j\n d=datelundi(s)+timedelta(days=(j.index(njour)))\n return njour+\" \"+str(d.day)+\"/\"+str(d.month)+\"/\"+str(d.year-2000)",
"def check_dates(self,words,entity_tag):\n months=['enero','febrero','marzo','abril','ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process a relation triplet found by ClausIE and store the data | def process_relation_triplet(triplet):
sentence = triplet.subject + ' ' + triplet.predicate + ' ' + triplet.object
# print ("triplet.subject: "+triplet.subject)
# print("triplet.predicate: " + triplet.predicate)
# print("triplet.object: " + triplet.object)
doc = nlp(unicode(sentence))
x=1
... | [
"def process_relation_triplet(triplet):\n #triplet = cl.extract_triples([\"Bob has a dog named Fido.\"])[0]\n sentence = triplet.subject + ' ' + triplet.predicate + ' ' + triplet.object\n doc = nlp(unicode(sentence))\n for t in doc:\n if t.pos_ == 'VERB' and t.head == t:\n root = t\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transforming coordinates between two EPSG codes. | def transform_epsg(from_proj: str, target_proj: str, x1: float, x2: float):
from_proj = Proj('epsg:3857')
target_proj = Proj('epsg:4326')
x1, y1 = -11705274.6374, 4826473.6922
x2, y2 = transform(from_proj, target_proj, x1, y1)
return (x2, y2) | [
"def _reproject(xy, crs1, crs2):\n return crs1.transform(crs2, *xy)",
"def transform_ref_system(lat=0.0, lon=0.0,\n in_proj='EPSG:3006', # SWEREF 99TM 1200\n out_proj='EPSG:4326'):\n o_proj = CRS(out_proj)\n i_proj = CRS(in_proj)\n\n x, y = transform(i_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create two opencv windows with images and titels. | def create_two_windows(
image1: np.ndarray,
image2: np.ndarray,
title1: str = "Left window",
title2: str = "Right window",
) -> None:
cv2.namedWindow(title1, cv2.WINDOW_AUTOSIZE)
cv2.namedWindow(title2, cv2.WINDOW_AUTOSIZE)
cv2.moveWindow(title1, 100, 0)
cv2.moveWindow(title2, 705, 0)
... | [
"def open_display_window(width, height):\n cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)\n cv2.resizeWindow(WINDOW_NAME, width, height)\n cv2.moveWindow(WINDOW_NAME, 0, 0)\n cv2.setWindowTitle(WINDOW_NAME, 'AI-Hygiene-Tracker[ROOM]')",
"def showImage(titleList,imageList):\n for title, image in zi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the msms output of maxquant as pandas dataframe. | def get_msms (self):
try:
self.msms = pd.read_csv(self.msms_data, sep = '\t')
except:
print("Data File %s not found. Make sure you specified the right directory." % self.msms_data) | [
"def frame(self):\n microseconds = np.array(self.results['time']) * 1e6\n return pd.DataFrame(self.results, index=microseconds)",
"def get_data_frame_for_mRMR_method(self):\n values = self.get_feature_values_as_np_array() # *10e+7\n print(max(values))\n df = pd.DataFrame(data=v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the allPeptides output of maxquant as pandas dataframe. | def get_all_peptides (self):
try:
self.all_peptides = pd.read_csv(self.all_peptides_data, sep ='\t')
except:
print("Data File %s not found. Make sure you specified the right directory." % self.all_peptides_data) | [
"def getPbest(self):\n df = pd.DataFrame(np.stack(\n [self.pBest['ch'][nG] for nG in range(self.nGen)]))\n\n df['val'] = [self.pBest['value'][nG] for nG in range(self.nGen)]\n return df",
"def HIGHLIMIT(self) -> pd.DataFrame:\r\n pass",
"def into_pandas(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds ion mobility colums to the maxquant results that are currently loaded. | def annotate_ion_mobility (self, pasef_data):
if hasattr(self, 'all_peptides'):
self.all_peptides['IonMobilityIndexK0'] = pasef_data.scanNumToOneOverK0(1,self.all_peptides['Ion mobility index'])
if hasattr(self, 'evidence'):
self.evidence['IonMobilityIndexK0'] = pasef_data.scanN... | [
"def add_motif_counts(self, list_of_counts):\n self.motif_counts = list_of_counts",
"def calc_disp(self):\r\n self.add_new_channel_zeros('disp_from_strain', \"mm\")\r\n self.channels['disp_from_strain'][\"data\"] = self.channels['avg_strain'][\"data\"] * self.specimen_length\r\n\r\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is being used to send whatsapp messages. It takes a string message and a cell phone number and it returns a link so we can add it to an html page and send the message to that phone number. | def make_link(phone_number: Optional[str], message: Optional[str]) -> str:
link = 'https://api.whatsapp.com/send?'
mydict = {'phone': phone_number, 'text': message}
msglink = link + urlencode(mydict)
return {"link": msglink} | [
"def wbrowsermethod(self, number, msg, morethanone=None, speed=15):\n print(\"[+] Don't touch anything !\\nStarting to send message(s)\")\n if morethanone == None:\n open(\"https://web.whatsapp.com/send?phone={}&text={}&app_absent=1\".format(number, msg))\n sleep(speed)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds the movement to the current position | def add_movement(self, movement):
self.current_slider_pos += movement.distance_delta * self.diameter/2.0
self.current_angle += movement.angle_delta * 360 | [
"def move(self):\n if self.direction == \"n\":\n self.position = (self.position[0]-1, self.position[1])\n\n elif self.direction == \"s\":\n self.position = (self.position[0]+1, self.position[1])\n\n elif self.direction == \"e\":\n self.position = (self.position[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Github's usable emoji. | def get_github_emoji(): # pragma: no cover
try:
resp = requests.get(
'https://api.github.com/emojis',
timeout=30
)
except Exception:
return None
return json.loads(resp.text) | [
"def get_emoji(self, emoji):\n\t\tif emoji == \"?\":\n\t\t\treturn \"\\u2753 \"\n\t\telif emoji == \"i\":\n\t\t\treturn \"\\u2139 \"\n\t\telif emoji == \"ok\":\n\t\t\treturn \"\\u2714 \"\n\t\treturn \"\"",
"def get_full_emoji():\n return settings.raid_full_emoji",
"def get_join_emoji():\n return settings.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the emoji pattern in memory. | def update_emoji(): # pragma: no cover
global RE_EMOJI
global URL_EMOJI
emoji_list = get_github_emoji()
emoji_map = {}
if emoji_list is not None:
for emoji in emoji_list:
url = emoji_list[emoji]
m = RE_ASSET.match(url)
if m:
emoji_map[e... | [
"def update_patterns(self, patterns):\n\t\tpass",
"def pattern(self, pattern):\n\n self.container['pattern'] = pattern",
"def output_pattern(self, pattern):\n self._clear()\n for i, line in enumerate(pattern.split(\"\\n\")):\n # for each row in the given pattern.\n for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update this source file with the latest emoji. | def update_emoji_source(file_name, emoji_map):
if emoji_map:
replacement = None
start = None
end = None
with codecs.open(file_name, 'r', encoding='utf-8') as f:
m = re.match(r'(.*?# --start--\r?\n).*?(# --end--.*)', f.read(), re.DOTALL)
... | [
"async def replace(self, ctx, emoji):\n await ctx.message.channel.send(f\"Reply emoji changed to {emoji}\")\n if '<' in emoji:\n emoji = emoji.split(':')[1]\n with open(\"emoji\", \"wb\") as f:\n f.write(emoji.encode('utf-8'))",
"def update(self, index, new_char):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of anchors per spatial location. | def num_anchors_per_location(self):
return [len(self._scales) * len(self._aspect_ratios)] | [
"def get_number_of_fpp_anchors(self) -> int:\n return int(self.fpp_anchor_inventory.getLinkInventorySize())",
"def getNumAnchors(self) -> \"int\":\n return _coin.ScXMLStateElt_getNumAnchors(self)",
"def getNumAnchors(self) -> \"int\":\n return _coin.ScXMLParallelElt_getNumAnchors(self)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a tiled set of anchors strided along a grid in image space. This op creates a set of anchor boxes by placing a "basis" collection of boxes with userspecified scales and aspect ratios centered at evenly distributed points along a grid. The basis collection is specified via the scale and aspect_ratios arguments. F... | def tile_anchors(grid_height,
grid_width,
scales,
aspect_ratios,
base_anchor_size,
anchor_stride,
anchor_offset):
ratio_sqrts = tf.sqrt(aspect_ratios)
heights = scales / ratio_sqrts * base_anchor_size[0]
widths =... | [
"def generate_anchors(scales, ratios, height, width, anchor_stride):\n\n # Get all combinations of scales and ratios.\n # For example, scales = [32, 64, 128], ratios = [0.5, 1., 2.]\n # n_anchors_per_location = 3 * 3 = 9\n # scales = [32, 64, 128, 32, 64, 128, 32, 64, 128]\n # ratios = [0.5, 0.5, 0.5... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts bbox centersize representation to corners representation. | def _center_size_bbox_to_corners_bbox(centers, sizes):
return tf.concat([centers - .5 * sizes, centers + .5 * sizes], 1) | [
"def center_size_bbox_to_corners_bbox(centers, sizes):\n return tf.concat([centers - .5 * sizes, centers + .5 * sizes], 1)",
"def center_to_corner_box2d(centers, dims, angles=None, origin=0.5):\n # 'length' in kitti format is in x axis.\n # xyz(hwl)(kitti label file)<->xyz(lhw)(camera)<->z(-x)(-y)(wlh)(l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the name and a list of Problem objects associated with the Contest | def getProblems(self) -> tuple:
# Scraping the page
contestPage = requests.get(self.contestURL)
parsedContestPage = BeautifulSoup(contestPage.content, "html.parser")
# Getting the problems(Table -> Div -> List)
contestName = parsedContestPage.find_all(
class_="rtabl... | [
"def getListOfProblems(self):\n return self.__problems",
"def get_svc_problems(self):\n\n return self.make_view_name_request('svcproblems')",
"def get_problem_desc(*args):\n return _ida_problems.get_problem_desc(*args)",
"def extractBugsPerComponent(self):\n print '\\nGenerating classifica... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write all experiments to sfb xml file | def write_toXMLfile(self):
sfbxml = self.sdict['sfbxml']
self._make_sfbxmlfile(sfbxml) | [
"def read_sfbxmlfile(self):\n sfbxml = self.sdict['sfbxml']\n #open elementtree\n try:\n tree = et.parse(sfbxml)\n except:\n #return \"empty\" xml file\n series = et.Element('Series')\n tree = et.ElementTree(series)\n \n serie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read sfb xml file | def read_sfbxmlfile(self):
sfbxml = self.sdict['sfbxml']
#open elementtree
try:
tree = et.parse(sfbxml)
except:
#return "empty" xml file
series = et.Element('Series')
tree = et.ElementTree(series)
series = tree.getroot(... | [
"def read_xml_file(self, xml_fn):\n pass",
"def read_xml_file(self):\r\n\r\n #Find the root of xml tree.\r\n xml_tree = ET.parse(self.xml_file_path + \"pic{}.xml\".format(self.file_index))\r\n root = xml_tree.getroot()\r\n\r\n return root",
"def ScXML_readFile(filename: 'char ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert images in Experiment to jpg | def convert_jpg(self):
for exp in self.exp.itervalues():
if 'convertet_to_jpg' in exp.data.keys():
pass
else:
exp.convert_jpg() | [
"def jpg_to_png(self) -> None:\n for img in os.listdir(self.img_path):\n if os.path.splitext(img)[1] == '.jpg':\n img_path = self.img_path + '/' + img\n frame = cv2.imread(img_path)\n index = int(img.replace('.jpg', ''))\n cv2.imwrite(f'{... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate flame height for every Experiment | def calc_flameHeight(self, nGauss = 2):
for exp in self.exp.itervalues():
if 'flammenhoehe' in exp.data.keys():
pass
else:
exp.calc_flameHeight(nGauss) | [
"def _flame_length(self):\n pass",
"def analyze_initiation_heights(self, flash_type='all', show_plot=True,\n hist_lims=None):\n\n temp_storm = self.get_flash_type(flash_type=flash_type)\n\n fig, ax = plt.subplots(1, 1, figsize=(12, 6))\n\n temp_storm['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries to set to the module the given attributes. | def try_set_attribute(module, attribute_name, attribute_value):
try:
setattr(module, attribute_name, attribute_value)
except AttributeError:
pass | [
"def set_module(self, mod):\n self.module = mod",
"def set_module_info(self, module_id, **kwargs):\n self.module_id = module_id\n # propagate to variants\n for i, _var_ in enumerate(self.variants):\n self.variants[i].module_id = module_id\n for key, value in kwargs.it... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a module from the given spec. | def create_module_from_spec(spec):
module = ModuleType(spec.name)
try_set_attribute(module, '__name__', spec.name)
try_set_attribute(module, '__loader__', spec.loader)
try_set_attribute(module, '__package__', spec.parent)
try_set_attribute(module, '__spec__', spec)
try_set_attribute(module,... | [
"def create_module(self, spec):\n # Opposed to what is defined in PEP-451, this method is not optional.\n # We want the default results, so we simply return None (which is\n # handled for su my the import machinery). See\n # https://bugs.python.org/issue23014 for more information.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start an fteproxy server. Iterate through the FTE formats available to fteproxy. For each format, spawn a client using that format, connect to the fteproxy server and pump data through the connection. Verify the data successfully traversed the client and server, upon success output performance statistics. | def main():
def_dir = os.path.join(fteproxy.conf.getValue('general.defs_dir'))
def_file = fteproxy.conf.getValue('fteproxy.defs.release') + '.json'
def_abspath = os.path.normpath(os.path.join(def_dir, def_file))
print 'Testing formats in', def_abspath
start_server()
languages = fteproxy.defs... | [
"def start_server():\n\n executeCmd(\"./bin/fteproxy --quiet --mode server\"\n + \" --server_ip \" + BIND_IP\n + \" --server_port \" + str(SERVER_PORT)\n + \" --proxy_ip \" + BIND_IP + \" --proxy_port \" + str(PROXY_PORT) + \" &\")\n\n waitForListener(BIND_IP, SERVER_PO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the ``language_name``, start the fteproxy client and pump ``BYTES_TO_SENDTIRALS`` bytes via the fteproxy client and server. | def doTest(language_name):
elapsed = -1
bytesSent = 0
try:
start_client(language_name)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((BIND_IP, PROXY_PORT))
sock.listen(100)
... | [
"def start_client(language_name):\n\n\n executeCmd(\"./bin/fteproxy --quiet --mode client\"\n + \" --upstream-format \" + language_name + \"-request\"\n + \" --downstream-format \" + language_name + \"-response\"\n + \" --client_ip \" + BIND_IP\n + \" --client_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start our fteproxy client, block until it's ready. | def start_client(language_name):
executeCmd("./bin/fteproxy --quiet --mode client"
+ " --upstream-format " + language_name + "-request"
+ " --downstream-format " + language_name + "-response"
+ " --client_ip " + BIND_IP
+ " --client_port " + str(CLIENT_PORT)... | [
"def start(self):\n log.debug(\"Starting client to worker at {}:{}\".format(\n self.hostname, self.port))\n self._client.start()\n self._started = True",
"def start_server():\n\n executeCmd(\"./bin/fteproxy --quiet --mode server\"\n + \" --server_ip \" + BIND_IP\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start our fteproxy server, block until it's ready. | def start_server():
executeCmd("./bin/fteproxy --quiet --mode server"
+ " --server_ip " + BIND_IP
+ " --server_port " + str(SERVER_PORT)
+ " --proxy_ip " + BIND_IP + " --proxy_port " + str(PROXY_PORT) + " &")
waitForListener(BIND_IP, SERVER_PORT) | [
"def start(self):\n server_host = Constants.RPI_IP\n server_port = Constants.WEB_SERVER_PORT # random.randint(10000, 60000)\n new_loop = asyncio.new_event_loop()\n start_server = websockets.serve(self.__send_data, server_host, server_port, loop=new_loop)\n t = threading.Thread(ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop our fteproxy client. | def stop_client():
executeCmd("./bin/fteproxy --quiet --mode client --stop")
time.sleep(1) | [
"def stop_server():\n\n executeCmd(\"./bin/fteproxy --quiet --mode server --stop\")\n\n time.sleep(1)",
"def stop(self):\n if self._proxy_thread is not None:\n if self._proxy_thread.is_alive():\n self._proxy.stop()\n self._proxy_thread.join()\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop our fteproxy server. | def stop_server():
executeCmd("./bin/fteproxy --quiet --mode server --stop")
time.sleep(1) | [
"def stop_client():\n\n executeCmd(\"./bin/fteproxy --quiet --mode client --stop\")\n\n time.sleep(1)",
"def stop_server(self):\n response = requests.post(self._build_url(\"stop\"))\n return response",
"def stop_webserver():\r\n _webserver_do('stop')",
"def stop(self):\n if self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Converts each string in the input Tensor to the specified numeric type. (Note that int32 overflow results in an error while float overflow results in a rounded value.) | def string_to_number(string_tensor, out_type=None, name=None):
result = _op_def_lib.apply_op("StringToNumber", string_tensor=string_tensor,
out_type=out_type, name=name)
return result | [
"def cast_str_to_numeric(values):\n if not (isinstance(values[0], str) or isinstance(values[0], bytes)):\n return numpy.array(values)\n\n if not isinstance(values, numpy.ndarray):\n values = numpy.array(values, dtype=\"U\")\n\n for typ in (int, float, complex):\n try:\n valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move the z stage to the specified position (in microns). | def zMoveTo(self, z):
self.commWithResp("M Z={0:.2f}".format(z * self.um_to_unit)) | [
"def cam_move(self, z_val):\n\n cmds.move(z_val, self.ren_cam, moveZ=True, objectSpace=True, relative=True)\n cmds.refresh(force=True)",
"def moveZ(z, warn=True):\n\t\tpos = position()\n\t\tif warn and (pos.get(Z_AXIS)-z>1.0):\n\t\t\tmsg = \"Move Z axis to %0.3f mm from %0.3f mm?\" % (z, pos.get(Z_A... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
exclude a patient's full path (the patient folder) from further processing if patient has nodules with ratings of more than four raters (which is inconsistent with what the raw data is supposed to comprise, also rater ids appear multiple times on the same nodule in these cases motivating the assumption that the same ra... | def exclude_too_many_ratings(self):
exclude_paths = []
for path in self.paths:
roi_ids = set([ii.split('.')[0].split('_')[-1] for ii in os.listdir(path) if '.nii.gz' in ii])
found = False
for roi_id in roi_ids:
n_raters = len([ii for ii in os.listdir(p... | [
"def _ignorePath(self, name, fullpath, isdir):\r\n # Ignore the metadata and tree cache data when indexing\r\n if name == self._mdFile or name == self._treeFile:\r\n return True\r\n else:\r\n return False",
"def test_3_exclude():\n run_main_and_compare([\"scrapbook_te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
print unique seg and counts of nodule nodule_id of patient pid. | def analyze_lesion(self, pid, nodule_id):
nodule_id = nodule_id.lstrip("0")
nodule_id_paths = [ii for ii in os.listdir(os.path.join(self.cf.raw_data_dir, pid)) if '.nii' in ii]
nodule_id_paths = [ii for ii in nodule_id_paths if ii.split('_')[2].lstrip("0")==nodule_id]
assert len(nodule_i... | [
"def print_unique_fasta_number():\n st = set()\n dgri_samples = [\"dgri_f_wb_r1\", \"dgri_m_wb_r1\", \"dgri_f_wb_r2\", \"dgri_m_wb_r2\"]\n dmel_samples = [\"dmel_f_go_r1\", \"dmel_m_go_r1\", \"dmel_f_wb_r1\", \"dmel_m_wb_r1\"]\n samples = {\"dgri\":dgri_samples, \"dmel\":dmel_samples}\n for dxxx in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
wrapper to multiprocess verification of seglabel pairings. | def verify_seg_label_pairings(self, processes=os.cpu_count()):
pool = Pool(processes=processes)
findings_dfs = pool.map(self.verify_seg_label_pairing, self.paths, chunksize=1)
pool.close()
pool.join()
findings_df = pd.concat(findings_dfs, axis=0)
findings_df.to_pickle(o... | [
"def cross_validate_sequence_segmenter(*args, **kwargs): # real signature unknown; restored from __doc__\n pass",
"def check_ids(seg):\n seg_ids = np.unique(seg)\n max_id = np.max(seg_ids)\n n_ids = len(seg_ids)\n try:\n assert max_id == n_ids-1\n except:\n missing_ids = np.sort(np... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
process patient with merged annotations, i.e., only one final GT per image. save img and seg to npy, rest to metadata. | def produce_merged_gt(self, path, pid, df, img_spacing, img_arr_shape):
final_rois = np.zeros(img_arr_shape, dtype=np.uint8)
patient_mal_labels = []
roi_ids = set([ii.split('.')[0].split('_')[-1] for ii in os.listdir(path) if '.nii.gz' in ii])
rix = 1
for roi_id in roi_ids:
... | [
"def setup_annotations(self):\n sbd_path = self.sbd_path\n target_path = pjoin(self.root, \"SegmentationClass/pre_encoded\")\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n #print ('sbd_path = ', sbd_path)\n path = pjoin(sbd_path, \"dataset/train.txt\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get insights for a users account Include the `since` and `until` parameters with Unix timestamps to define a range. | def getUserInsights(params, since = None, until = None):
endpointParams = dict() # parameter to send to the endpoint
# fields to get back
endpointParams['metric'] = 'follower_count,impressions,profile_views,reach'
endpointParams['period'] = 'day' # period
endpointParams['since'] = since
endpointParams['until']... | [
"def getInstagramImpressions(\n self, since: str = \"\", until: str = \"\", period: str = \"&period=day\", date_preset: str = \"\"\n ) -> json:\n if since is not \"\":\n since = f\"&since={since}\"\n if until is not \"\":\n until = f\"&untill={until}\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that SearchableManager can get appropriate params. | def test_searchable_manager_search_fields(self):
manager = DisplayableManager()
self.assertFalse(manager._search_fields)
manager = DisplayableManager(search_fields={"foo": 10})
self.assertTrue(manager._search_fields) | [
"def test_get_search(self):\n pass",
"def test_api_search_get(self):\n pass",
"def test_search_query(self):\n pass",
"def test_api_v3_search_get(self):\n pass",
"def test_staking_parameters_get(self):\n pass",
"def test_get_search(self):\n GalleryFactory(title='Th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test sending of passwordreset mails and evaluation of the links. | def test_password_reset(self):
self.client.logout()
del mail.outbox[:]
# Go to admin-login, search for reset-link
response = self.client.get("/admin/", follow=True)
self.assertContains(response, u"Forgot password?")
url = re.findall(
b"<a href=[\"']([^'\"]+)[... | [
"def test_password_reset(self):\n data = dict(email=self.reg_data['email'])\n self.reset_password(data=data, code=201,\n msg='Check your email address for new password')",
"def test_password_reset_failure_email(self):\n # Log the user out\n self.client.logout... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the RichTextField gets its widget type correctly from settings, and is able to be overridden in a form's Meta. | def test_richtext_widget(self):
class RichTextModel(models.Model):
text_default = RichTextField()
text_overridden = RichTextField()
form_class = modelform_factory(
RichTextModel,
fields=("text_default", "text_overridden"),
widgets={"text_over... | [
"def test_editor_widgets(self):\r\n form = AlbumAdminForm(instance=self.album)\r\n self.assertTrue(isinstance(form.fields['headline'].widget,\r\n OppsEditor))",
"def test_editor_widgets(self):\r\n form = PostAdminForm(instance=self.post)\r\n self.asser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensures the site selection dropdown appears in the admin. | def test_admin_sites_dropdown(self):
self.client.login(username=self._username, password=self._password)
response = self.client.get("/admin/", follow=True)
set_site_url = reverse("set_site")
# Set site URL shouldn't appear without multiple sites.
self.assertNotContains(response, ... | [
"def select_manage_settings(self):\n self.q(css=self._bounded_selector(\".tab-manage_students\")).first.click()",
"def open_admin_side_menu(self):\n self.click_on_element_by_css(adpl.ADMIN_SIDE_NAVIGATION_MENU)",
"def verify_dropdown_page(self):\n\n logging.info(\"## Verifying Dropdown page... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies that ``BaseDynamicInlineAdmin`` properly adds the ``_order`` field for admins of ``Orderable`` subclasses. | def test_dynamic_inline_admins(self):
request = self._request_factory.get("/admin/")
request.user = self._user
field_admin = FieldAdmin(Form, AdminSite())
fieldsets = field_admin.get_fieldsets(request)
self.assertEqual(fieldsets[0][1]["fields"][-1], "_order")
fields = fie... | [
"def test_admin_inlines(self):\n\n class InlineModelAChild(StackedPolymorphicInline.Child):\n model = InlineModelA\n\n class InlineModelBChild(StackedPolymorphicInline.Child):\n model = InlineModelB\n\n class Inline(StackedPolymorphicInline):\n model = InlineMod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the CSRF cookie is properly set when using nevercache. | def test_csrf_cookie_with_nevercache(self):
# Clear the cached value for cache_installed and initialize nevercache
cache_installed.cache_clear()
initialize_nevercache()
# Test uses an authenticated user as the middleware behavior differs
self.client.login(username=self._usernam... | [
"def test_if_csrf_token_is_used(self):\n if self.csrf_token is None:\n self.skipTest('csrf_token attribute is None')\n resp = self.get_response()\n self.assertIn('csrf_token', resp.context)",
"def ensure_xsrf_token():\n xsrf_token = get_xsrf_token()\n if not xsrf_token:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Content model cannot change after initial save. That's the only time we'll know for certain that the __class__ is the lowest class in the hierarchy. Of course, content_model will keep getting set to None for base concrete classes, which is confusing but not necessarily a problem. | def test_set_content_model_again(self):
richtextpage = RichTextPage.objects.create()
richtextpage.set_content_model()
page = Page.objects.get(pk=richtextpage.pk)
self.assertEqual(page.content_model, "richtextpage")
self.assertEqual(page.get_content_model(), richtextpage)
... | [
"def _set_model_class(self):\n raise OverrideRequiredError()",
"def test_get_for_model_create_contenttype(self):\n\n class ModelCreatedOnTheFly(models.Model):\n name = models.CharField()\n\n ct = ContentType.objects.get_for_model(ModelCreatedOnTheFly)\n self.assertEqual(ct.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses Tile Layout to find the largest chunk size in each dimension (XY) that the image_length will reach | def max_dimensions(self, image_length):
width_height = [0, 0]
for i, level in enumerate(self.levels):
part = i % 2
# how many of these will you need up to a full modulo worth
coordinate_in_chunk = min(int(math.ceil(image_length / float(level.chunk_size))), level.modul... | [
"def bestSize(dim):\r\n boundary = min((glGetInteger(GL_MAX_TEXTURE_SIZE), dim))\r\n test = 1\r\n while test < boundary:\r\n test = test * 2\r\n return test",
"def GetTiledSize(self, *int, **kwargs):\n ...",
"def find_base_size(self):\n\n# Find longitudinal locations of first two point... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build dictionary for fastlookup of all Twitter userIDs determined to be of organizations | def build_bots_filter():
bot_users = {} # dict for quick lookup
bots_folders = ['../humanizr/results/t51m', '../humanizr/results/t11m']
for folder in bots_folders:
bots_fn = os.listdir(folder)
for file in bots_fn:
with open(os.path.join(folder, file), 'r') as fin:
... | [
"def map():\n table = db.execute(db.mk_connection(), 'select user_id, tweet_id, url, expanded_url from tweets_url')\n print(len(table), 'Table Entries')\n url_map = {}\n for user_id, tweet_id, url, expanded_url in table:\n url = normalize(url) if expanded_url is None or expanded_url == 'Request E... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all the files the Brain object made to show you things. You must rerun all cells to reload the data | def clear_brain():
if os.path.exists(os.path.abspath("papaya_data")):
shutil.rmtree(os.path.abspath("papaya_data")) | [
"def remove_all(self):\n log.info(\"In function remove_all (images).\")\n try:\n self.Zen.GUI.File.CloseAll.Execute()\n except Exception:\n raise HardwareError(\"Error in Removing all images (connect_zen_black.py).\")",
"def _clean(self):\n if self.verbose:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator for first checking user login state before proceeding with function. Returns 401 unauthorized error if not logged in or csrf check fails. | def checks_login_and_csrf_status(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Check that user id exists in session
if 'user_id' not in login_session:
return abort(401)
# Verify posted csrf token matches session token
if request.cookies['_csrf'] != login_session... | [
"def login_required(view):\n \n @wraps(view)\n def inner_decorator(request,*args, **kwargs):\n \n out = createBaseResponseObject()\n \n try:\n if request.user.is_authenticated():\n return view(request, *args, **kwargs)\n \n except Exception, e:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the menu for a restaurant in JSON format. Requires either the name or database ID number for a restaurant. You can get a list of restaurant names and ID numbers by using "/api/restaurants". | def api_menu(name=None, r_id=None):
if 'restaurant_id' in request.args:
r_id = request.args.get('restaurant_id')
if 'restaurant' in request.args:
name = request.args.get('restaurant')
if name:
# Retrieve menu items by the given restaurant name.
try:
recs = app.q_M... | [
"def restaurant_menu_json():\n session = connect()\n items = session.query(MenuItem).all()\n return jsonify(MenuItems=[i.serialize for i in items])",
"def get_menus(restaurant_id):\n db_session = current_app.config[\"DB_SESSION\"]\n menus = db_session.query(Menu).filter(restaurant_id == Men... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns random selection of favorited menu items (default is three). Pass a user_id as a parameter or default to the currently logged in user. Returns an error if neither exists. | def get_favorites(user_id=None, limit=3):
if 'limit' in request.args:
limit = int(request.args.get('limit'))
if 'user_id' in request.args:
try:
user_id = int(request.args.get('user_id'))
except ValueError as e:
return abort(400)
else:
user_id = login_s... | [
"def view_favorites():\n\n favorite_items = User.objects(id = session['user']['id']).get().favorites_list\n \n items = []\n\n for i in range(0, len(favorite_items)):\n\n item = Item.objects(id = favorite_items[i]).first()\n items.append(item)\n \n return render_template(\"user... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves a menu item rating to the database. | def save_rating():
user_id = login_session['user_id']
# Retrieve and check parameters.
params = request.get_json()
try:
item_id = params['item_id']
new_rating = params['rating']
except KeyError:
return jsonify(error='Missing data in request.'), 400
try:
# Find exi... | [
"def save_rating(movie_id: int, user_id: str, rating: Optional[float]):\n \n db = cloudant_client[CL_RATINGDB]\n\n current_milli_time = lambda: int(round(time.time() * 1000))\n\n id = 'user_{0}/movie_{1}'.format(user_id, movie_id)\n\n with Document(db, id) as document:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves new restaurant to the database. Incoming request data must contain keyvalue pairs for new item. | def save_restaurant():
obj = request.get_json()
restaurant_data = obj.pop('restaurant')
try:
new_rec = Restaurant(created_by=login_session['user_id'],
**restaurant_data)
app.db_session.add(new_rec)
app.db_session.flush()
app.db_session.commit()
... | [
"def newRestaurant():\n if request.method == 'POST':\n newRestaurant = Restaurant(name=request.form['name'])\n session.add(newRestaurant)\n session.commit()\n flash('{R} added as a new restaurant.'.format(R=newRestaurant.name))\n return redirect(url_for('showRestaurants'))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes a restaurant from the database. | def delete_restaurant():
if 'id' not in request.get_json():
return abort(400)
if not isinstance(request.get_json()['id'], int):
return abort(400)
try:
record = app.q_Restaurant().get(request.get_json()['id'])
app.db_session.delete(record)
app.db_session.commit()
... | [
"def delete(self, *args, **kwargs):\n self.status = Restaurant.STATUS_DELETED\n self.save()",
"def delete_restaurant(restaurant_id):\n if Restaurant.user_creator(login_session['user_id'], restaurant_id):\n restaurant = db_session.query(Restaurant).filter_by(id=restaurant_id).one()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
contextmanager to indent logging for the duration of the context. | def indentation():
try:
indent()
yield
finally:
unindent() | [
"def _indent(self):\n if self._debug:\n self._debug += 1",
"def incIndent(self):\n self._logIndentLevel += 1",
"def indent(self):\r\n return _osgDB.Output_indent(self)",
"def indent(self, prefix):\n _indent = self._indent\n self._indent += prefix\n yield\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Background process from RuuviTag Sensors | def run_get_data_background(macs, queue):
def callback(data):
data[1]["time"] = str(datetime.now())
queue.put(data)
RuuviTagSensor.get_data(callback, macs) | [
"def _native_thread(self):\n while True:\n libvirt.virEventRunDefaultImpl()",
"def run_job():",
"def watch(self):\n\n itimer = Timer(\"getImage\")\n gtimer = Timer(\"GRIP Pipeline\")\n atimer = Timer(\"Analyze Blobs\")\n utimer = Timer(\"Update Robo RIO\")\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Either the highest_recorded_rps or the max() of all tests max_rps | def max_total_rps(self):
max_tested = self.max_tested_total_rps
return max([max_tested, self.highest_recorded_rps, self.max_tested_rps]) | [
"def max_tested_total_rps(self):\n\n max_tested = 0\n if len(self.tests) > 0:\n max_tested = max([t.max_rps for t in self.tests])\n return max([max_tested, self.max_tested_rps])",
"def personal_best(self) -> int:\n return max(self._scores)",
"def testMax(self):\n ranks = [\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Either the given max_tested_rps or the max of our testing. We do this calculation here because when users are entering new features we allow them to specify this data because we dont already have it. Once that feature starts getting tested we override it. | def max_tested_total_rps(self):
max_tested = 0
if len(self.tests) > 0:
max_tested = max([t.max_rps for t in self.tests])
return max([max_tested, self.max_tested_rps]) | [
"def max_total_rps(self):\n\n max_tested = self.max_tested_total_rps\n return max([max_tested, self.highest_recorded_rps, self.max_tested_rps])",
"def test_result_has_max_requested_or_less(self):\n pass",
"def personal_best(self) -> int:\n return max(self._scores)",
"def mpeg_max_gop_test(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the latest run test for this feature | def latest_test(self):
return (Tests.search
.filter(Tests.feature_id == self.id)
.order_by(Tests.ended_at.desc())
.first()) | [
"def last_test_result():\n \n return Script.last_result",
"def get_test(self):\n return Test.objects.get(pk=self.testid, deleted=False)",
"def get_last_run(runfile):\n runfile = open(runfile, 'r')\n return int(runfile.readlines()[-1])",
"def run(self):\n return self.since.run... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows an elbow curve plot to determine the appropriate number of kmeans clusters. | def KMeansClusteringElbowCurve(X):
distorsions = []
for k in range(1, 7):
kmeans_model = KMeans(n_clusters=k)
kmeans_model.fit(X)
distorsions.append(kmeans_model.inertia_)
fig = plt.figure(figsize=(15, 5))
plt.plot(range(1, 7), distorsions)
plt.title('Elbow Curve')
plt.sh... | [
"def elbow(max_k, X):\r\n scores = []\r\n for k in range(1, max_k + 1):\r\n _, _, curr_score = kmeans(X, k)\r\n scores.append(curr_score)\r\n k_fit_plot(scores, max_k, 'K Fit for K-means using Elbow Method')",
"def elbow(min_clusters, max_clusters, df):\n score_dict = {}\n for num_clu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a kmeans model and a pandas data frame containing quote information and cluster label. | def KMeansClustering(X, quote_dict, clusters=6):
kmeans_model = KMeans(n_clusters=clusters, random_state=42).fit(X)
kmeans_labels = kmeans_model.labels_
kmeans_df = pd.DataFrame(columns=['news_source', 'quote', 'kmeans_label'])
for quote_key, quote_list in zip(quote_dict.keys(), quote_dict.values()):
... | [
"def Prediction():\t\n\tif model == 'HAC':\n\t\tclf = _HAC_model()\n\t\tclf.set_params(**best_params)\n\t\tlabels = clf.fit_predict(np.array(df.astype(int)))\n\t\tdf_ = pd.concat([df,pd.DataFrame(labels,columns=['Cluster'])], axis=1)\n\t\treturn df_\n\n\tclf = _kmeans_model()\n\tclf.set_params(**best_params)\n\tlab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a 405 response when method is not allowed. If _methods are in routing_args, send an allow header listing the methods that are possible on the provided URL. | def handle_405(environ, start_response):
_methods = util.wsgi_path_item(environ, '_methods')
headers = {}
if _methods:
# Ensure allow header is a python 2 or 3 native string (thus
# not unicode in python 2 but stay a string in python 3)
# In the process done by Routes to save the all... | [
"def _check_method(cls, allowed_methods=VALID_METHODS):\n if cherrypy.request.method.upper() not in allowed_methods:\n cherrypy.response.headers['Allow'] = (', ').join(allowed_methods)\n raise cherrypy.HTTPError(405)",
"def nomethod(cls):\n web.ctx.status = '405 Method Not Allowed'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process route declarations to create a Route Mapper. | def make_map(declarations):
mapper = routes.Mapper()
for route, targets in declarations.items():
allowed_methods = []
for method in targets:
mapper.connect(route, action=targets[method],
conditions=dict(method=[method]))
allowed_methods.append(m... | [
"def build_routes(self):\n mapper = self.get_mapper()\n routes = mapper.get_routes(include_static=False)\n\n for route in routes:\n data = _get_route_data(route, self.request.registry)\n for name, pattern, view_data in data:\n\n if self.is_good_route_item(na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the path to the label data for msdlastfm50 | def msd_lastfm50_label():
return pkg_resources.resource_filename(__name__, MSD_LASTFM50_LABEL) | [
"def data_label(path):\n if os.path.basename(path) == '':\n path = os.path.dirname(path)\n _, fname = os.path.split(path)\n name, _ = os.path.splitext(fname)\n return name",
"def make_label_file(self, pathname, final_path):\n song_strings = glob.glob(pathname)\n genre_list = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the splits for msdlastfm50 | def msd_lastfm50_splits(fold=0, split='train'):
assert split in {'train', 'valid', 'test'}
return pkg_resources.resource_filename(
__name__, MSD_LASTFM50_SPLIT.format(split, fold)
) | [
"def dataset_splits(self):\n # 10% evaluation data\n return [{\n \"split\": problem.DatasetSplit.TRAIN,\n \"shards\": 99,\n }, {\n \"split\": problem.DatasetSplit.EVAL,\n \"shards\": 1,\n }]",
"def get_splits(self, sids, dt):\n raise NotImplementedError",
"def get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the path to the metadata (fnsongid map) for IRMAS training set | def irmas_train_metadata():
return pkg_resources.resource_filename(__name__, IRMAS_TRAIN_METADATA) | [
"def __read_metadata():\n\n batch_number = 140010\n training_example_file_name = find_training_file(\n top_training_dir_name=TOP_TRAINING_DIR_NAME, batch_number=batch_number,\n raise_error_if_missing=True)\n training_example_dict = read_input_examples(\n netcdf_file_name=training_examp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a+abs(b), but without calling abs. >>> a_plus_abs_b(2, 3) 5 >>> a_plus_abs_b(2, 3) 5 | def a_plus_abs_b(a, b):
if b < 0:
op = sub
else:
op = add
return op(a, b) | [
"def a_plus_abs_b(a, b):\n\tif b < 0:\n\t\tf = sub\n\telse:\n\t\tf = add\n\treturn f(a, b)",
"def exp_uniform_abs(a,b):\n assert b >= a\n if a < 0 < b:\n exp = (a**2 + b**2)*1.0/(b - a)/2\n else:\n exp = (abs(a) + abs(b))*1.0/2\n return exp",
"def abs_comp(field_1, field_2):\n field... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return xx + yy, where x and y are the two largest of a, b, c. >>> two_of_three(1, 2, 3) 13 >>> two_of_three(5, 3, 1) 34 >>> two_of_three(10, 2, 8) 164 >>> two_of_three(5, 5, 5) 50 | def two_of_three(a, b, c):
max1 = max(a, b)
max2 = max(b, c)
ans = add
return ans(max1*max1, max2*max2) | [
"def two_of_three(a, b, c):\n\treturn max(a * a + b * b, b * b + c * c, c * c + a * a)",
"def largest_of_three(a: int, b: int, c: int) -> int:\n return(max(a,b,c))",
"def max_of_three(num1, num2, num3):\n if num1 > num2 and num1 > num3:\n return num1\n elif num2 > num1 and num2 > num3:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of light novels under a certain language. | def light_novels(self, language="English"):
projects = []
r = requests.get(self.api,
params={'action': 'query', 'list': 'categorymembers',
'cmtitle': 'Category:Light_novel_({})'.format(language.replace(" ", "_")),
... | [
"def web_novels(self, language=\"English\"):\n projects = []\n r = requests.get(self.api,\n params={'action': 'query', 'list': 'categorymembers',\n 'cmtitle': 'Category:Web_novel_({})'.format(language.replace(\" \", \"_\")),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of teaser projects under a certain language. | def teaser(self, language="English"):
projects = []
r = requests.get(self.api,
params={'action': 'query', 'list': 'categorymembers',
'cmtitle': 'Category:Teaser_({})'.format(language.replace(" ", "_")),
'cmtype': ... | [
"def web_novels(self, language=\"English\"):\n projects = []\n r = requests.get(self.api,\n params={'action': 'query', 'list': 'categorymembers',\n 'cmtitle': 'Category:Web_novel_({})'.format(language.replace(\" \", \"_\")),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of web novels under a certain language. | def web_novels(self, language="English"):
projects = []
r = requests.get(self.api,
params={'action': 'query', 'list': 'categorymembers',
'cmtitle': 'Category:Web_novel_({})'.format(language.replace(" ", "_")),
'cm... | [
"def light_novels(self, language=\"English\"):\n projects = []\n r = requests.get(self.api,\n params={'action': 'query', 'list': 'categorymembers',\n 'cmtitle': 'Category:Light_novel_({})'.format(language.replace(\" \", \"_\")),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage. | def chapters(self, title):
r = requests.get("https://www.baka-tsuki.org/project/index.php?title={}".format(title.replace(" ", "_")),
headers=self.header)
if r.status_code != 200:
raise requests.HTTPError("Not Found")
else:
parsed = soup(r.text, 'h... | [
"def load_chapters(self):\r\n \r\n if self.chapters > 1:\r\n navigate = self.request(\"https://archiveofourown.org/works/%i/navigate?view_adult=true\"%self.workid)\r\n all_chapters = navigate.find(\"ol\", {'class': 'chapter index group'})\r\n self.chapter_ids = []\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a cover image given a page id. | def cover(self, pageid):
r = requests.get(self.api,
params={'action': 'query', 'prop': 'pageimages', 'pageids': pageid, 'format': 'json'},
headers=self.header)
jsd = r.json()
image = "File:" + jsd['query']['pages'][pageid]['pageimage']
r ... | [
"def get_image(id):\n\n # by default we will fetch the original image\n endUrl = 'original.jpg'\n\n quality = ''\n if request.args != None:\n # a `q` param is passed in, get it\n quality = request.args.get('q', '')\n if quality.lower() == 'medium':\n endUrl = '300x294_ac.jpg'\n elif quality.low... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a chain of preprocessors. | def create_chain(class_items, kwargs_list):
chain = None
for i, pre_id in enumerate(class_items):
chain = CPreProcess.create(
pre_id, preprocess=chain, **kwargs_list[i])
return chain | [
"def _create_preprocess_chain(pre_id_list, kwargs_list):\n chain = None\n pre_list = []\n for i, pre_id in enumerate(pre_id_list):\n chain = CPreProcess.create(\n pre_id, preprocess=chain, **kwargs_list[i])\n pre_list.append(CPreProcess.create(pre_id, **kwar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visualize activation values for a particular neuron on some text. This method returns an SVG drawing of text with every token's background color set according to the passed in activation values (red for negative values and blue for positive). | def visualize_activations(
tokens,
activations,
darken=2,
colors=["#d35f5f", "#00aad4"],
text_direction="ltr",
char_limit=60,
font_size=20,
filter_fn=lambda x: x,
):
################################ Validation ################################
valid_text_directions = ["ltr", "rtl"... | [
"def __call__(self, tokens, layer, neuron, **kwargs):\n\n with self.__HiddenPrints__():\n activations, _ = extract_sentence_representations(\n \" \".join(tokens), self.model, self.tokenizer\n )\n return visualize_activations(tokens, activations[layer, :, neuron], *... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visualize the activations of ``neuron`` from ``layer`` in the loaded model on the given tokens. | def __call__(self, tokens, layer, neuron, **kwargs):
with self.__HiddenPrints__():
activations, _ = extract_sentence_representations(
" ".join(tokens), self.model, self.tokenizer
)
return visualize_activations(tokens, activations[layer, :, neuron], **kwargs) | [
"def train_with_activation_display(network_name, mdl_name):\n\n network = load_network(network_name)\n for cur_mdl in network.modules:\n cur_mdl.reset()\n\n mdl = network.module_with_name(mdl_name)\n\n # pick first input module (this code won't work with multi-input modules)\n input_mdl = six.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that calculates the number of clusters of a UserInfo instance. | def number_of_clusters(self, obj):
clusters = ClusterInfo.objects.all().filter(user_id=obj.user_id). \
filter(cluster_status=1).count()
return clusters | [
"def get_cluster_count(imp_centers, subs):\r\n center_tree = spatial.KDTree(imp_centers)\r\n cluster_count = {i: 0 for i in range(len(imp_centers))}\r\n for sub in subs:\r\n cluster_count[center_tree.query(sub)[1]] += 1\r\n cluster_count_freq = sorted(cluster_count.items(), key=operator.itemgette... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |