query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
`clicked on board | || yes No | | selected from where nothing to do | | | | selection_bar Board no selection | | | is clicked on valid position is clicked on valid position(Rajan) clicked on empty slot | | | (it returns pgn) | | | | | | | yes no yes no | | | | | | place it (if his piece) does move contain 'x' (capture)... | def main_board_maintenance(self,x_cor,y_cor):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
x_adjusted,y_adjusted = Helping_Class.convert_coordinate(x_cor,y_cor,from_where... | [
"def selection_board_maintenance(self,x_cor,y_cor):\t\t\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tpygame.display.quit()\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tquit() \r\n\r\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN:\r\n\t\t\t\t#print(\"mouse is pressed\")\r\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
clicked on selection_bar | | | Yes No | | selected from where or not selected is it his piece | | | | | | | selection_bar board nothing selected yes no \ | / | | \ | / blit cover nothing to do \ | / (if clicked piece is his piece == True) else nothing to do and if its availability is their \ / | \ / | \ / | \ / | \/ | ... | def selection_board_maintenance(self,x_cor,y_cor):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
#print("mouse is pressed")
#everything begins here
x_adjusted,y_adjusted... | [
"def select_piece(self, mouse_pos):\n x, y = (mouse_pos[0] // piece_size[0], mouse_pos[1] // piece_size[1]) # Obtains the coordinates of the square that has been selected\n\n if self.selected_piece == (None, None) and self.move_loc == (None, None): # If a piece has not been previously selected...\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the scheduling actions based on highest Qvalues. This requires the model weights to be already saved. | def get_best_schedule(self):
# load the model weights
self.models = [load_model(f'dqn_{task_id}.h5')
for task_id in range(len(self.models))]
actions = []
is_scheduled = [0] * len(self.models)
while (not all(is_scheduled)):
observation = OrderedDict([('is... | [
"def bestAction(self):\n get_q = self.getQFunction()\n maxq = -5000\n best_actions = []\n for (state, action), q in get_q.items():\n if q > maxq:\n maxq = q\n best_actions = [action]\n elif q == maxq:\n best_actions.appen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates embeddings from a given dataframe assume dataframe has title and abstract in the columns | def calculate_embeddings(df, option="lsa", n_papers=MAX_BATCH_SIZE, n_components=30):
assert option in ["lsa", "sent_embed"]
if len(df) < n_components:
print(
"Length of dataframe is less than number of projected components, \
set option to sent_embed instead"
)
o... | [
"def embed(self, text_dataframe: pd.DataFrame) -> pd.DataFrame:\n\n vector_dict_list = [\n {f\"dim_{ind}\": val for ind, val in enumerate(self.mean_transformer_embedding(input_text=txt))} for txt in\n tqdm(text_dataframe.Review, \"Embed the Review Texts\")]\n embedding_df = pd.Da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses the unicode of an input kanji to find the corresponding stroke order gif in mistval's collection | def get_gif_uri(kanji):
fileName = kanji.encode("unicode-escape").decode("utf-8").replace("\\u", '') + '.gif'
animationUri = f'https://raw.githubusercontent.com/mistval/kanji_images/master/gifs/{fileName}'
return animationUri | [
"def hiragana(str):\n kana={'ァ': 'ぁ', 'ア': 'あ', 'ィ': 'ぃ', 'イ': 'い', 'ゥ': 'ぅ', 'ウ': 'う', 'ェ': 'ぇ', 'エ': 'え', 'ォ': 'ぉ', 'オ': 'お', 'カ': 'か', 'ガ': 'が', 'キ': 'き', 'ギ': 'ぎ', 'ク': 'く', 'グ': 'ぐ', 'ケ': 'け', 'ゲ': 'げ', 'コ': 'こ', 'ゴ': 'ご', 'サ': 'さ', 'ザ': 'ざ', 'シ': 'し', 'ジ': 'じ', 'ス': 'す', 'ズ': 'ず', 'セ': 'せ', 'ゼ': 'ぜ', 'ソ': 'そ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a word and returns true if there are hiragana or katakana present within the word | def contains_kana(word):
for k in word:
if k in hiragana or k in katakana or k in small_characters:
return True
return False | [
"def isChinese(word):\n if word not in set([\"和\",\"的\",\"有\",\"由\",\"又\",\"地\",\"阿\",\"按\",\"啊\",\"们\",\"喝\",\"友\",\"那么\",\"我们\", \"元\"]):\n for ch in word:\n if '\\u4e00' <= ch <= '\\u9fff':\n return True\n return False\n return False",
"def isword(word):\n for c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Directly use Jisho's official API to get info on a phrase (can be multiple characters) | def search_for_phrase(self, phrase):
uri = uriForPhraseSearch(phrase)
return json.loads(requests.get(uri).content) | [
"def get_phrase(self):\n if self.skye.config.get(\"urban_dictionary\", \"api_key\") == \"\":\n self.skye.speak(\"No API key has been set in the config file.\")\n return\n self.skye.speak(\"What phrase should I define?\")\n word = self.skye.active_listen()\n if (word... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
With the response, extract the HTML and store it into the object. | def _extract_html(self, url):
self.response = requests.get(url, timeout=5)
self.html = BeautifulSoup(self.response.content, "lxml") if self.response.ok else None
# return self.html | [
"def soup(self, response):\r\n if \"html\" in response.content_type:\r\n html = response.html\r\n elif \"json\" in response.content_type:\r\n html = BeautifulSoup(response.json[\"html\"])\r\n else:\r\n self.fail(\r\n \"Response content-type {0} is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take the meanings list from the DOM and clean out noninformative meanings. | def _isolate_meanings(self, meanings_list):
index = self._get_meaning_cutoff_index(meanings_list)
if index:
return [m for i, m in enumerate(meanings_list) if i < index]
else:
return meanings_list | [
"def get_meanings(self):\n meanings = self.__soup.select(self.__helper.get_meaning_selector())\n\n def convert(m): return self.__helper.meaning_text(m)\n\n return list(map(convert, meanings))",
"def clean_summaries(data):\n\n for entry in data:\n # split summary list\n entry.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the full furigana of a word from the html. | def _get_full_vocabulary_string(self, html):
# The kana represntation of the Jisho entry is contained in this div
text_markup = html.select_one(".concept_light-representation")
upper_furigana = text_markup.select_one(".furigana").find_all('span')
# inset_furigana needs more formatting ... | [
"def word_of_the_day():\n r = requests.get(\"http://www.urbandictionary.com\") # link is always homepage\n soup = BeautifulSoup(r.content, features=\"html.parser\") # sets up soup\n def_header = \"**\" + soup.find(\"div\", attrs={\"class\": \"def-header\"}).text.replace(\"unknown\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prefetch the approvals, so that we don't do a query perprescription on the regional summary page. | def queryset(self, request):
qs = super(PrescriptionAdmin, self).queryset(request)
qs.prefetch_related('approval_set')
return qs | [
"def get_approvals_for_first_stage(self):\n query = \"exec payment.get_approvals_for_first_stage\"\n self.__cursor.execute(query)\n return self.__cursor.fetchall()",
"def setup_eager_loading(queryset):\n # select_related for \"to-one\" relationships\n # queryset = queryset.selec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override the redirect url after successful save of an existing burn plan. | def response_post_save_change(self, request, obj):
url = reverse('admin:prescription_prescription_detail',
args=[str(obj.id)])
return HttpResponseRedirect(url) | [
"def response_post_save_change(self, request, obj):\n return HttpResponseRedirect(obj.get_absolute_url())",
"def response_post_save_add(self, request, obj):\n return HttpResponseRedirect(obj.get_absolute_url())",
"def redirect_url(self):\n if self.id:\n return config.CHECKOUT_URL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View to manage corporate approval of an ePFP. | def corporate_approve(self, request, object_id, extra_context=None):
obj = self.get_object(request, unquote(object_id))
if request.method == 'POST':
url = reverse('admin:prescription_prescription_detail',
args=[str(obj.id)])
if request.POST.get('_cancel'... | [
"def test_approver(self):\n self._add_client_group('PR')\n self._unprivileged_page_tests(\n additional_pages=['manage:event_request', 'manage:events',\n 'manage:participants']\n )\n response_approvals = self.client.get(reverse('manage:approvals'))\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View to manage endorsement of an ePFP. | def endorse(self, request, object_id, extra_context=None):
obj = self.get_object(request, unquote(object_id))
title = "Endorse this ePFP"
if obj.endorsement_status == obj.ENDORSEMENT_DRAFT:
title = "Submit for endorsement"
form = AddEndorsementForm(request.POST or None, req... | [
"def office_edit_process_view(request):\n status = ''\n success = True\n # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer\n authority_required = {'verified_volunteer'}\n if not voter_has_authority(request, authority_required):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the substring between the first and last chars/strings | def __find_between(self, s, first, last):
try:
start = s.index(first) + len(first)
end = s.index(last, start)
return s[start:end]
except ValueError:
return "" | [
"def extract_string(begin, end, string):\n b = string.find(begin) + len(begin)\n e = string.find(end, b)\n\n return string[b:e]",
"def find_between_r(s, first, last):\n try:\n start = s.rindex(first) + len(first)\n end = s.rindex(last, start)\n return s[start:end]\n except Valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Figure out where to redirect after the 'Save' button has been pressed when adding a new object. | def response_post_save_add(self, request, obj):
opts = self.model._meta
if "next" in request.GET:
return HttpResponseRedirect(request.GET['next'])
if self.has_change_permission(request, None):
post_url = reverse('admin:%s_%s_changelist' %
... | [
"def response_post_save_add(self, request, obj):\n return HttpResponseRedirect(obj.get_absolute_url())",
"def response_post_save_change(self, request, obj):\n return HttpResponseRedirect(obj.get_absolute_url())",
"def response_post_save_change(self, request, obj):\n url = reverse('admin:pre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save the model and assign delete permissions to particular objects. Also save user to object if an audit object | def save_model(self, request, obj, form, change):
try:
obj.prescription = self.prescription
except AttributeError:
pass
if not obj.pk:
obj.creator = request.user
obj.modifier = request.user
obj.save()
# If can_delete is set, allow the... | [
"def save(self, **kwargs):\n super().save(**kwargs)\n self.grant_permissions()",
"def save_model( self, request, obj, form, change ):\n obj.save()",
"def permissions_save_override(permittee_kw, model_func, create_perm, edit_perm, delete_perm):\n def save(self, *args, **kwargs):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fix up the display of the criteria so that it looks a bit nicer. | def criteria_display(self, obj):
return markdownify(obj.criteria) | [
"def listCriteria():",
"def print_conditions(self):\n _outstr = \"\"\n first = True\n for cond in self._conditions:\n if not first:\n _outstr += \", \"\n if cond in ThresholdCheck._default_min_conditions:\n _outstr += \"{:s}={:.2e}\".format(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
At the begining the function reads the layers thickness of a composite material and converts its properties to the property of the isotropic one. Then the properties of the isotropic material are assigned to the tables if necessary. Additionally the function tests the input parameters of the isotropic material on consi... | def updateData( Tables, Graph, LayersInfo, WarningMessage ):
# clean the warning message
LayersInfo.clean()
WarningMessage.clean()
LayerThicknessBuffer = Tables[ "GeometryProperties" ].getValue( 0, 2 )
try:
Layers = getLayersFromString( Tables[ "GeometryProperties" ].getValue( 0, 2 ) )
... | [
"def get_material_info(TABLE_info):\n \"\"\"\n 1 Get info from TABLE_info.\n \"\"\"\n width = TABLE_info[0]\n height = TABLE_info[1]\n t_m = TABLE_info[2]\n\n \"\"\"\n 2 Get material info.\n \"\"\"\n z_m = 3 * t_m\n\n m_width = rs.GetInteger(\"Put the width of material\", z_m, N... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function saves the current state of the tables and calls "cangeMode" function | def updateMode( Tables,
WarningMessage,
Graph,
Properties ):
WarningMessage.clean( )
Graph.setMode( Properties )
#WarningMessage.printMessage( "Click on the Apply button to update grapths..." )
if Properties == 0:
Tables[ "ElasticModulus" ].fillT... | [
"def __update_saved_mode(self, value):\n self._current_mode = value\n self.adb._current_mode = value\n self.shell._current_mode = value\n self.fastboot._current_mode = value",
"def update_mode(self):\n pass",
"def SetCurrMode(self, name):\r\n\t\tname = name.lower().strip()\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function sets up the default values for the tables | def setDefaultSettings( Tables, Graph, LayersInfo, WarningMessage ):
WarningMessage.clean()
if Graph.getMode() == 0:
Tables[ "ElasticModulus" ].fillTableWithBufferData( "DefaultOrthotropic" )
Tables[ "ShearModulus" ].fillTableWithBufferData( "DefaultOrthotropic" )
Tables[ "PoissonRati... | [
"def apply_defaults(self, db, dest, kvargs, lines):\n table = db.get_table(kvargs['table'])\n default_text = kvargs['default_text']\n table.find_default_from_allowable_range_descriptions(default_text)\n # Log the defaults\n logging.info(\"Defaults for table: {}\".format(tab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the metrics from the registry in latest text format as a string. | def generate_latest(registry=Registry):
def sample_line(line, metric_type):
if line.labels:
labelstr = '{{{0}}}'.format(','.join(
['{0}="{1}"'.format(
k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"'))
for k, v in sorted(l... | [
"def print_metrics(self):\n output = \"\"\n metrics = self.get_all_metrics()\n for k, v in metrics.items():\n # Print the help line\n output += \"\\n# HELP {name} {help}\\n\".format(name=v['name'],\n help=v['help'])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a list of random colours in RGB given a random number generator and the size of this list | def generate_random_colours_list(rng: random.Random, size: int) -> List[TupleInt3]:
return [random_colour(rng) for _ in range(size)] | [
"def random_color_gen():\n r = randint(0, 255)\n g = randint(0, 255)\n b = randint(0, 255)\n return [r, g, b]",
"def makeRGB(ncol = 16, minc = 32, maxc = 216):\n subd = int((maxc - minc)/ncol)\n numpy.random.seed(1)\n RGB = [[]]\n for r in range(minc, maxc, subd):\n for g in range(m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
learn novel phrases by looking at cooccurrence of candidate term pairings; docs should be input in tokenized (`tdocs`) and untokenized (`docs`) form | def extract_phrases(tdocs, docs, idf):
# Gather existing keyphrases
keyphrases = set()
for doc in tdocs:
for t in doc:
if len(t.split(' ')) > 1:
keyphrases.add(t)
# Count document co-occurrences
t_counts = defaultdict(int)
pair_docs = defaultdict(list)
fo... | [
"def intent_of_text_LnDOR(ChapterTextS, TargetQuestionsD, TestS, StopWords):\n \n # Chapter Text - stokenize\n StokensCT = stokenize(ChapterTextS, StopWords) \n\n # Test question - stokenize\n StokensTest = stokenize(TestS, StopWords)\n\n # Knowledge Base Dict - stokenize\n KBD_structure = stok... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns `top_n` keywords for a list of articles. keywords are returned as (keyword, score) tuples. | def keywords(articles, top_n=25):
# compute term idfs
token_docs = [lemma_tokenize(clean(a.text)) for a in articles]
local_term_idf = IDF(token_docs)
token_docs, phrases = extract_phrases(token_docs, [a.text for a in articles], global_term_idf)
titles = [a.title for a in articles]
title_token... | [
"def top_keywords(urls, count=10):\n try:\n res = Counter()\n for url in urls:\n res += Counter(get_keyword_dict(url))\n return [w[0] for w in res.most_common(count)]\n except:\n print('Error finding top keywords')",
"def extract_keywords(article_list, n=10):\n vectorizer = TfidfVectorizer()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return current thread name. | def get_threadname():
cur_thread = threading.current_thread()
return cur_thread.name | [
"def thread_name(self):\n return threading.current_thread().name",
"def thread_name():\n return threading.current_thread().name",
"def name(self):\n assert self._initialized, \"Thread.__init__() not called\"\n return self._name",
"def get_thread_name(self) -> Optional[str]:\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove duplicate keys while preserving order. optionally return values. | def find_uniq_preserve_order(orig_keys, orig_values=None):
seen = {}
keys = []
values = []
for i, item in enumerate(orig_keys):
if item in seen:
continue
seen[item] = 1
keys.append(item)
if orig_values:
values.append(orig_values[i])
return keys, values | [
"def remove_duplicates(array):\n return list(dict.fromkeys(array))",
"def remove_duplicates(data):\n data = sorted(data)\n return [k for k, _ in itertools.groupby(data)]",
"def RemoveDuplicates(pcoll): # pylint: disable=invalid-name\n return (pcoll\n | 'ToPairs' >> Map(lambda v: (v, None))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
resets server figure by deleting lines and clearing legend. | def _handle_reset(self):
stream_data = self.server.stream_data
# remove lines from graph, and reset legends
for name in stream_data:
stream_data[name]['line'].remove()
for name in self.server.axes:
self.server.axes[name].legend([]) # TODO: find a better way.
stream_data = {} | [
"def reset(self):\n\n self.fig.clear()\n self.ax = self.fig.add_subplot(111)\n self.hasLegend.set(False)\n self.title(Graph.default_title)\n # Lines is a list of DataSet objects. The user should take care to make\n # DataSet names unique, as there is no error checking done ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the legend for single_axes, listing duplicate labels once. | def _handle_update_legend(self, single_axes):
# lines are bundled with an axes.
# legends are printed per axes.
# line data is in stream_data without reference to axes sets.
# for each current line, get label, get axes
# for unique axes-labels create a list to pass to legend()
artists, labels = ... | [
"def legend (self, **kwargs):\n axes = self.twin_axes or self.axes\n self.mpl_legend = axes.legend (self.mpl_lines, self.labels, **kwargs)",
"def remove_legend_duplicates(figure):\n seen = []\n for n,i in enumerate(figure['data']):\n name = figure['data'][n]['name']\n if name in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a line on the given axes using style_args. returns line_name | def _handle_create_line(self, axes, style_args):
stream_data = self.server.stream_data
# sample data for initial create
x_data = numpy.arange(0, 2, 1)
y_data = numpy.array([0]*2)
line, = axes.plot(x_data, y_data, '-', **style_args)
# NOTE: client may set 'label'
line_name = style_args['labe... | [
"def addLineStyle(dist, focus, axis, pupil):\n r = 0 #focus / 2\n g = 0 #np.log10(dist) / (25 / 3)\n b = 0 #axis / 20\n a = 0.4\n rgb = [r, g, b, a]\n line = {'style': '-', 'color': rgb}\n return line",
"def create_line(self, x1, y1, x2, y2, style=None, parent=None):\n attrs = {'d': 'M... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new axis, if axis_args are not already created. | def _handle_setup_axis(self, axis_args):
axis_name = axis_args['name']
axes_dict = self.server.axes
if axis_name not in [name for name, _ in axes_dict.items()]:
print "Adding a new axis:", axis_name
axis_count = len(axes_dict)
newaxis = self.server.figure.add_subplot(axis_count+1, 1, axis... | [
"def _appendAxisDefinition(self, axis):\n length = len(axis)\n\n self.na_dict[\"NX\"].append(length)\n self.na_dict[\"XNAME\"].append(xarray_utils.getBestName(axis))\n\n # If only one item in axis values\n if length < 2:\n self.na_dict[\"DX\"].append(0)\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create instance data for figure, axes, and stream data. | def setup(self, flags):
self.figure = pylab.figure(1)
self.axes = {}
self.stream_data = {}
self.flags = flags | [
"def initialiseData(self):\n self.currentPosition = 0\n self.xs = scipy.linspace(0.0, self.numberOfPoints*self.resolution, self.numberOfPoints)\n self.cursorXS = self.getCurrentPositionArray()\n self.cursorVertical = scipy.array([self.verticalLimit,0.0])\n self.array0 = scipy.zero... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the last 5 published polls(Not including those to be published in the future) that have at least 2 choices | def get_queryset(self):
#Old get_queryset() method.
#Return last 5 published polls
#return Poll.objects.order_by('-pub_date')[:5]
#New get_queryset() method.
#return Poll.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
return Poll.objects.annotate(num_choices=Count('choic... | [
"def get_queryset(self):\n return Poll.objects.order_by('-pub_date')[:5]",
"def get_queryset(self):\n return Poll.objects.filter(\n pub_date__lte=timezone.now()\n ).order_by('-pub_date')[:5]",
"def latest_question(questions):\n return questions.order_by('-pub_date')[:5]",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor for decisions having just the low and high value | def __init__(self, low, high):
self.low = low
self.high = high | [
"def __init__(self, low_score=0, high_score=0):\n self.low_score = low_score\n self.high_score = high_score",
"def __init__(self, endowment1, endowment2, preference1, preference2):\n self.good1 = max(0, endowment1)\n self.good2 = max(0, endowment2)\n self.pref1 = preference1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor for model having objectives, constraints and decisions | def __init__(self, objectives, constraints, decisions):
self.objectives = objectives
self.constraints = constraints
self.decisions = decisions | [
"def __init__(self):\n self.name = \"Osyczka\"\n objectives = [ob_os_1, ob_os_2]\n constraints = [con_os_1, con_os_2, con_os_3, con_os_4, con_os_5, con_os_6]\n decisions = [Decision(0, 10), Decision(0, 10), Decision(1, 5), Decision(0, 6), Decision(1, 5), Decision(0, 10)]\n Model._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates the score for a given solution using all objectives | def evaluate(self, solution, total = 0):
for objective in self.objectives:
total = total + objective(solution)
return total | [
"def evaluate(self, aSolution):",
"def evaluate(self, *args, **kwargs):\n out = {\"objectives\": np.array([])}\n x_ = np.array(list(map(lambda foo: foo.x, self.individuals)))\n self.problem._evaluate(x_, out, *args, **kwargs)\n self.objective_values = out[\"objectives\"]",
"def evalu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates if given solutions is as per the constraints | def ok(self, solution):
if self.constraints is not None:
for constraint in self.constraints:
if not constraint(solution):
return False
return True | [
"def isValid(self, aSolution):",
"def validateSolution(solution) -> bool:\r\n # Does not use shortcut return, if invalidation found, to print all errors.\r\n isValid = True\r\n\r\n if not validateTeacherTimeConstraints(solution):\r\n logger.debug(\"Solution: %4i, TeacherTime Constraint Fail!\" % s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor for Osyczka2 model | def __init__(self):
self.name = "Osyczka"
objectives = [ob_os_1, ob_os_2]
constraints = [con_os_1, con_os_2, con_os_3, con_os_4, con_os_5, con_os_6]
decisions = [Decision(0, 10), Decision(0, 10), Decision(1, 5), Decision(0, 6), Decision(1, 5), Decision(0, 10)]
Model.__init__(self... | [
"def __init__(self):\n self.name = \"Kursawe\"\n objectives = [o_ku_1, o_ku_2]\n decisions = [Decision(-5, 5), Decision(-5, 5), Decision(-5, 5)]\n Model.__init__(self, objectives, None, decisions)",
"def __init__(self):\n self.name = \"Schaffer\"\n objectives = [o_sh_1, o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor for Schaffer model | def __init__(self):
self.name = "Schaffer"
objectives = [o_sh_1, o_sh_2]
decisions = [Decision(-10 ** 5, 10 ** 5)]
Model.__init__(self, objectives, None, decisions) | [
"def __init__(self, ChannelModel):\n self.Channel = ChannelModel",
"def __init__(self):\n\t\tsuper(BigramModel, self).__init__()",
"def _construct(self, model_config):\n raise NotImplementedError",
"def __init__(self, **kwargs):\n _declarative_constructor(self, **kwargs)",
"def __init__... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor for Kursawe model | def __init__(self):
self.name = "Kursawe"
objectives = [o_ku_1, o_ku_2]
decisions = [Decision(-5, 5), Decision(-5, 5), Decision(-5, 5)]
Model.__init__(self, objectives, None, decisions) | [
"def __init__( self, weights, topics ):\n\n # Number of topics and dictionary size\n self.W, self.K = topics.shape\n assert( self.W > self.K )\n\n self.topics = topics\n MixtureModel.__init__(self, weights, topics)",
"def __init__(self, params, model, name=\"las_encoder\", mode=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a phone number as a subscriber to the current Topic | def addSubscriber(self, phoneNumber):
if self.topicArn is None:
print 'ERROR: Notification topic not set!'
return
protocol = 'sms'
subscribeResponse = self.snsClient.subscribe(
TopicArn=self.topicArn,
Protocol=protocol,
Endpoint=phoneN... | [
"def addSubtopic(id):",
"def _registerSubscriber(self, callerId, topic, topicType, callerApi):\n if topic not in self.FilterSubscribedTopics:\n self.__docWriter.addSub(callerId, topic, topicType)",
"def add_subscriber(self, address):\n self.logger.debug('add_subscriber(%s:%d)'%address)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute http probe and count metrics | async def exec_probes(self, session: aiohttp.ClientSession,
counter: dict):
self._logger.debug('Start exec probe %s', self.url)
regexp_metrics = [RegexpMetrics(pattern) for pattern in self._patterns]
status_code_metrics = StatusCodeMetrics()
time_metrics = Time... | [
"def do_metrics():\n do_delay_metric()\n do_rtt_metric()",
"def test_metrics_prometheus(self, master_ar_process):\n url = master_ar_process.make_url_from_path('/nginx/metrics')\n\n resp = requests.get(\n url,\n allow_redirects=False,\n )\n\n assert resp.stat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to write the XML file containing the information regarding the stop condition for branching in DET method @ In, filename, string, filename (with absolute path) of the XML file that needs to be printed out @ In, trigger, string, the name of the trigger variable | def writeXmlForDET(filename,trigger,listDict,stopInfo):
# trigger == 'variable trigger'
# Variables == 'variables changed in the branch control logic block'
# associated_pb = 'CDF' in case multibranch needs to be performed
# stopInfo {'end_time': end simulation time (already stopped), 'end_ts': end time s... | [
"def _writeBranchInfo(self, filename, endTime, endTimeStep, tripVariable):\n from ..Utilities import dynamicEventTreeUtilities as detUtils\n tripVar = self._returnAliasedVariable(tripVariable)\n detUtils.writeXmlForDET(filename,tripVar,[],{'end_time': endTime, 'end_ts': endTimeStep})",
"def write_report_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw circle for face, sized relative to window size | def drawFace(win, winW, winH):
face = Circle(Point(winW/2, winH/2), min(winW, winH)*11/24)
face.setOutline("black")
face.setFill("burlywood")
face.draw(win) | [
"def draw(self, screen): \n pygame.draw.circle(screen, self.color, (int(self.pos.x), int(self.pos.y)), self.radius)",
"def draw_face():\n\n # Draw outline\n draw_circle(40, 10, 100)\n\n # Draw left eye\n draw_eye(0, 100, 20)\n\n # Draw right eye\n draw_eye(80, 100, 20)\n\n # Dra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws eyes for face | def drawEyes(win, winW, winH):
# leftEye = Oval(Point(300-120-40, 300-80-20), Point(300-120+40, 300-80+20))
leftEye = Oval(Point(winW/2-winW/5-winW/15, winH/2-winH/7.5-winH/30),
Point(winW/2-winW/5+winW/15, winH/2-winH/7.5+winH/30))
leftEye.setFill("white")
leftEye.setOutline("black")
... | [
"def draw_eyes(self):\n GREEN = (0, 255, 0)\n for eye in self.eyes:\n if eye:\n cv2.circle(self.eyes_frame, eye, 8, GREEN, 1)",
"def draw_face():\n\n # Draw outline\n draw_circle(40, 10, 100)\n\n # Draw left eye\n draw_eye(0, 100, 20)\n\n # Draw right eye\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws arc for mouth | def drawMouth(win, winW, winH):
drawArc(win, winW/2, winH/2, winH/4, 60, 1.5) # draw mouth | [
"def DrawArc(\n self, draw, bbox, start, end, fill,\n width = 1, units = 'deg'\n ):\n# bbox = [\n# origin_x - radius, origin_y - radius,\n# origin_x + radius, origin_y + radius\n# ]\n\n st_rad = start * math.pi / 180.0 if units != 'rad' else start\n en_rad = end * math.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws arcs for eyebrows | def drawEyebrows(win, winW, winH):
drawArc(win, winW/2-winW/5, winH/2-winH/7.5+winH/10, winH/6, 30, 0.5) # left eyebrow
drawArc(win, winW/2+winW/5, winH/2-winH/7.5+winH/10, winH/6, 30, 0.5) # right eyebrow | [
"def horizontal_arcs_iglu():\n arc(screen, BLACK, (50, 560, 300, 20), 3.14, 0)\n arc(screen, BLACK, (60, 510, 280, 20), 3.14, 0)\n arc(screen, BLACK, (80, 460, 240, 20), 3.14, 0)\n arc(screen, BLACK, (120, 420, 160, 20), 3.14, 0)",
"def draw_equitriangle(t,sz):\r\n\r\n\tdraw_poly(t, 3, sz)",
"def dr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws red nose with reflection spot (polygon) | def drawNose(win, winW, winH):
noseRad = winW/12
nose = Circle(Point(winW/2, winH/2+winH/15), noseRad)
nose.setOutline("red4")
nose.setFill("red")
nose.draw(win)
spot = Polygon(Point(winW/2+noseRad*0.7, winH/2+noseRad*0.6),
Point(winW/2+noseRad*0.7, winH/2+noseRad*0.4),
... | [
"def drawPoles(wn):\n wn.setworldcoordinates(-1, -5, 3, 20)\n t = turtle.Turtle()\n t.speed(0)\n t.pensize(3)\n t.up()\n t.goto(-.5, 0)\n t.down()\n t.goto(2.5, 0)\n t.up()\n for i in range(3):\n t.goto(i, 0)\n t.down()\n t.goto(i, 10)\n t.up()\n t.hidetu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save the saveable objects to a checkpoint with `file_prefix`. | def save(self, file_prefix, options=None):
options = options or checkpoint_options.CheckpointOptions()
tensor_names = []
tensors = []
slice_specs = []
for checkpoint_key, tensor_slices in self._tensor_slice_dict.items():
for slice_spec, tensor in tensor_slices.items():
if isinstance(te... | [
"def save(self, file_prefix, options=None):\n options = options or checkpoint_options.CheckpointOptions()\n\n # IMPLEMENTATION DETAILS: most clients should skip.\n #\n # Suffix for any well-formed \"checkpoint_prefix\", when sharded.\n # Transformations:\n # * Users pass in \"save_path\" in save()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restore the saveable objects from a checkpoint with `file_prefix`. | def restore(self, file_prefix, options=None):
options = options or checkpoint_options.CheckpointOptions()
tensor_names = []
tensor_dtypes = []
slice_specs = []
for checkpoint_key, tensor_slices in self._tensor_slice_dict.items():
for slice_spec, tensor in tensor_slices.items():
tensor... | [
"def restore(self, file_prefix, options=None):\n options = options or checkpoint_options.CheckpointOptions()\n\n def restore_fn():\n restore_fn_inputs = {}\n restore_fn_input_count = {\n fn: len(keys) for fn, keys in self._restore_fn_to_keys.items()}\n\n restore_ops = {}\n # Sort ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append sharding information to a filename. | def sharded_filename(filename_tensor, shard, num_shards):
return gen_io_ops.sharded_filename(filename_tensor, shard, num_shards) | [
"def _get_shard_path(self, split, shard_id, shard_size):\n return os.path.join(self.output_dir,\n '{}-{:03d}-{}.tfrecord'.format(split, shard_id,\n shard_size))",
"def get_shard_filename(collection: str, shard: str) -> str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save the saveable objects to a checkpoint with `file_prefix`. | def save(self, file_prefix, options=None):
options = options or checkpoint_options.CheckpointOptions()
# IMPLEMENTATION DETAILS: most clients should skip.
#
# Suffix for any well-formed "checkpoint_prefix", when sharded.
# Transformations:
# * Users pass in "save_path" in save() and restore(). ... | [
"def save(self, file_prefix, options=None):\n options = options or checkpoint_options.CheckpointOptions()\n tensor_names = []\n tensors = []\n slice_specs = []\n for checkpoint_key, tensor_slices in self._tensor_slice_dict.items():\n for slice_spec, tensor in tensor_slices.items():\n if i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restore the saveable objects from a checkpoint with `file_prefix`. | def restore(self, file_prefix, options=None):
options = options or checkpoint_options.CheckpointOptions()
def restore_fn():
restore_fn_inputs = {}
restore_fn_input_count = {
fn: len(keys) for fn, keys in self._restore_fn_to_keys.items()}
restore_ops = {}
# Sort by device name... | [
"def restore(self, file_prefix, options=None):\n options = options or checkpoint_options.CheckpointOptions()\n tensor_names = []\n tensor_dtypes = []\n slice_specs = []\n\n for checkpoint_key, tensor_slices in self._tensor_slice_dict.items():\n for slice_spec, tensor in tensor_slices.items():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main entry point for landing zone command. | def run(config, toml_config, args, parser, subparser):
if not args.landingzone_cmd: # pragma: nocover
return run_nocmd(config, args, parser, subparser)
else:
config = LandingZoneConfig.create(args, config, toml_config)
return args.landingzone_cmd(config, toml_config, args, parser, subpa... | [
"def Run(self, args):\n project = properties.VALUES.core.project.Get(required=True)\n zone = {}\n zone['dnsName'] = args.dns_name\n zone['name'] = args.zone\n zone['description'] = args.description\n\n really = console_io.PromptContinue('Creating %s in %s' % (zone, project))\n if not really:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override method from djrestauth library to login with username or email | def login(self):
self.user = self.serializer.validated_data['user'] or self.serializer.validated_data['email'] | [
"def account_signin_post(self, email, password, auth=None, gogoro_sess=None, csrf_token=None):\n self.init.authHeader(gogoro_sess, csrf_token)\n\n data = {\n \"username\": {\n \"email\": email\n },\n \"password\": password,\n \"emailLogin\": T... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert numpy array of noisy coefs to dataframe for plotting. | def arr_to_df(coefs_noisy, n_arr, coefs_id):
out = pd.DataFrame(coefs_noisy, columns=n_arr)
out = pd.DataFrame(out.stack()).reset_index()
out.columns = ['component', 'n', 'value']
out = out.assign(id=coefs_id)
return out | [
"def from_numpy(array):\n return pd.DataFrame(array)",
"def to_data_frame(array: list) -> pd.DataFrame:\n return pd.DataFrame(array)",
"def to_dataframe(self) -> pd.DataFrame:\n df = pd.DataFrame(data=self.to_numpy())\n df[\"fs\"] = self.dec_fs\n df[\"factors\"] = self.dec_factors\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot risk and fairness gaps. | def plot_metrics(results, epsilon_pos, epsilon_neg):
## Plot risk and fairness gaps as a function of sample size,
## with true minimum risk and true fairness gaps for reference.
metrics_Y0 = pd.concat(results['metrics_Y0_noisy'], keys=n_arr)
metrics_Y0 = metrics_Y0.reset_index().drop(columns='level_1')... | [
"def risk_ratio_pregnant_women():\n\n # Maternal risk factors\n plt.figure(figsize=(8,8))\n values = [np.array([1.49]),np.array([1.56]),np.array([3.77]),np.array([0.93]),np.array([1.07]),np.array([1.73]),np.array([2.34]),np.array([2.96]),np.array([1.96]),np.array([2.81])]\n upper_cf = np.array([np.array... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the residuals between measured and predicted values. | def residuals(y_true, y_pred, ax=None):
_check_parameter_validity(y_true, y_pred)
if ax is None:
ax = plt.gca()
# horizontal line for residual=0
ax.axhline(y=0)
ax.scatter(y_pred, y_true - y_pred)
_set_ax_settings(ax, "Predicted Value", "Residuals", "Residuals Plot")
return ax | [
"def plot_residuals(actual, predicted, feature):\n residuals = actual - predicted\n plt.hlines(0, actual.min(), actual.max(), ls=':')\n plt.scatter(actual, residuals)\n plt.ylabel('residual ($y - \\hat{y}$)')\n plt.xlabel('actual value ($y$)')\n plt.title(f'Actual vs Residual on {feature}')\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Complete the images table of the database with the relevant values of the directory images. | def complete_images_table(self, table):
# Variable initialization
cmp_double = 0
cmp_img = 0
# Connection to database
conn, cursor = connection_database(self.db_name, self.host, self.user, self.password, self.local, self.ssl_ca)
# Get images paths
image... | [
"def load_images(image_filename):\n\n # Write code here to loop over image data and populate DB.",
"def load_example_images():\r\n\r\n\tprint(\"Images\")\r\n\r\n\tImage.query.delete()\r\n\r\n\timages = [\r\n \tImage(filesize=800, xdim=1200, ydim=1080, imgtype='jpg', uploaded=datetime.datetime.now(), url='ht... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Connects to the SQL server and stores the results of the comparisons in a csv. | def get_duels(self, csv_file, table):
conn, curs = connection_database(self.db_name, self.host, self.user, self.password, self.local, self.ssl_ca)
query = "SELECT * FROM {};".format(table)
curs.execute(query)
result = curs.fetchall()
end_connection(conn, curs)
# W... | [
"def test_sql_to_csv():\n csv_outfile = 'optwrf_database.csv'\n db_conn = conn_to_db('optwrf.db')\n sql_to_csv(csv_outfile, db_conn)\n close_conn_to_db(db_conn)\n assert os.path.exists(csv_outfile) == 1",
"def get_output_as_csv(dataset, engines, db):\n wt.reload_scripts()\n eng = wt.join_post... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Commit queries of a connect instance. | def commit_query(conn):
conn.commit() | [
"def _commit(self):\n self._connection.commit()",
"def commit ( self ): \n if self.txncursor:\n self.conn.commit()\n self.txncursor.close()\n self.txncursor = None",
"def commit(ctx):\n wrapped_ctx = _CtxWrapper.wrap(ctx)\n wrapped_ctx.commit_connections()",
"def commit(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
nice_name tag returns the username when the full name is not available | def test_nice_name_returns_username(self):
class UserNoName():
username = 'my_username'
def get_full_name(self):
return None
rendered = self.render_nice_name(UserNoName())
self.assertEquals(rendered, 'my_username') | [
"def get_full_name(self):\n if self.first_name or self.last_name:\n full_name = u'%s %s' % (self.first_name, self.last_name)\n else:\n full_name = self.username\n return full_name.strip()",
"def _username_from_name(self, name):\r\n return name.replace(' ', '_')",
"def get_short_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
nice_name tag returns the full name when is available | def test_nice_name_returns_full_namename(self):
class User():
username = 'my_username'
def get_full_name(self):
return 'my_full_name'
rendered = self.render_nice_name(User())
self.assertEquals(rendered, 'my_full_name') | [
"def nice_name():\n\n pass",
"def test_nice_name_returns_username(self):\n\n class UserNoName():\n username = 'my_username'\n\n def get_full_name(self):\n return None\n\n rendered = self.render_nice_name(UserNoName())\n\n self.assertEquals(rendered, 'my... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Forwards output, extracts Thonny message, replaces normal prompts with raw prompts. This is executed when some code is running or just after requesting raw prompt. After submitting commands to the raw REPL, the output should be like {stdout}\x04\{stderr}\x04\n\> In the end of {stdout} there may be \x02{valueforthonny} ... | def _process_until_raw_prompt(self, capture_output=False):
# TODO: experiment with Ctrl+C, Ctrl+D, reset
eot_count = 0
value = None
done = False
out = b""
err = b""
while not done:
if (self._connection.num_bytes_received == 0
and time.... | [
"def main_doPrompt(self):\n # Don't have to worry about the rank, because we only ever run a single kernel.\n sys.stdout.write(self.command_prompt)\n sys.stdout.flush()\n return",
"def prompt(self, question):\n self.output(' ')\n self.output(question)\n self.output... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a file of predictions and a file of targets compute evaluation metrics and return dict containing results (including a sum of squared errors so that errors can be added across multiple chromosomes) metrics can be computed on gene/enhancer/promoter subsets by passing lists of bin ids matching these subsets (option... | def evaluate_predictions(unfiltered_preds, unfiltered_targets, gene_bins=None,
enhancer_bins=None, promoter_bins=None, retain_bins=None):
unfiltered_errors = np.square(unfiltered_preds-unfiltered_targets)
if retain_bins is None:
retain_bins = np.arange(unfiltered_errors.shape[0]... | [
"def compute_metrics(files, is_qa):\n targets = []\n predictions = []\n if is_qa:\n def metric_fn(targets, predictions):\n return dict(\n relaxed_accuracy=pix2struct_metrics.aggregate_metrics(\n targets=targets,\n predictions=predictions,\n metric_fn=pix2st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assumption is that bins which when sorted lie outside top_bottom_bin_range are outliers and the relevant 'robust' minimum and maximum are percentiles within the top_bottom_bin_range This is a bit lie the scikitlearn robust scaler idea; though not exactly | def find_robust_min_max(x, pct_thresh=0.05, top_bottom_bin_range=2000000):
y = x[x > 0]
idxs = np.argsort(y)
abs_max = y[idxs[-1]]
abs_min = y[idxs[0]]
robust_max = y[idxs[-int(pct_thresh * top_bottom_bin_range)]]
robust_min = y[idxs[int(pct_thresh * top_bottom_bin_range)]]
log.info('Array l... | [
"def _calculate_lower_and_upper_bound(\n bootstrap_array, percentiles, central_estimate=None, method=\"simple_percentile\"\n):\n if method == \"simple_percentile\":\n upper, lower = np.percentile(bootstrap_array, percentiles)\n else:\n lower, upper = 2 * central_estimate - np.percentile(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The method used to make sure that the number of starting chips for each player can be set. | def test_set_starting_chips(self):
# Setup new game and attempt to set their valid number of starting chips
valid_chips = [
1,
10,
100,
9999,
]
for chips in valid_chips:
game = Game()
game.setup_new_game()
... | [
"def update_chips(self):\n assert sum(self.chips) <= 1, \"Only one chip can be played at once\"\n\n if self.chips[0] is True:\n assert self.wildcard_played is False, \"Wildcard is already played\"\n self.wildcard_played = True\n self.free_transfers = 2**10000 # setti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The method used to make sure that the names of the players in the game can be set. | def test_set_player_names(self):
# Setup new games and attempt to set their players' names
valid_players = [
["Bob", "Sam", "Cal", "Kris"],
["Player 1", "Player 2", "Player 3", "Player 4", "Player 5"],
["Bot"],
["P1", "P2", "P3"],
]
for pl... | [
"def initPlayerNamesDialog(self, master):\n Label(master, text=\"Enter Player Names:\").grid(row=0, column=1)\n if self.numberOfPlayers == 3:\n self.initEntries(3,[(1,1),(2,2),(2,0)],master)\n elif self.numberOfPlayers == 4:\n self.initEntries(4,[(1,1),(2,2),(3,1),(2,0)],m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Selects two customers that are nearest to each other and their neighbours and removes them from the solution. See ``customers_to_remove`` for the degree of destruction done. Similar to cross route removal in Hornstra et al. (2020). | def cross_route(current: Solution, rnd_state: Generator) -> Solution:
problem = Problem()
destroyed = deepcopy(current)
customers = set(range(problem.num_customers))
removed = SetList()
while len(removed) < customers_to_remove():
candidate = rnd_state.choice(tuple(customers))
rout... | [
"def remove_existing_customers(self):\n # remove the customers which are not active (.is_active )\n self.to_move = False\n #for cust in self.customers:\n # print(cust.state)\n self.customers = [cust for cust in self.customers if cust.state != 'checkout']\n #if cust.t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tidies a string `time` into a `date` in `datetime64[D]` format, and records the status of the conversion (`date_status`). | def tidy_time_string(time):
# TODO - :return date_range: Where date_status is "centred", date_range is a tuple (`first_date`, `last_date`) of
# `datetime64[D]` objects. Otherwise will return a tuple of Not a Time objects.
# TODO - warnings/logging
# TODO - change date offsets to rounding using MonthEn... | [
"def decode_datetime(self, string):\n if isinstance(string, str):\n if 'T' in string:\n return datetime.strptime(string, \"%Y%m%dT%H%M%S\")\n else:\n return datetime.strptime(string, \"%Y%m%d\")\n else:\n return string",
"def __parse_dat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that noun_chunks raises Value Error for 'fr' language if Doc is not parsed. | def test_noun_chunks_is_parsed_fr(fr_tokenizer):
doc = fr_tokenizer("trouver des travaux antérieurs")
with pytest.raises(ValueError):
list(doc.noun_chunks) | [
"def test_noun_chunks_is_parsed(fi_tokenizer):\n doc = fi_tokenizer(\"Tämä on testi\")\n with pytest.raises(ValueError):\n list(doc.noun_chunks)",
"def test_noun_chunks_is_parsed_it(it_tokenizer):\n doc = it_tokenizer(\"Sei andato a Oxford\")\n with pytest.raises(ValueError):\n list(doc.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add (multidimensional) samples to buffer. | def push(self, samples):
len_s = len(samples)
if self.idx + len_s < self.len:
self.data[self.idx:self.idx + len_s] = samples
self.idx += len_s
else:
if self.idx == self.len:
self.data[:-len_s] = self.data[len_s:]
else:
... | [
"def add_samples(self, samples):\n for sample in samples:\n self.add_sample(sample)",
"def add_sample(self, sample: Tuple):\n self.samples.append(sample)\n if len(self.samples) > self.max_memory:\n self.samples.pop(0)",
"def addSample(self, sample):\n\t\tself.length = min(self.l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pop a number of samples from buffer. | def pop(self, idx=None):
if not idx:
samples = np.copy(self.data[:self.idx])
self.data[:] = np.empty(self.data.shape)
self.idx = 0
else:
if idx > self.idx:
raise ValueError()
samples = np.copy(self.data[:idx])
data =... | [
"def _popN(self, n):\n for _ in range(n):\n self._buffer.popleft()",
"def read(self, nsamp=None, remove=True): ###\n available = self.to_read()\n if nsamp == None:\n nsamp = available\n if nsamp > available:\n raise RuntimeError(\"ring buffer underflow... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the dictionary of genome fasta | def getseq(genomefasta):
genomedict = {}
for i in SeqIO.parse(open(genomefasta), "fasta"):
genomedict[i.id] = str(i.seq)
return genomedict | [
"def read_fasta_to_dictionary(genome_file):\n filename = genome_file\n dct = {}\n\n id_name = \"\"\n sequence = \"\"\n first_pass = 1\n\n read_fh = open(filename, 'r')\n for i, line in enumerate(read_fh):\n line = line.rstrip()\n if re.search(r'^>(\\S+)(\\s+)(\\S+)(\\s+)(\\S+)(\\s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Program to read a gff and create dictionary of exons from a transcript | def read_gff(gff):
genome = getseq(args.genome)
dictoftranscripts = {}
for k in open(gff):
if not k.startswith("#"):
lines = k.strip().split("\t")
if lines[2] == "exon":
strand = lines[6]
chromosome = lines[0]
start = lines[3]
... | [
"def GFFParse(gff_file):\n genes, utr5, exons=dict(), dict(), dict()\n transcripts, utr3, cds=dict(), dict(), dict()\n # TODO Include growing key words of different non-coding/coding transcripts \n features=['mrna', 'transcript', 'ncrna', 'mirna', 'pseudogenic_transcript', 'rrna', 'snorna', 'snrna', 'tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show all or a specific predefined statistic. | def show_predefined_statistics(idx: int = -1) -> None:
if idx < 0:
print(PermutationStatistic._predefined_statistics())
else:
print(PermutationStatistic._STATISTICS[idx][0]) | [
"def show_stats(self):\r\n print(\"Name: Mr. Park\") \r\n print(\"Health: 600\")\r\n print(\"Strength: 400\")\r\n print(\"Agility: 400\")\r\n print(\"Block: 400\")\r\n print(\"Special: 400\")\r\n print(\"Be careful! He's quite powerful\")",
"def collect_show_statis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if statistic (self) is preserved in a bijection. | def preserved_in(self, bijection: BijectionType) -> bool:
return all(self.func(k) == self.func(v) for k, v in bijection.items()) | [
"def is_bijective(self):\n return self.is_injective() and self.is_surjective()",
"def is_involution(self):\n return self == self.inverse()",
"def check_all_transformed(cls, bijection: BijectionType) -> Dict[str, List[str]]:\n transf = defaultdict(list)\n all_stats = cls._get_all()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a distribution of statistic for a fixed length of permutations. If a class is not provided, we use the set of all permutations. | def distribution_for_length(
self, n: int, perm_class: Optional[Av] = None
) -> List[int]:
iterator = perm_class.of_length(n) if perm_class else Perm.of_length(n)
cnt = Counter(self.func(p) for p in iterator)
lis = [0] * (max(cnt.keys(), default=0) + 1)
for key, val in cnt.it... | [
"def sampling_class_portion(data,classes,others=None,class_portion=None,rng=np.random.RandomState(100)):\n u, indices = np.unique(classes,return_inverse=True)\n indices=np.asarray(indices)\n num_u=len(u)\n sample_sizes=dict()\n \n # get sample size of each class\n size_min=float(\"inf\")\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all stats that are equally distributed for two classes up to a max length. | def equally_distributed(cls, class1: Av, class2: Av, n: int = 6) -> Iterator[str]:
return (
stat.name
for stat in cls._get_all()
if all(
stat.distribution_for_length(i, class1)
== stat.distribution_for_length(i, class2)
for i in... | [
"def jointly_equally_distributed(\n class1: Av, class2: Av, n: int = 6, dim: int = 2\n ) -> Iterator[Tuple[str, ...]]:\n return (\n tuple(stat[0] for stat in stats)\n for stats in combinations(PermutationStatistic._STATISTICS, dim)\n if all(\n Counter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if a combination of statistics is equally distributed between two classes up to a max length. | def jointly_equally_distributed(
class1: Av, class2: Av, n: int = 6, dim: int = 2
) -> Iterator[Tuple[str, ...]]:
return (
tuple(stat[0] for stat in stats)
for stats in combinations(PermutationStatistic._STATISTICS, dim)
if all(
Counter(
... | [
"def equally_distributed(cls, class1: Av, class2: Av, n: int = 6) -> Iterator[str]:\n return (\n stat.name\n for stat in cls._get_all()\n if all(\n stat.distribution_for_length(i, class1)\n == stat.distribution_for_length(i, class2)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all predefined statistics as an instance of PermutationStatistic. | def _get_all(cls) -> Iterator["PermutationStatistic"]:
yield from (cls(name, func) for name, func in PermutationStatistic._STATISTICS) | [
"def mutation_probabilities(self):\n return list(self.mutation_pool.values())",
"def show_predefined_statistics(idx: int = -1) -> None:\n if idx < 0:\n print(PermutationStatistic._predefined_statistics())\n else:\n print(PermutationStatistic._STATISTICS[idx][0])",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a bijection, check what statistics transform into others. | def check_all_transformed(cls, bijection: BijectionType) -> Dict[str, List[str]]:
transf = defaultdict(list)
all_stats = cls._get_all()
for stat1, stat2 in product(all_stats, all_stats):
if all(stat1.func(k) == stat2.func(v) for k, v in bijection.items()):
transf[stat... | [
"def preserved_in(self, bijection: BijectionType) -> bool:\n return all(self.func(k) == self.func(v) for k, v in bijection.items())",
"def check_distribution(self):\n pass",
"def test_sampling_with_rejection():\n a = BbnNode(Variable(0, 'a', ['on', 'off']), [0.5, 0.5])\n b = BbnNode(Variable... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yield all symmetric versions of a bijection. | def symmetry_duplication(
bijection: BijectionType,
) -> Iterator[BijectionType]:
return (
bij
for rotated in (
{k.rotate(angle): v.rotate(angle) for k, v in bijection.items()}
for angle in range(4)
)
for bij in (rotated... | [
"def symmetric(n):\n for perm in variations(range(n), n):\n yield Permutation(perm)",
"def symmetric(self):\n result = self.directed()\n result.extend([(down, up) for up, down in result])\n return Pairs(result)",
"def _iter_pairs(graph):\n for u, v in set(graph.edges_iter()):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a binary model using the configuration above. | def create_model(
input_length, input_depth, num_conv_layers, conv_filter_sizes, conv_stride,
conv_depths, max_pool_size, max_pool_stride, num_fc_layers, fc_sizes,
num_tasks, batch_norm, conv_drop_rate, fc_drop_rate
):
bin_model = binary_models.BinaryPredictor(
input_length=input_length,
... | [
"def generate_model(config_file=None, config_dict={}, initialize_site_data=None, log_level='info'):\n\n return Model(config_file, config_dict, initialize_site_data, log_level)",
"def create_model(self):\n pass",
"def create_model(self, model_config, is_training=True):\n return model_builder.build(m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets environment variable as string. | def getenv_string(setting, default=''):
return os.environ.get(setting, default) | [
"def _get_env(key: str) -> str:\n value = os.getenv(key)\n assert isinstance(value, str), (\n f\"the {key} environment variable must be set and a string, \" f\"{value=}\"\n )\n return value",
"def get_environ_value(key: str) -> str:\n assert key in os.environ, f\"{key} sh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets environment variable as boolean value. | def getenv_bool(setting, default=None):
result = os.environ.get(setting, None)
if result is None:
return default
return str2bool(result) | [
"def demand_env_var_as_bool(name: str) -> bool:\n\n value_str: str = demand_env_var(name=name).lower()\n if value_str in (\"true\", \"1\"):\n return True\n if value_str in (\"false\", \"0\"):\n return False\n raise EnvironmentVariableNotFoundError(f\"Environment variable ({name}) not boole... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle a change of the target object. This handler will remove the old observer and attach a new observer to the target attribute. If the target object is not an Atom object, an exception will be raised. | def __call__(self, change: ChangeDict) -> None:
old = None
new = None
ctype = change["type"]
if ctype == "create":
new = change["value"]
elif ctype == "update":
old = change["oldvalue"]
new = change["value"]
elif ctype == "delete":
... | [
"def update(self, observerable, object):\n print(f'observer 2: update from observable notify: {object}')",
"def update(self, observerable, object):\n print(f'observer 1: update from observable notify: {object}')",
"def __set__(self, obj, new_obj):\n old_value = getattr(obj, self.field_name)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add or override a member after the class creation. | def add_member(cls: AtomMeta, name: str, member: Member) -> None:
existing = cls.__atom_members__.get(name)
if existing is not None:
member.set_index(member.index)
member.copy_static_observers(member)
else:
member.set_index(len(cls.__atom_members__))
member.set_name(name)
# ... | [
"def add(self, member):\n raise NotImplementedError",
"def register(cls, member_name, member_cls):\n if member_name in cls.members:\n raise MemberNameConflictError(u'%s member name has conflicted.' % member_name)\n cls.members[member_name] = member_cls()",
"def __add_member(self, mem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the members dictionary for the type. Returns | def members(cls) -> Mapping[str, Member]:
return cls.__atom_members__ | [
"def _members(self):\n return {\n key: value\n for key, value in self.__dict__.items()\n if not key.startswith(\"_\")\n }",
"def members(cls) -> Dict[str, 'UserEnum']:\n return cls._member_map",
"def members(self):\n ordered = sorted(self.fields.items... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the program details in the GUI. {Boolean} Always returns True. | def __setDetails(self):
self.MainWindow.setWindowTitle("{0} {1}".format(
const.APP_NAME, const.VERSION))
return True | [
"def setup_gui_system(main_window: Any, dat_details: dict[str, dict[str, str]], config: Config) -> None:\r\n\r\n config.system_name = ''\r\n\r\n # Remove United Kingdom from the region lists, as UK is already in there.\r\n region_order_default: list[str] = [x for x in config.region_order_default if x != 'U... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delegate len() to the list | def __len__(self):
return len(self.list) | [
"def len_list(self) -> int:\n return 1",
"def __len__(self):\n return _libsbml.ListWrapperSBase___len__(self)",
"def __len__(self):\n return _libsbml.ListOf___len__(self)",
"def length(self):\n return self.list_length",
"def _size(self):\n return self.list.size",
"def Up... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delegate pop() to the list | def pop(self):
self.list.pop() | [
"def pop(self, *args, **kwargs): # real signature unknown; restored from __doc__\n pass",
"def pop_from_deque(self):",
"def pop_last(self):\n self.pop_item(-1)",
"def pop(self, *args, **kwargs):\n response = super(APIList, self).pop(*args, **kwargs)\n self._update(self.__build_args... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If avoid_repeats is False, delegates extend() to the list. Otherwise, appends all items that don't create a repeat of 2 items to the list. | def extend(self, other_list:list, avoid_repeats:bool=False):
if not avoid_repeats:
self.list.extend(other_list)
else:
for item in other_list:
if not self.list or not self.list[-1] == item:
self.list.append(item) | [
"def append_or_extend(myList: list, item):\r\n if isinstance(item, list):\r\n myList.extend(item)\r\n else:\r\n myList.append(item)\r\n\r\n return myList",
"def repeat_items(self: 'LinkedList') -> None:\n pass",
"def extend(self, other_list):\n for item in other_list:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reverses the portion of the list between start and end indexes, inclusive. | def reverse(self, start:int=0, end:int=None):
if end == None:
if start == 0:
self.list.reverse()
return
end = len(self) - 1
left = start
right = end
while left < right:
self.swap(left, right)
left += 1
... | [
"def reverse_run(lst: list, start: int, end: int) -> None:\n shrtlst = lst[start:end]\n mid = len(shrtlst) // 2\n\n for i in range(mid):\n shrtlst[i], shrtlst[-(i+1)] = shrtlst[-(i+1)], shrtlst[i]\n\n for i in range(len(shrtlst)):\n lst[i + start] = shrtlst[i]\n\n # lst = lst[:start] + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A generator that filters through the tuples under specific conditions that can be specified. | def filter(self, filters:list)->list:
for item in self.list:
use_item = True
for filter in filters:
filter_key, filter_value, filter_type = filter
if filter_type == "<" and item[filter_key] >= filter_value:
use_item = False
... | [
"def createCompoFilter(filters):\n def compoFilter(transition):\n startsOfTuples = [ () ]\n for filt in filters:\n oneLongerStartsOfTuples = []\n for sot in startsOfTuples:\n for x in filt(transition):\n oneLongerStartsOfTuples.append( sot+(x,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Quicksorts the list by outside_key, then divides the list by stable blocks of outside_key and quicksorts those blocks by inner_key. Essentially equivalent to SQL statement of SORT BY outside_key, inner_key. | def double_sort(self, outside_key:int, inner_key:int, start:int=0, end:int=None, reverse_outside:bool=False, reverse_inside:bool=False):
self.quicksort(outside_key, start, end)
if reverse_outside:
self.reverse(start, end)
self.sub_quicksort(outside_key, inner_key, start, end, reverse... | [
"def sub_quicksort(self, stable_key:int, sort_key:int, start:int=0, end:bool=None, reverse:bool=False):\n if end == None: \n end = len(self) - 1\n if start >= end:\n return\n first = start\n for index in range(start + 1, end + 1):\n if not self[index][... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Quicksorts subsets of the list grouped by a stable key. Inplace, nonrecursive. This function maintains the order of blocks of tuples having the same stable_key. Within that block, items are resorted by sort_key using quicksort(). Since quicksort() is ascending, specifying reverse = True will reverse the order within th... | def sub_quicksort(self, stable_key:int, sort_key:int, start:int=0, end:bool=None, reverse:bool=False):
if end == None:
end = len(self) - 1
if start >= end:
return
first = start
for index in range(start + 1, end + 1):
if not self[index][stable_key] ... | [
"def quicksort(self, key:int, start:int=0, end:int=None):\n if end == None:\n end = len(self) - 1\n if start >= end:\n return\n if start == end - 1:\n if self[start][key] > self[end][key]:\n self.swap(start, end)\n return\n work ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A nonrecursive, inplace version of quicksort. Note that Python has notgreat tailrecursion properties, so a recursive approach is not generally recommended. This is inplace to save on memory. Otherwise, it is a straightforward ascending quicksort of all the items between start and end indexes comparing the values in the... | def quicksort(self, key:int, start:int=0, end:int=None):
if end == None:
end = len(self) - 1
if start >= end:
return
if start == end - 1:
if self[start][key] > self[end][key]:
self.swap(start, end)
return
work = [(start, end... | [
"def quicksort(lst, start, end, num_comparison, way=0):\n\n if start < end: # if list has 2 or more items\n pivot_index = partition(lst, start, end, num_comparison, way)\n quicksort(lst, start, pivot_index-1, num_comparison, way)\n quicksort(lst, pivot_index+1, end, num_comparison, way)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines if the slope of a line is positive. | def positive_slope(line:tuple)->bool:
return line[0][1] < line[1][1] == line[0][0] < line[1][0] | [
"def is_slope(self):\n\t\tif self.high_elevation != self.low_elevation:\n\t\t\treturn True\n\t\treturn False",
"def l1_is_slope_minus1(p1, p2):\n return p2[1] - p1[1] == p1[0] - p2[0]",
"def slope(line: Line) -> float:\n rise = (line.y2 - line.y1)\n run = (line.x2 - line.x1)\n # We're trading off a ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines if a line moves up from left to right. | def is_upwards(line:tuple)->bool:
return line[1][1] > line[0][1] | [
"def _move_up(self) -> bool:\n current_agent_node = self._maze.get_player_node()\n\n if current_agent_node.y == 0:\n # Can't go up. Already on the top row\n return False\n else:\n next_node = self._maze.get_node_up(current_agent_node)\n return self._h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |