query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Runs everyday, queries db for open games last modified more than 72 hours ago and sends the game owner a reminder email | def get(self):
three_days_ago = datetime.now() - timedelta(days=3)
app_name = app_identity.get_application_id()
subject = "You have had an open game for 3 days now!"
open_games = Game.query(Game.over == False).\
filter(Game.modified < three_days_ago)
for game in ope... | [
"def notify_users_of_reminders():\n\n #Get current date into dd/mm/YYYY format.\n now = datetime.datetime.now()\n todays_date = now.strftime(\"%d/%m/%Y\")\n\n #Get current time and convert it to hh:mm.\n todays_time = now.strftime(\"%H:%M\")\n print(todays_time)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a releaseinfo.py file in the current directory | def _create_releaseinfo_file(projname, relinfo_str):
dirs = projname.split('.')
os.chdir(os.path.join(*dirs))
print 'updating releaseinfo.py for %s' % projname
with open('releaseinfo.py', 'w') as f:
f.write(relinfo_str) | [
"def create_version_file(version='unknown', gitmeta=''):\n\tfname = join(dirname(abspath(__file__)), 'MHLogin', '_version.py')\n\tf = open(fname, 'wb')\n\tf.write(VERSION_PY % {'version': version, 'gitmeta': gitmeta, })\n\tf.close()",
"def gen_version_file_in_cmd(self, target_dir):\n if not self.dry_run:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build an sdist out of a develop egg and place it in destdir. | def _build_sdist(projdir, destdir, version):
startdir = os.getcwd()
try:
os.chdir(projdir)
# clean up any old builds
cleanup('build')
_build_dist('sdist', destdir)
cleanup('build')
if sys.platform.startswith('win'):
os.chdir(destdir)
# unzi... | [
"def copy():\n put(os.path.join('dist', get_egg_name()), remote_egg_dir)",
"def _build_bdist_eggs(projdirs, destdir, hosts, configfile):\n startdir = os.getcwd()\n hostlist = hosts[:]\n try:\n if 'localhost' in hostlist:\n hostlist.remove('localhost')\n for pdir in projdir... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds binary eggs on the specified hosts and places them in destdir. If 'localhost' is an entry in hosts, then it builds a binary egg on the current host as well. | def _build_bdist_eggs(projdirs, destdir, hosts, configfile):
startdir = os.getcwd()
hostlist = hosts[:]
try:
if 'localhost' in hostlist:
hostlist.remove('localhost')
for pdir in projdirs:
os.chdir(pdir)
_build_dist('bdist_egg', destdir)
... | [
"def uploadeggs():\r\n\r\n hostout = api.env['hostout']\r\n\r\n #need to send package. cycledown servers, install it, run buildout, cycle up servers\r\n\r\n dl = hostout.getDownloadCache()\r\n with api.hide('running', 'stdout', 'stderr'):\r\n contents = api.run('ls %s/dist' % dl).split()\r\n\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an OpenMDAO release, placing the following files in the | def make_release():
parser = OptionParser()
parser.add_option("-d", "--destination", action="store", type="string",
dest="destdir",
help="directory where distributions and docs will be placed")
parser.add_option("-v", "--version", action="store", type="string",
... | [
"def release():\n # create the dist directory \n with quiet():\n local('rm -rf {}'.format(env.paths['dist']))\n local('mkdir -p {}'.format(env.paths['dist']))\n # find compiled packages\n for (dirpath, dirnames, filenames) in os.walk(env.paths['compiled']):\n files = []\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Auxiliary method to raise an evaluation error in case of an index error while reading files. | def _raise_index_error(is_gt, tracker, seq):
if is_gt:
err = 'Cannot load gt data from sequence %s, because there are not enough ' \
'columns in the data.' % seq
raise TrackEvalException(err)
else:
err = 'Cannot load tracker data from tracker %s, seq... | [
"def test_non_batching_collated_task_dataset_getitem_bad_index(\n non_batching_collated_task_dataset, index):\n with pytest.raises(IndexError, match='.*must be 0.*'):\n non_batching_collated_task_dataset[index]",
"def test_get_document_inexistent(empty_index):\n with pytest.raises(Exception):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List the members of a team | def list_members(self, id):
request = self.request_builder('orgs.teams.list_members', id=id)
return self._get_result(request) | [
"def get_members(self, team_id):\n endpoint = '/teams/{}/members'.format(team_id)\n return self.client._api_call('get', endpoint)",
"def get_team_members(self, teamId):\n\n url = f\"/teams/{teamId}/members\"\n return self.get(url)",
"def test_teams_id_team_members_get(self):\n pass",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if user is a member of a team | def is_member(self, id, user):
request = self.request_builder('orgs.teams.is_member',
id=id, user=user)
return self._bool(request) | [
"def is_team_member(session, api, team, user):\n teams = session.get(\"teams\", {})\n # Check to see if their permissions are still valid\n if teams and team in teams and TimeUtils.get_local_timestamp() < teams[team][1]:\n return teams[team][0]\n\n is_member = api.is_member(team, user)\n logge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a repo from the a team | def remove_repo(self, id, user, repo):
request = self.request_builder('orgs.teams.remove_repo',
id=id, user=user, repo=repo)
return self._delete(request) | [
"def remove(cls, repo, name ):\r\n repo.git.remote(\"rm\", name)",
"def _remove_repo(repo_name):\n\n package_manager = _get_package_manager()\n package_manager.remove_repo(repo_name)\n\n return 0",
"def remove(repository_name):\n add_or_remove(\"remove\", repository_name)",
"def gitdel():\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrite subtract operator to get proper subnet subtracting | def __sub__(self, other):
if not isinstance(other, Subnet):
raise ValueError("I'm sorry, but I'm afraid I cannot do that")
if other.subnet_mask < self.subnet_mask:
raise ValueError("We cannot subtract from a subnetmask greater than out own")
results = []
for su... | [
"def __sub__(self, tc):\n tc = TwosComplement(tc)._negative()\n return self.__add__(tc)",
"def subtract(a, b):\n return a - b",
"def subtract(operand1, operand2):\n return operand1 - operand2",
"def subtract(a, b):\n return a - b",
"def __sub__(self, other):\n return self.__add__(o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Repeat RGB weights n times. Assumes channels are dim 1 | def cycle_rgb_weights(weights, n):
slices = [(c % 3, c % 3 + 1) for c in range(n)] # slice a:a+1 to keep dims
new_weights = torch.cat([
weights[:, a:b, :, :] for a, b in slices
], dim=1)
return new_weights | [
"def repeat_weights(weights, shape):\n weights_extra = weights.unsqueeze(-1)\n return weights_extra.expand(\n weights.shape[0], shape[-1]).reshape(shape)",
"def _repeat_n(new_batch: int, data: jnp.ndarray) -> jnp.ndarray:\n return jnp.broadcast_to(data, (new_batch,) + data.shape)",
"def th_repeat(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Repeat RGB weights given a str eg. RRGGBB would repeat each weight twice | def select_rgb_weights(weights, rgb_str):
rgb_str = rgb_str.lower()
rgb_map = {'r': 0, 'g': 1, 'b': 2}
slices = [(rgb_map[c] % 3, rgb_map[c] % 3 + 1) for c in rgb_str] # slice a:a+1 to keep dims
new_weights = torch.cat([
weights[:, a:b, :, :] for a, b in slices
], dim=1)
return new_weig... | [
"def repeat(word, repetitions):\n return word * repetitions",
"def repeat_string_n_times(string, count):\r\n return string * int(count)",
"def _repeat_pattern(pattern, width):\n assert width % pattern.width == 0\n return operation.repeat(pattern, width // pattern.width)",
"def repeat_string_n_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decodes a list of string notations to specify blocks inside the network. | def decode(string_list):
assert isinstance(string_list, list)
blocks_args = []
for block_string in string_list:
blocks_args.append(BlockDecoder._decode_block_string(block_string))
return blocks_args | [
"def decode(self, string_list):\n assert isinstance(string_list, list)\n blocks_args = []\n for block_string in string_list:\n blocks_args.append(self._decode_block_string(block_string))\n return blocks_args",
"def decode(tagged_blocks):\n return [parse_tagged_block(block... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a list of BlockArgs to a list of strings. | def encode(blocks_args):
block_strings = []
for block in blocks_args:
block_strings.append(BlockDecoder._encode_block_string(block))
return block_strings | [
"def encode(self, blocks_args):\n block_strings = []\n for block in blocks_args:\n block_strings.append(self._encode_block_string(block))\n return block_strings",
"def _encode_list(source: list) -> bytes:\n result_data = b\"l\"\n\n for item in source:\n result_data += ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map EfficientNet model name to parameter coefficients. | def efficientnet_params(model_name):
params_dict = {
# Coefficients: width,depth,res,dropout
'efficientnet-b0': (1.0, 1.0, 224, 0.2),
'efficientnet-b1': (1.0, 1.1, 240, 0.2),
'efficientnet-b2': (1.1, 1.2, 260, 0.3),
'efficientnet-b3': (1.2, 1.4, 300, 0.3),
'efficien... | [
"def efficientnet_params(model_name):\n params_dict = {'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'efficientnet-b1': (1.0, 1.1, 240, 0.2), 'efficientnet-b2': (1.1, 1.2, 260, 0.3), 'efficientnet-b3': (1.2, 1.4, 300, 0.3), 'efficientnet-b4': (1.4, 1.8, 380, 0.4), 'efficientnet-b5': (1.6, 2.2, 456, 0.4), 'efficientne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the block args and global params for a given model | def get_model_params(model_name, override_params):
if model_name.startswith('efficientnet'):
w, d, s, p = efficientnet_params(model_name)
# note: all models have drop connect rate = 0.2
blocks_args, global_params = efficientnet(
width_coefficient=w, depth_coefficient=d, dropout_r... | [
"def get_model_params(model_name, override_params):\n if model_name.startswith('efficientnet'):\n w, d, _, p = efficientnet_params(model_name)\n blocks_args, global_params = efficientnet(width_coefficient=w, depth_coefficient=d, dropout_rate=p)\n else:\n raise NotImplementedError('model n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates model name. None that pretrained weights are only available for the first four models (efficientnetb{i} for i in 0,1,2,3) at the moment. | def _check_model_name_is_valid(cls, model_name, also_need_pretrained_weights=False):
num_models = 4 if also_need_pretrained_weights else 8
valid_models = ['efficientnet_b' + str(i) for i in range(num_models)]
if model_name.replace('-', '_') not in valid_models:
raise ValueError('mode... | [
"def _check_model_name_is_valid(cls, model_name):\n num_models = [18, 34, 50, 101, 152]\n valid_models = [\"resnet\" + str(i) for i in num_models]\n if model_name not in valid_models:\n raise ValueError(\"model_name should be one of: \" + \", \".join(valid_models))",
"def check_mod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes XML File of Test Cases and returns a list of UniDBTest Case Objects, with DB Connections and Cursors, to validate | def getUniDBTestCasesFromXML(inputXMLTestCasesParametersFile,dbConnection,dbCursor):
#Get Case list
testCaseListXML = XML2TC.xml2TestCaseAdapter.getTestCasesFromXMLFile(inputXMLTestCasesParametersFile)
testCaseList = XML2TC.xml2TestCaseAdapter.createTestCaseListFromXML(testCaseListXML)
#Set UniDB Conn... | [
"def parse(self):\n\n def parse_testcase(xml_object):\n testcase = xml_object\n\n tc_dict = {\n \"classname\": testcase.attrib.get(\"classname\", \"unknown\"),\n \"file\": testcase.attrib.get(\"file\", \"unknown\"),\n \"line\": int(testcase.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes Test Cases from DB and returns a list of UniDBTest Case Objects, with DB Connections and Cursors, to validate | def getUniDBTestCasesFromDB(dbSourceDataProcessor,rawListCasesFromDB,testNumber,validationTestMappingRules,dbConnection,dbCursor):
testCaseList = dbSourceDataProcessor.createTestCaseListFromSourceDB(rawListCasesFromDB,testNumber,validationTestMappingRules)
#Set UniDB Connection & Cursor (pointers) for each cas... | [
"def getUniDBTestCasesFromXML(inputXMLTestCasesParametersFile,dbConnection,dbCursor):\n\n #Get Case list\n testCaseListXML = XML2TC.xml2TestCaseAdapter.getTestCasesFromXMLFile(inputXMLTestCasesParametersFile)\n testCaseList = XML2TC.xml2TestCaseAdapter.createTestCaseListFromXML(testCaseListXML)\n\n #Set... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates a list of UniDBTest Cases and Generates an detailed report of the results. | def validateTestCaseList(testCaseList,validationTestName,outputDirectory,testLogger):
#Local Variables
logger = testLogger
uniDBValidationTestName = validationTestName
resultsarray = []
validationTestStatistics = vreport.TestStatistics(uniDBValidationTestName) #Create Validation Test Class to Log Re... | [
"def list(self):\n print \"\\nAvailable Test Cases\"\n print \"====================\"\n for case in self.cases:\n print case.__name__",
"def test_cases_list(self):\n pass",
"def run_all(self):\n failures, errors = [], []\n\n # Run each test case registered wi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes test case lists from XML and automated (stored procedure+csv) sources. Also adds DB Connnection & Cursor information | def processValidationTests(scriptLogger,inputDirectory,outputDirectory,caseSourceType,dbHost,uniDBdbName,sourceDBName,dbuser,dbPassword,inputTestParameterSettingsXML):
#Local Variables
arrayXMLTestCaseFiles = []
logger = scriptLogger
# #Setup Test Logger
# logFileName='validation_script_nt2osm.log... | [
"def getUniDBTestCasesFromXML(inputXMLTestCasesParametersFile,dbConnection,dbCursor):\n\n #Get Case list\n testCaseListXML = XML2TC.xml2TestCaseAdapter.getTestCasesFromXMLFile(inputXMLTestCasesParametersFile)\n testCaseList = XML2TC.xml2TestCaseAdapter.createTestCaseListFromXML(testCaseListXML)\n\n #Set... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests a quest load fail due to semver mismatch | def test_quest_load_version_fail(testing_quest_page):
testing_quest_page.save()
# fetch the data
doc = testing_quest_page.doc_ref.get()
data = testing_quest_page.storage_model.parse_obj(doc.to_dict())
# mess with the version
data.version = str(VersionInfo.parse(data.version).bump_major())
... | [
"def test_version_not_unknown():\n import lstchain\n assert lstchain.__version__ != 'unknown'",
"def test_check_version():\n assert check_version('0.9.4-1', '0.9.4', '>=')\n assert check_version('3.0.0rc1', '3.0.0', '<')\n assert check_version('1.0', '1.0b2', '>')",
"def test_versioning_unknown_v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests a quest load fail due to data model mismatch | def test_quest_load_data_fail(testing_quest_page):
testing_quest_page.save()
# fetch the data
doc = testing_quest_page.doc_ref.get()
data = testing_quest_page.storage_model.parse_obj(doc.to_dict())
# mess with the data
data.serialized_data = json.dumps({"this": "nonesense"})
testing_quest_... | [
"def test_quest_load_version_fail(testing_quest_page):\n testing_quest_page.save()\n\n # fetch the data\n doc = testing_quest_page.doc_ref.get()\n data = testing_quest_page.storage_model.parse_obj(doc.to_dict())\n\n # mess with the version\n data.version = str(VersionInfo.parse(data.version).bump_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check through self.outfile to see if any of the scans' heuristics exceed the values defined in __init__ | def checkScans(self, azf, azb, elf, elb):
ok = True
#read self.outfile
hfile = open("{0}.hc".format(self.projid), "r")
#save each line in self.outfile as a list, within a list called scans
scans = []
lines = hfile.readlines()[3:]
for line in lines:
scan = [x.strip() for x in line.split('|')]
scans.ap... | [
"def _check_output_consistency(self): \n\t\tfor job in range(len(self.output_files)):\n\t\t\tassert \"_1.fastq.gz\" in self.output_files[job][0], \"Output missing first strand\"\n\t\t\tassert \"_2.fastq.gz\" in self.output_files[job][1], \"Output missing second strand\"",
"def should_scan(self) -> bool:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Construct the WindowManager \param pipes The communication pipes to the PluginManager \param args Additional startup arguments | def __init__(self, pipes, args):
self.displays = {} #The display of each player
super(WindowManager, self).__init__(pipes)#initialize the PluginInterface | [
"def __init__(self, pipeline, parent):\r\n DraggableWindow.__init__(self, width=1300, height=900, parent=parent,\r\n title=\"Pipeline Visualizer\")\r\n self._pipeline = pipeline\r\n self._scroll_width = 8000\r\n self._scroll_height = 3000\r\n self._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Initialize the WindowManager \param args Should be empty Nothing to do | def initialize(self, args):
pass | [
"def __init__(self, initialTestName, *args):\n apply(QMainWindow.__init__,(self, ) + args)\n apply(BaseGUITestRunner.__init__,(self, initialTestName))\n self.mw=WdgPyUnit(self)\n self.initActions()\n self.initMenu()\n self.initStatusBar()\n self.setCentralWidget(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Display a manialink via ManialinkManager \param args the arguments that would be passed to the ManialinkManager | def displayMl(self, *args):
self.callMethod(('ManialinkManager', 'displayManialinkToLogin'), *args) | [
"def do_show(self, args):\n args = args.split(\" \")\n if args[0] == '':\n print(\"Incorrect command.\")\n return\n elif args[0] == 'device':\n if len(args) < 2:\n if len(self.topology.devices) == 0:\n print(\"No device in this ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Hide a manialink from the dipslay of a player \param args The args to hide a special manialink from the player | def hideMl(self, *args):
self.callMethod(('ManialinkManager', 'hideManialinkToLogin'), *args) | [
"def hide(*args, **kwargs):\n\n pass",
"def hide_entry(self, entry, **args):\n args.update(entry=entry)\n return self.fetch(\"/hide\", post_args=args)",
"def do_hf_unhide(self, arg):\n self.show_hidden_frames = True\n self.refresh_stack()",
"def do_hf_hide(self, arg):\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Callback for closing a window \param entries The entries in the window's manialink \param login The login of the player \param name The name of the window to close | def closeWindow(self, entries, login, name):
try:
display = self.displays[login]
try:
del display[name]
self.hideMl(name, login)
except KeyError:
self.log('error: ' + str(login) + ' has no window named "' + str(name) + '" to close')
except KeyError:
self.log('error: login ' + str(login) + ' ... | [
"def OnClose(self, event):\r\n pos.app.main.Exit()",
"def OnCloseWindow(self, event):\r\n self.data.close()\r\n sizes[self.data.__class__.__name__] = self.GetSizeTuple()\r\n self.Destroy()",
"def on_main_win_close(self):\n child_list = self.nb.winfo_children()\n for i i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Add a window to manage \param login The player to display the window to \param name The name of the window to display \param window The window instance to display \param useOldState Should the state of the replaced window be used | def __addWindow(self, login, name, window, useOldState = False):
if not (login in self.displays):
self.displays[login] = {}
if useOldState:
try:
oldWindow = self.displays[login][name]
window.setState(oldWindow.getState())
except KeyError:
pass
self.displays[login][name] = window | [
"def displayWindow(self, login, name, window, useOldState = False):\n\t\twindow.setName(name)\n\t\twindow.setUser(login)\n\t\twindow.setWindowManager(self)\n\t\tself.__addWindow(login, name, window, useOldState)\n\t\tml = window.getManialink()\n\t\tself.displayMl(ml, name, login)",
"def new_window(window_name):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Display the given window \param login The player to display the window to \param name The name of the window to display \param window The window instance to display \param useOldState Should be tried to use the state of the old window if there is one? | def displayWindow(self, login, name, window, useOldState = False):
window.setName(name)
window.setUser(login)
window.setWindowManager(self)
self.__addWindow(login, name, window, useOldState)
ml = window.getManialink()
self.displayMl(ml, name, login) | [
"def __addWindow(self, login, name, window, useOldState = False):\n\t\tif not (login in self.displays):\n\t\t\tself.displays[login] = {}\n\t\tif useOldState:\n\t\t\ttry:\n\t\t\t\toldWindow = self.displays[login][name]\n\t\t\t\twindow.setState(oldWindow.getState())\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\tself.dis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Display a paged window \param login The player to display tdhe window to \param name The name of the window \param title The title of the window \param size The size of the window \param pos The upper left corner of the window \param pages A list of pages (manialinks) \param useOldState Should be tried to use th... | def displayPagedWindow(self, login, name, title, size, pos, pages, useOldState = False):
window = PagedWindow(title, pages)
window.setName(name)
window.setSize(size)
window.setPos(pos)
self.displayWindow(login, name, window, useOldState) | [
"def displayWindow(self, login, name, window, useOldState = False):\n\t\twindow.setName(name)\n\t\twindow.setUser(login)\n\t\twindow.setWindowManager(self)\n\t\tself.__addWindow(login, name, window, useOldState)\n\t\tml = window.getManialink()\n\t\tself.displayMl(ml, name, login)",
"def __addWindow(self, login, n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Display lines in a window \param login The login of the player to display to \param name The name of the window \param size The size of the window \param pos The upper left corner of the window \param rows The rows to display \param rowsPerPage The number of rows to display per page \param useOldState Should be ... | def displayLinesWindow(self, login, name, title, size, pos, rows, rowsPerPage, useOldState = False):
window = LinesWindow(title)
window.setName(name)
window.setSize(size)
window.setPos(pos)
window.setLines(rows, rowsPerPage)
self.displayWindow(login, name, window, useOldState) | [
"def displayTableWindow(self, login, name, title, size, pos, rows, rowsPerPage, \n\t\t\t\t\t\tcolumnWidths, headLine = None, useOldState = False):\n\t\twindow = TableWindow(title)\n\t\twindow.setName(name)\n\t\twindow.setSize(size)\n\t\twindow.setPos(pos)\n\t\twindow.setTable(rows, rowsPerPage, columnWidths, headLi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Display manialink elements in a table \param login The player to display to \param name The windows name \param title The title of the window \param size The size of the window \param pos The upper left corner of the window \param rows The rows to display (each is an iterable of columns) \param rowsPerPage The n... | def displayTableWindow(self, login, name, title, size, pos, rows, rowsPerPage,
columnWidths, headLine = None, useOldState = False):
window = TableWindow(title)
window.setName(name)
window.setSize(size)
window.setPos(pos)
window.setTable(rows, rowsPerPage, columnWidths, headLine)
self.displayWindow(lo... | [
"def displayTableStringsWindow(self, login, name, title, size, pos, rows, \n\t\t\t\t\t\t\t\trowsPerPage, columnWidths, headLine = None, useOldState = False):\n\t\twindow = TableStringsWindow(title)\n\t\twindow.setName(name)\n\t\twindow.setSize(size)\n\t\twindow.setPos(pos)\n\t\twindow.setTableStrings(rows, rowsPerP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Display strings in a table \param login The player to display to \param name The windows name \param title The title of the window \param size The size of the window \param pos The upper left corner of the window \param rows The rows to display (each is an iterable of columns) \param rowsPerPage The number of ro... | def displayTableStringsWindow(self, login, name, title, size, pos, rows,
rowsPerPage, columnWidths, headLine = None, useOldState = False):
window = TableStringsWindow(title)
window.setName(name)
window.setSize(size)
window.setPos(pos)
window.setTableStrings(rows, rowsPerPage, columnWidths, headLine)
... | [
"def displayTableWindow(self, login, name, title, size, pos, rows, rowsPerPage, \n\t\t\t\t\t\tcolumnWidths, headLine = None, useOldState = False):\n\t\twindow = TableWindow(title)\n\t\twindow.setName(name)\n\t\twindow.setSize(size)\n\t\twindow.setPos(pos)\n\t\twindow.setTable(rows, rowsPerPage, columnWidths, headLi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\brief Change the page of a multiPage window \param entries The entries of the manialink \param login The login of the calling player \param name The name of the window \param pageNumber The number of the page to change to | def changePage(self, entries, login, name, pageNumber):
try:
display = self.displays[login]
try:
window = display[name]
try:
window.setCurrentPage(pageNumber)
self.displayMl(window.getManialink(), name, login)
except AttributeError:
self.log('error: ' + str(name) + ' does not seem to ... | [
"def displayPagedWindow(self, login, name, title, size, pos, pages, useOldState = False):\n\t\twindow = PagedWindow(title, pages)\n\t\twindow.setName(name)\n\t\twindow.setSize(size)\n\t\twindow.setPos(pos)\n\t\tself.displayWindow(login, name, window, useOldState)",
"def pagination_number_set(page_name: str, pagin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adv. examples stored in "data/adversarial/{att}_{ds}.npy" | def attack(self, attack, nExamples=100):
adversarialExamples = attack.attack(
ds.test_data[:nExamples],
get_labs(ds.test_data[:nExamples])
)
if not os.path.exists("data"):
os.mkdir("data")
if not os.path.exists("data/adversarial"):
os.mkdi... | [
"def train(self, examples):\n pass",
"def create_adversarials(model, data, config, name, path, save,\n target_classes, lots_targets):\n num_classes, device = model.num_classes, data.tensors[0].device\n images = data.tensors[0].to(device)\n labels = data.tensors[1].to(device)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluate defense against attack | def evaluate(self, defense, attack):
advPath = 'data/adversarial/{}_{}.npy'.format(
attack.name,
self.dataset.name
)
if not os.path.exists(advPath):
self.attack(attack, nExamples=100)
adversarialExamples = np.load(advPath) | [
"def apply_attack(self, data):",
"def assess_defense_single(self):\n # Attack; later we need to be able to handle multiple attacks.\n self.attack_successful = False\n try:\n match = re.search(self.defense, self.attack[-1]).group()\n except AttributeError or TypeError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a land use raster and a set of weights, applies the weights to each land use type then sets everything else to 1 so that the raster can be used as a multiplier later | def make_weight_raster(land_use, modifications):
land_use_array = compatibility.raster_to_numpy_array(land_use)
land_use_array += 10000 # offset everything by 10000 so we can identify everything that's still a default later
for modification in modifications:
land_use_array[
land_use_arr... | [
"def weight_images(im_dir, wt_dir, weight_dir, im_weight_dir, wt_weight_dir, imtype='intbgsub', wttype='rrhr'):\n im_suff, wt_suff = '*-{}.fits'.format(imtype), '*-{}.fits'.format(wttype)\n imfiles = sorted(glob.glob(os.path.join(im_dir, im_suff)))\n wtfiles = sorted(glob.glob(os.path.join(wt_dir, wt_suff)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This was the first version of the convolution function I wrote. It takes an approach I thought would be faster originally and takes the loading matrix for each year and multiplies it against the entire URF matrix representing the future relative to the year, then adds its result to the output. That would probably take ... | def convolve_and_sum_slow(loadings, unit_response_functions=None):
loadings = loadings.T
print(loadings.shape)
print("Convolving")
if (
unit_response_functions is None
): # this logic is temporary, but have a safeguard so it's not accidentally used in production
if settings.DEBUG:
... | [
"def convolve(self, kernel):\n kernel_rows, kernel_cols = kernel.shape\n img_rows, img_cols = self.img_array.shape\n\n print(\"imgae shape: \", self.img_array.shape)\n print(self.img_array[:10,:10])\n\n # flip the kernel\n flipped_kernel = np.zeros(kernel.shape)\n \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function takes in the filename of the data (stored with sklearnjoblib), checks the data for outliers, establishes the interpolation grid, computes the nearest neighbours between all data points and that grid, and outputs the necessary values for using BLISS The `flux` is assumed to be pure stellar signal i.e. no p... | def setup_BLISS_inputs_from_file(dataDir, xBinSize=0.01, yBinSize=0.01, xSigmaRange=4, ySigmaRange=4):
points, fluxes = BLISS.extractData(dataDir)
points, fluxes = BLISS.removeOutliers(points, fluxes, xSigmaRange, ySigmaRange)
knots = BLISS.createGrid(points, xBinSize, yBinSize)
knotTree = spa... | [
"def interpolate(in_path, layer='all', out=None, scale_factor=0.1, \n function='invdist', smooth=0, params=None, bounds=None, \n buffer=25, z_stats=True, res_plot=True, \n grid_id_name='GRIDMET_ID', grid_res=None, options=None, \n grid_meta_path=None):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
NEW word2vec_by_period using skipgram txt files DOES NOT YET IMPLEMENT word_size!!! | def word2vec_by_period(self,bin_years_by=None,word_size=None,skipgram_n=10, year_min=None, year_max=None):
from llp.model.word2vec import Word2Vec
from llp.model.word2vecs import Word2Vecs
if not year_min: year_min=self.year_start
if not year_max: year_max=self.year_end
path_model = self.path_model
model_... | [
"def apply_word2vec_model(w2v_txt_file):\r\n\r\n\tcount = 0\r\n\ttrain_documents = []\r\n\tembedding_size = 300\r\n\r\n\t#read in opinion file for word2vec training\r\n\twith open(w2v_txt_file, encoding=\"utf8\", errors='ignore') as fp:\r\n\t\tline = fp.readline()\r\n\r\n\t\twhile line:\r\n\t\t\t# print(line)\r\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if a cell is on the board. | def is_cell_on_board(cell, board_shape): # TODO: Remove
return (0, 0) <= cell < board_shape | [
"def check_on_board(cell):\n if cell[0] > 4 or cell[0] < -4 or cell[1] > 4 or cell[1] < -4:\n return False\n if cell[0] + cell[1] > 4 or cell[0] + cell[1] < -4:\n return False\n\n return True",
"def inBoard(self, row, col):\n return 0 <= row < self.rows and 0 <= col < self.cols",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform the action of the player to a move. The move is made and the reward computed. | def make_move(state, action, player, rewarding_move=False): # TODO : done and next_is_reward can be removed as
# they are in the state object
board = state.get_board()
json_action = action.get_json_action()
action = action.get_action_as_dict()
captured = None
reward = 0
... | [
"def take_action(self, idx, state):\n\n # Predict action and return embedding using RL model used\n action, embed = self.model.predict_action(idx, state)\n\n # Convert embedding from tensor to numpy\n temp = embed.cpu().numpy()\n\n # Set embeddings to current player\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
extract the patient names from csv files | def obtain_patient_names():
split_names = ['train', 'valid', 'test']
for split_name in split_names:
csv_file = 'config/fetal_hc_train_{0:}.csv'.format(split_name)
with open(csv_file, 'r') as f:
lines = f.readlines()
data_lines = lines[1:]
patient_names = []
... | [
"def get_patients_in_csv_file(src_directory, code_extract_func):\n input_list = extract.load(src_directory)\n\n # Validate the number of distinct files here\n filenames = set()\n\n for i, row in enumerate(input_list):\n if i == 0:\n continue\n filename = code_extract_func(row[0]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Factory method for constructing a new baseclient plus the corresponding view; Typically used in combination with pools | def view_with_client_from_config(cls, conf, config_section, logger=None):
if cls == PapiViewClient:
# we're implementing this factory in the base-class, so we don't
# have to copy-paste it into every single view. This means that
# someone could invoke it in the abstract base,... | [
"def create_client(self):",
"def _base(self):\n from hubspot3.base import BaseClient\n\n return BaseClient(**self.auth, **self.options)",
"def __init__(self, client):\n super(BaseManager, self).__init__()\n self.client = client",
"def make_client(self, context):\n return Cli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the 'folderPath' exists and it's valid folder | def isFolderValid(folderPath):
if os.path.isdir(folderPath):
return True
else:
return False | [
"def folderExists(self, folderPath: unicode) -> bool:\n ...",
"def check_folder_exists(path):\n if not os.path.isdir(path):\n raise ValueError(\"Error: \\\"\" + path + \"\\\" is not a folder\")",
"def check_folder(path):\n if not path.exists() or not path.is_dir():\n path.mkdir()",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes one train object with a 'trip_update' object from the MTA data, a dictionary of all the stop IDs and names in the subway system, and the index of the train in the master list of train objects. | def __init__(self, trip_update, stops, position_in_list):
self.trip_update = trip_update
self.stops = stops
self.routeID = str(self.trip_update.trip.route_id)
# A minor quirk in the MTA's data is fixed here. S trains were listed as GS for some reason
if self.routeID == "GS":
... | [
"def __init__(self, trip_id, starttime, stoptime, bikeid,\n tripduration, from_station, to_station, \n usertype, gender, birthyear):\n\n self.trip_id = trip_id\n self.starttime = starttime\n self.stoptime = stoptime\n self.bikeid = bikeid\n self.tri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the stop number (the nth stop on the train's remaining route) as an argument, this method prints out a message containing the train's direction, route number, station, and arrival time. | def showInfo(self, stop_number):
if self.arrivalTime == '': # At origin terminals, there will only be a departure time listed
if self.getArrivalTime(stop_number) == '00':
print "There is a", self.getDirection(), self.routeID, "train departing from", self.getStop(stop_number), "now."
... | [
"def print_traveled_route(self):\n print(\"Actor #%d:\" % self.actor_id)\n print(\"\\tNode: %d, timestamp: %f\" %\n (self.traveled_nodes[0][self.NODE_INDEX],\n self.traveled_nodes[0][self.TIME_INDEX]))\n\n for i in range(1, len(self.traveled_nodes)):\n prin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method, given a stop number, returns the number of minutes it will take for the train to arrive at the specified station. | def getArrivalTime(self, stop_number):
# Get absolute POSIX time from MTA data
self.arrivalTime = str(self.trip_update.stop_time_update[stop_number].arrival)
departureTime = str(self.trip_update.stop_time_update[stop_number].departure)
if self.arrivalTime != '': # Some stops only have a ... | [
"def find_subway_time(station):\n\tname = station.get('name')\n\tif name not in STATION_DICT.keys():\n\t\treturn None\n\n\tstation_id = STATION_DICT[name]\n\n\tsub_url = 'http://mtaapi.herokuapp.com/api?id=' + station_id\n\n\tresponse = requests.get(sub_url)\n\tsubway_json = json.loads(response.text)\n\tarrivals = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets all upcoming stops for the train. Returns a list of form [stop number, station name]. | def getAllStops(self):
all_stops = []
# Iterate through all the stop_time_update objects in trip_update
for i in range(len(self.trip_update.stop_time_update)):
stop = self.getStop(i)
if stop not in all_stops:
all_stops.append([i, stop])
return all_... | [
"def stops(self):\n self.client.get(url=\"/stops/\")",
"def get_calling_stops(self, train):\n try:\n calling_stops = []\n stops = train.subsequentCallingPoints\n stop_list = stops.callingPointList[0][0]\n for stop in stop_list:\n calling_sto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the nth stop for the train given the stop number as an argument. | def getStop(self, i):
stopID = self.trip_update.stop_time_update[i].stop_id
stop = self.stops[stopID]
return stop | [
"def _get_stop_index(self, tstop):\n i = bisect_right(self.data['epoch'], tstop)\n if not (i >= self.data.shape[0]):\n return i\n else:\n return -1\n raise ValueError(f'{tstop} did not match any value.')",
"def _get_nth(self, n):\n return self.start + ((n -... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the direction of the train. Returns 'N' or 'S'. | def getDirection(self):
if 'N' in str(self.trip_update.trip.trip_id):
direction = 'northbound'
if 'S' in str(self.trip_update.trip.trip_id):
direction = 'southbound'
return direction | [
"def direction(self, direction = None):\r\n if direction in [N, S, E, W]:\r\n self._direction = direction\r\n return self._direction",
"def get_direction(self):\n return self.direction",
"def current_direction(self) -> str:\n if self.tuya_device.status[DPCODE_FAN_DIRECTION... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the node's datum value, creating the attribute if not already defined. | def setNodeDatum(self, node, value):
if not cmds.attributeQuery('datum', node=node, exists=True):
cmds.addAttr(node, longName='cadence_datum', shortName='datum', niceName='Datum')
cmds.setAttr(node + '.datum', value) | [
"def setattr(self, node, attr, value):\n node.set(attr, value)",
"def set_attribute(self, node, name, value):\r\n return self._send({'name': 'setAttribute', 'args': [node, name, value]})",
"def set_data(node, value):\n node['data'] = value",
"def set_node_attribute(\n node: MatterNode,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the show_history of this FinancialPictureRequest. | def show_history(self, show_history):
self._show_history = show_history | [
"def family_history(self, family_history):\n\n self.logger.debug(\"In 'family_history' setter.\")\n\n self._family_history = family_history",
"def history(self, history):\n self._history = history",
"def history(self, history):\n\n self._history = history",
"def allow_view_history(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the currency_conversion of this FinancialPictureRequest. | def currency_conversion(self, currency_conversion):
self._currency_conversion = currency_conversion | [
"def currency(self, currency):\n\n self._currency = currency",
"def card_currency(self, card_currency):\n\n self._card_currency = card_currency",
"def currency_rate(self, currency_rate):\n\n self._currency_rate = currency_rate",
"def set_adjustment_charge_currency(self, currency):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the show_category_breakdown of this FinancialPictureRequest. | def show_category_breakdown(self, show_category_breakdown):
self._show_category_breakdown = show_category_breakdown | [
"def display_category(self, display_category):\n\n self._display_category = display_category",
"def categories_display(self, categories_display):\n\n self._categories_display = categories_display",
"def set_charge_category(self, charge_category):\n self.single_selection_from_kendo_dropdown(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the show_change of this FinancialPictureRequest. | def show_change(self, show_change):
self._show_change = show_change | [
"def set_change(self, a_change):\n self.set_parameter('change', a_change)\n return self",
"def show_new(self, show_new):\n if show_new is None:\n raise ValueError(\"Invalid value for `show_new`, must not be `None`\") # noqa: E501\n\n self._show_new = show_new",
"def toggl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the household_id of this FinancialPictureRequest. | def household_id(self, household_id):
self._household_id = household_id | [
"def picture_id(self, picture_id):\n\n self._picture_id = picture_id",
"def cover_picture_id(self, cover_picture_id):\n self._cover_picture_id = cover_picture_id",
"def loan_id(self, loan_id):\n\n self._loan_id = loan_id",
"def bank_id(self, bank_id):\n\n self._bank_id = bank_id",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the create_log of this FinancialPictureRequest. | def create_log(self, create_log):
self._create_log = create_log | [
"def set_log(self, log):\n self.log = log",
"def log_date(self, log_date):\n\n self._log_date = log_date",
"def create_date(self, create_date):\n\n self._create_date = create_date",
"def signing_log(self, signing_log):\n\n self._signing_log = signing_log",
"def create_at(self, cr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take the music_data file from convert_txt_to_data and sort it by user choice Put it into a decque/list/tuple/dictionary/whatever | def sort_music_data(sort_by = None):
for lists in read_file():
print(lists)
pass | [
"def process(filename):\r\n x = open(filename, \"r\")\r\n words_from_songs=[]\r\n for line in x:\r\n array =line.split(\":\")\r\n songid= array[0]\r\n lyrics=array[1]\r\n lyrics=lyrics.replace(\"\\n\", \"\")\r\n lyrics=lyrics.split(\" \")\r\n for i in range(len(lyr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort what the user wants to see by argument with a loop | def sort_by_user_arg(user_argument = 'sort by ex. artist'):
pass | [
"def shell_sort(input_list):",
"def sort_list(user_input):\n user_input.sort()\n return user_input # added a return statement for a cleaner looking main function",
"def main():\n\ta = sys.argv[1:]\n\tsort(a)\n\tassert is_sorted(a)\n\t_show(a)",
"def choice_sort(A):\n pass",
"def sort(results, key)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A decorator that appends conditions to the auth.require config variable. | def require(*conditions):
def decorate(f):
if not hasattr(f, '_cp_config'):
f._cp_config = dict()
if 'auth.require' not in f._cp_config:
f._cp_config['auth.require'] = []
f._cp_config['auth.require'].extend(conditions)
return f
return decorate | [
"def require(*conditions):\r\n def decorate(f):\r\n if not hasattr(f, '_cp_config'):\r\n f._cp_config = dict()\r\n if 'auth.require' not in f._cp_config:\r\n f._cp_config['auth.require'] = []\r\n f._cp_config['auth.require'].extend(conditions)\r\n return f\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
subclasses must implement package provisioning logic | def _provision_package(self): | [
"def packages():",
"def __init__(self, section):\n # /dist/install_package.sh <package name>\n self.package = section.package\n cmd = \"%s %s\" % (self.installPackageScript, self.package)\n super(PackageConfig, self).__init__(cmd)",
"def test_setup_package(self):\n pluggable_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
run commands before entering chroot | def _pre_chroot_block(self):
pass | [
"def _post_chroot_block(self):\n pass",
"def chroot(path):\n pass",
"def chroot(cmd, dest_dir, stdin=None, stdout=None):\n run = ['chroot', dest_dir]\n\n for element in cmd:\n run.append(element)\n\n try:\n proc = subprocess.Popen(run,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
commands to run after the exiting the chroot | def _post_chroot_block(self):
pass | [
"def cleanup():\n call(\"rc-update delete firstboot default\")\n print(\"Rebooting in 5 seconds...\")\n sleep(5)\n call(\"reboot\")",
"def reset_chroot(self):\n try:\n if self.HAS_CHROOT:\n task = reset_ldap_users.post()\n MonQTask.wait_for_tasks(query={... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
execute every python or shell script found in scripts_dir 1. run python or shell scripts in lexical order | def _run_provision_scripts(self, scripts_dir):
script_files = sorted(glob(scripts_dir + '/*.py') + glob(scripts_dir + '/*.sh'))
if not script_files:
log.debug("no python or shell scripts found in {0}".format(scripts_dir))
else:
log.debug('found scripts {0} in {1}'.format... | [
"def run_all_scripts(dir=\".\", autodestruct=True, condition=None, ignore=[]):\n if condition is None:\n condition = lambda file: file.endswith(\".py\") and not file.startswith(\"_\")\n os.chdir(dir)\n files = sorted([file for file in os.listdir(dir) if condition(file)])\n for file in files:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if context.package.arg ends with a package extension | def _local_install(self):
config = self._config
ext = config.plugins[self.full_name].get('pkg_extension', '')
if not ext:
return False
# ensure extension begins with a dot
ext = '.{0}'.format(ext.lstrip('.'))
return config.context.package.arg.endswith(ext) | [
"def is_package(self):\n return self.relpath.endswith(\"__init__.py\")",
"def has_extras(self):\n return any(map(utils.assert_package_has_extras, self.pkg_arguments))",
"def is_package(self, fullmodname):\n submodname, is_package, relpath = self._get_info(fullmodname)\n return is_package",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dowload url to context.package.dir | def _download_pkg(self, context):
pkg_url = context.package.arg
dst_file_path = context.package.full_path
log.debug('downloading {0} to {1}'.format(pkg_url, dst_file_path))
download_file(pkg_url, dst_file_path, context.package.get('timeout', 1), verify_https=context.get('verify_https', F... | [
"def _package_url(self, package):",
"def get_url(self, package):\n return self.request.app_url('api/package', package.name,\n package.version, 'download', package.filename)",
"def _process_resource(self, url):\n url_parts = urlparse.urlsplit(url)\n rel_pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regular expression component to capture a number expressed in Hebrew letters | def hebrew_number_regex():
rx = u""" # 1 of 3 styles:
((?=[\u05d0-\u05ea]+(?:"|\u05f4|'')[\u05d0-\u05ea]) # (1: ") Lookahead: At least one letter, followed by double-quote, two single quotes, or gershayim, followed by one letter
\u05ea*(?:"|\u05f4|'')? ... | [
"def zh_num2digit(string):\n for match in zh_nums_iter(string):\n num_str = match.group(0)\n digit_num = parse_zh_num(num_str)\n if digit_num is None:\n continue\n string = string.replace(num_str, str(digit_num), 1)\n return string",
"def 取龜(我):\n return 我",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Casts a ray in the world defined by p0 and p1 and calls callback with the body, normal, collision id, user data and intersection distance | def RayCast( self, p0, p1, callback, userdata):
self.raycastUserData = userdata
self.raycastCallback = callback
self.CppRayCast.__call__(p0[0], p0[1], p0[2], p1[0], p1[1], p1[2]) | [
"def __init__(self, ray, otherobject, distance, point, normal):\n self.ray = ray\n self.otherobject = otherobject\n self.distance = distance\n self.point = point\n self.normal = normal.normalized()",
"def intersect(self, ray):\n # TODO A5 (Step3 and Step4) implement this ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get KoBERT ONNX file path after downloading | def get_onnx_kobert_model(cachedir=".cache"):
onnx_kobert = {
"url": "s3://skt-lsl-nlp-model/KoBERT/models/kobert.onnx1.8.0.onnx",
"chksum": "6f6610f2e3b61da6de8dbce",
}
model_info = onnx_kobert
model_path, is_cached = download(
model_info["url"], model_info["chksum"], cachedir=... | [
"def get_download_path() -> Path:\n return Path(\n os.environ.get(\"MXNET_HOME\", str(Path.home() / \".mxnet\" / \"gluon-ts\"))\n )",
"def maybe_download():\n\n print(\"Downloading Inception 5h Model ...\")\n download.maybe_download_and_extract(url=data_url, download_dir=data_dir)",
"def _dow... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a page (id, title, categories, article) Put it into a given sqlite3 database | def parsePage(elem, db: WikiDB = None, filter: str = "births") -> None:
if exclude(elem): return # Only iterate over articles
# Parse out basic information
pageid = elem.find("id").text
title = elem.find('title').text
article = elem.find('revision/text').text
# Only insert the data if the cat... | [
"def save(self):\n database = Database()\n check_query = \"\"\"SELECT id FROM page WHERE img_url=%s\"\"\"\n insert_query = \"\"\"INSERT INTO page VALUES (NULL, %s, %s, %s)\"\"\"\n for page in self.pages:\n result = database.execute(check_query, [page])\n if result i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the lists of categories for a wiki article page | def getCategories(page: wtp._wikitext.WikiText) -> List[str]:
# Categories are always listed at the bottom of the wikipedia article
# So the first "[[Category: ...]]" you find everything after it will be categories
s = page.string
categories = s[s.find("[[Category:"):].split("\n")
return categories | [
"def get_categories(self, page: str) -> Union[List[str], Dict[str, List[str]]]:\n\n r_params = {\n \"action\": \"query\",\n \"prop\": \"categories\",\n \"titles\": page,\n \"format\": \"json\",\n \"redirects\": \"true\"\n }\n\n skip_categor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Requires a property, value, uncertainty and unit and returns boolean. Returns the claim that fits into the defined precision or None. | def check_claim(item, prop, target):
item_dict = item.get()
try:
claims = item_dict['claims'][prop]
except KeyError:
return None
for claim in claims:
if claim.target_equals(target):
return claim
return None | [
"def test_output_ensure_output_for_property(profile_from_dataset):\n output = CheckOutput(profile=profile_from_dataset)\n\n output.ensure_output_for_property(\"PRES\")\n flags = output.get_output_flags_for_property(\"PRES\")\n\n assert flags is not None\n assert isinstance(flags, ma.MaskedArray)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fit a relation between ISO speed and normalisation. Currently two types of model are supported, namely linear and 'knee'type. Both are fitted and the best is chosen. | def fit_iso_normalisation_relation(isos, ratios, ratios_errs=None, min_iso=50, max_iso=50000):
# Fit a linear model
parameters_linear, covariance_linear = np.polyfit(isos, ratios, 1, cov=True)
errors_linear = np.sqrt(np.diag(covariance_linear))
model_linear = generate_linear_model(*parameters_linear)
... | [
"def test_Scale_model_set_linear_fit(Model):\n\n init_model = Model(factor=[0, 0], n_models=2)\n\n x = np.arange(-3, 7)\n yy = np.array([1.15 * x, 0.96 * x])\n\n fitter = fitting.LinearLSQFitter()\n fitted_model = fitter(init_model, x, yy)\n\n assert_allclose(fitted_model.parameters, [1.15, 0.96],... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalise data at a single ISO speed using the lookup table. | def normalise_single_iso(data, iso, lookup_table):
normalisation_factor = lookup_table[1][iso]
new_data = data / normalisation_factor
return new_data | [
"def normalise_iso_general(lookup_table, isos, data):\n if isinstance(isos, (int, float)):\n data_normalised = normalise_single_iso (data, isos, lookup_table)\n else:\n data_normalised = normalise_multiple_iso(data, isos, lookup_table)\n\n return data_normalised",
"def normalise_multiple_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalise data at multiple ISO speeds using the lookup table. `data` and `isos` are assumed to have the same length, i.e. each element of `data` has one associated ISO speed in `isos`. | def normalise_multiple_iso(data, isos, lookup_table):
as_list = [normalise_single_iso(data_sub, ISO, lookup_table) for data_sub, ISO in zip(data, isos)]
as_array = np.array(as_list)
return as_array | [
"def normalise_iso_general(lookup_table, isos, data):\n if isinstance(isos, (int, float)):\n data_normalised = normalise_single_iso (data, isos, lookup_table)\n else:\n data_normalised = normalise_multiple_iso(data, isos, lookup_table)\n\n return data_normalised",
"def normalise_single_iso... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalise data for ISO speed in general. Uses either `normalise_single_iso` or `normalise_multiple_iso` based on the number of isos given. | def normalise_iso_general(lookup_table, isos, data):
if isinstance(isos, (int, float)):
data_normalised = normalise_single_iso (data, isos, lookup_table)
else:
data_normalised = normalise_multiple_iso(data, isos, lookup_table)
return data_normalised | [
"def normalise_multiple_iso(data, isos, lookup_table):\n as_list = [normalise_single_iso(data_sub, ISO, lookup_table) for data_sub, ISO in zip(data, isos)]\n as_array = np.array(as_list)\n return as_array",
"def normalise_single_iso(data, iso, lookup_table):\n normalisation_factor = lookup_table[1][is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the ISO normalization lookup table located at `root`/calibration/iso_normalisation_lookup_table.npy If `return_filename` is True, also return the exact filename the bias map was retrieved from. | def load_iso_lookup_table(root, return_filename=False):
filename = root/"calibration/iso_normalisation_lookup_table.npy"
table = np.load(filename)
if return_filename:
return table, filename
else:
return table | [
"def load_iso_data(root, return_filename=False):\n filename = root/\"intermediaries/iso_normalisation/iso_data.npy\"\n data = np.load(filename)\n if return_filename:\n return data, filename\n else:\n return data",
"def load_iso_model(root, return_filename=False):\n filename = root/\"c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the ISO normalization function, the parameters of which are contained in `root`/calibration/iso_normalisation_model.dat If `return_filename` is True, also return the exact filename the bias map was retrieved from. | def load_iso_model(root, return_filename=False):
filename = root/"calibration/iso_normalisation_model.dat"
as_array = np.loadtxt(filename, dtype=str)
model_type = as_array[0,0]
parameters = as_array[1].astype(np.float64)
errors = as_array[2].astype(np.float64)
model = model_generator[model_t... | [
"def load_iso_data(root, return_filename=False):\n filename = root/\"intermediaries/iso_normalisation/iso_data.npy\"\n data = np.load(filename)\n if return_filename:\n return data, filename\n else:\n return data",
"def load_iso_lookup_table(root, return_filename=False):\n filename = r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load ISO normalisation data from `root`/intermediaries/iso_normalisation/iso_data.npy If `return_filename` is True, also return the exact filename the bias map was retrieved from. | def load_iso_data(root, return_filename=False):
filename = root/"intermediaries/iso_normalisation/iso_data.npy"
data = np.load(filename)
if return_filename:
return data, filename
else:
return data | [
"def load_iso_model(root, return_filename=False):\n filename = root/\"calibration/iso_normalisation_model.dat\"\n as_array = np.loadtxt(filename, dtype=str)\n model_type = as_array[0,0]\n parameters = as_array[1].astype(np.float64)\n errors = as_array[2].astype(np.float64)\n model = model_gene... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
853 ACTRESS_NAME 楓姫輝/白石里佳 小泉ありさ/新庄小雪 SITE_NAME DVDRip WOMAN INSIDE LINK_PATH GS670 歌舞伎町整体治療院 35(ゴーゴーズ) NoFile DMM月AVステーション【TMA】丸の内美人女子社員生中出し [ID051 20080206] 148koyuki CONTENTS_DATE 2009/05/01 20090601 INSERT INTO MOVIE_CONTENTS (ID, ACTRESS_NAME, SITE_NAME, LINK_PATH, CONTENTS_DATE) VALUES (21, '', 'SCUTE', 'ps4_93_yo... | def execute_contents(self):
self.mssql_cursor.execute('SELECT ID ' \
' , ACTRESS_NAME, SITE_NAME, LINK_PATH, CONTENTS_DATE ' \
'FROM MOVIE_CONTENTS ')
row = self.mssql_cursor.fetchone()
idx = 0
row_ok = 0
row... | [
"def insertClip(dbConnection, audiourl, podcastName, description, parsedDate, title):\n try:\n cursor = dbConnection.cursor()\n title = title.replace(\"'\", \"''\")\n cursor.execute(\"INSERT INTO transcriptions(audiourl, realtimefactor, podcastname, transcription, description... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
start time we only want to proceed when we are at the beginning of a minute, so stuck until seconds is at beginning of minute | def start():
beginning_of_min = False
while beginning_of_min == False:
start_at = datetime.now()
start_time_sec = start_at.strftime("%H:%M:%S")
start_time_min = start_at.strftime("%H:%M")
if start_time_sec[-2:] == '00':
beginning_of_min = True
print("S... | [
"def minute(caller):\n sleep = random.choice(range(1, 1 * 60))\n hevlog.logging.debug('[{}] sleeping for {} seconds'.format(caller, sleep))\n return time.sleep(sleep)",
"def startTimer():\n\ttimerAmount=1\n\t#Calc future time\n\tfutureTime=addTimeToCurrent(\"minutes\",timerAmount)\n\tcurrentT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wraps action method with zone based condition. | def if_action(hass, config):
entity_id = config.get(CONF_ENTITY_ID)
zone_entity_id = config.get(CONF_ZONE)
if entity_id is None or zone_entity_id is None:
logging.getLogger(__name__).error(
"Missing condition configuration key %s or %s", CONF_ENTITY_ID,
CONF_ZONE)
re... | [
"def _apply_action(self, action):\n raise NotImplementedError()",
"def stateguard(action_guard):\n\n def wrap(action_method):\n\n @functools.wraps(action_method)\n def guard_wrapper(self, *args):\n if not action_guard(self):\n return (False, True, ())\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if state is in zone. | def _in_zone(hass, zone_entity_id, state):
if not state or None in (state.attributes.get(ATTR_LATITUDE),
state.attributes.get(ATTR_LONGITUDE)):
return False
zone_state = hass.states.get(zone_entity_id)
return zone_state and zone.in_zone(
zone_state, state.attrib... | [
"def _zone_in_states(self, state_list):\n if self.get_state() not in state_list:\n raise ZoneException(\"Zone '%s' must be in one of states: %s.\"\\\n \"Current state is %s.\" %\n (self.get_name(), str(state_list), str(self.get_state())))",
"def exists(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Erstellt simplen baseline tfidfbasierten unigram SVM classifier mit 10fold crossvalidation auf preprocessed germeval.train dataset | def createBaselineClassifier(self, bigram=False):
tweets, labels = self.read_corpus()
ten_folds = self.get_n_folds(tweets, labels)
if(bigram):
print("Baseline: tf-idf bigram SVM")
self.write_label_to_csv("Baseline: tf-idf bigram SVM")
bow_transformer... | [
"def svm_clf_training(max_features, data):\r\n X_train, y_train, X_test, y_test = data\r\n clf = Pipeline([('feature_selection', SelectKBest(score_func=chi2, k=max_features)),\r\n ('clf', svm.SVC(C=1., kernel='linear'))])\r\n\r\n vectorizer = CountVectorizer(ngram_range=(1, 2), lowercase... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes webpage url, loads it with web chrome driver on given maximum waiting time (by default 60sec) and outputs html page source. | def get_page_source(self, url: str, target_class: str, waiting_time=60) -> str:
if self.get_status():
pass
else:
self.__driver = webdriver.Chrome(self.__driver_path)
try:
self.__driver.get(url)
except TimeoutException:
print(f"URL LOADING... | [
"def get_page_source(url):\n browser = webdriver.Chrome()\n browser.get(url)\n time.sleep(10)\n html_source = browser.page_source\n browser.quit()\n return html_source",
"def load_page(self, url: str):\n self.__driver.get(url)\n sleep(SLEEP_LONG_TIME)",
"def wait_for_load(driver)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes city,country name and inserts into AirBnB search query url | def get_city_url(self, city: str, country:str) -> str:
url = f"https://www.airbnb.com/s/{city}--{country}/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_dates%5B%5D=july&flexible_trip_dates%5B%5D=june&flexible_trip_dates%5B%5D=august&date_picker_type=flexible_dates&flexible_trip_lengths%5B%... | [
"def url_construction(company):\n postcode = company[\"registered_address\"].strip()\n postcode = postcode.split(\" \")\n for i in range(len(postcode) - 1, 0, -1): # loop backwards in the obtained string\n if postcode[i].strip().isdigit(): # if the obtained string is fully a number\n po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes BeautifulSoup object and tries to find next page in AirBnB search query. | def find_next_page(self, soup: BeautifulSoup) -> Optional[str]:
try:
next_page = (
f"https://www.airbnb.com{soup.find('a', class_='_za9j7e')['href']}"
)
except (TypeError, KeyError):
next_page = None
return next_page | [
"def next_results_page(driver, delay):\n try:\n # wait for the next page button to load\n print(\" Moving to the next page of search results... \\n\" \\\n \" If search results are exhausted, will wait {} seconds \" \\\n \"then either execute new search or quit\".form... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes city,country name and number of samples that needs to be scraped, then tries to find needed data and adds it into collected_dic dictionary. | def collect_city_items(self, samples: int, city: str, country:str) -> None:
time_start = time.time()
url = self.get_city_url(city,country)
samples_taken = 0
while url != None:
page_source = self.get_page_source(url, "_1g5ss3l")
soup = BeautifulSoup(page_source, "... | [
"def collect_all(self, samples: int, cities: list, country:str) -> None:\n\n time_start = time.time()\n for city in cities:\n self.collect_city_items(samples,city,country)\n print(f\"All scraping is done! Time elapsed: {time.time()-time_start} seconds.\")",
"def get_crime_info():\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes airbnb apartment url, gets html page source then from it collects longitude and latitude coordinates and amenities data which appends to collected_dic dictionary. | def collect_amenities(self, url: str) -> None:
page_source = self.get_page_source(url, "gmnoprint")
soup = BeautifulSoup(page_source, "html.parser")
# Get latitude and longitude data
self.get_coordinates(soup)
# Open amenities url and collect additional data
try:
... | [
"def scrape_detail_page(base_features):\r\n \r\n detailed_url = 'https://www.airbnb.com' + base_features['url']\r\n soup_detail = extract_soup_js(detailed_url)\r\n\r\n features_detailed = extract_listing_features(soup_detail, RULES_DETAIL_PAGE)\r\n features_amenities = extract_amenities(soup_detail)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes cities list,country name and number of samples that needs to be scraped, loops through every city, scrapes data and appends to collected_dic dictionary. | def collect_all(self, samples: int, cities: list, country:str) -> None:
time_start = time.time()
for city in cities:
self.collect_city_items(samples,city,country)
print(f"All scraping is done! Time elapsed: {time.time()-time_start} seconds.") | [
"def collect_city_items(self, samples: int, city: str, country:str) -> None:\n time_start = time.time()\n url = self.get_city_url(city,country)\n samples_taken = 0\n while url != None:\n\n page_source = self.get_page_source(url, \"_1g5ss3l\")\n soup = BeautifulSoup(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes beautiful soup object, returns and appends found url to collected_dic dictionary. If it doesn't exist returns and appends None value. | def get_item_url(self, soup: BeautifulSoup) -> Optional[str]:
try:
url = f"https://www.airbnb.com{soup.find('a').get('href')}"
except AttributeError:
url = None
self.__collected_dic["url"].append(url)
return url | [
"def collect_links(url_jahia, url_wp, soup_jahia, soup_wp):\n links_jahia = {}\n links_wp = {}\n\n menu_jahia = soup_jahia.find('ul', {'id' : 'jquery_tree'})\n menu_wp = soup_wp.find('ul', {'class' : 'simple-sitemap-page'})\n\n host_jahia = get_host(url_jahia)\n host_wp = get_host(url_wp)\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes beautiful soup object, tries to find and append item property type to collected_dic dictionary. If it doesn't exist appends None value. | def get_item_property_type(self, soup: BeautifulSoup) -> None:
try:
property_type = soup.find("div", class_="_b14dlit").get_text()
property_type = property_type.split(" ")
index = property_type.index("in")
property_type = " ".join(property_type[:index])
ex... | [
"def get_property_type(Beautiful_Soup_object):\n try:\n property_type_html = Beautiful_Soup_object.findChild(\"ul\", {\"class\":\"info\"})\n property_type = property_type_html.li.text.strip()[:-1]\n return property_type\n except:\n pass",
"def soup2dict(soup, dictionary, url=\"\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes beautiful soup object, tries to find and append item location to collected_dic dictionary. If it doesn't exist appends None value. | def get_item_location(self, soup: BeautifulSoup) -> None:
try:
location = soup.find("div", class_="_b14dlit").get_text()
location = location.split(" ")
index = location.index("in")
location = " ".join(location[index + 1 :])
except (AttributeError, IndexErr... | [
"def extract_listing_location_from_result(soup, location):\r\n for div in soup.find_all(name='div', class_='pdate'):\r\n for city in div.find(name='span'):\r\n location.append(city)\r\n # print(locations)\r\n return location",
"def add_location(listing, search):\n if listing['pid'] i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes beautiful soup object, tries to find and append item title to collected_dic dictionary. If it doesn't exist appends None value. | def get_item_title(self, soup: BeautifulSoup) -> None:
try:
title = soup.find("span", class_="_bzh5lkq").get_text()
except AttributeError:
title = None
self.__collected_dic["title"].append(title) | [
"def soup2dict(soup, dictionary, url=\"\"):\n domain = get_tld(url)\n meta = soup.find_all(\"meta\")\n for tag in meta:\n if tag.get(\"property\") == \"og:title\" and tag.get(\"content\"):\n dictionary[\"title\"] = tag.get(\"content\")\n elif tag.get(\"name\") == \"title\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes beautiful soup object, tries to find and append item rating to collected_dic dictionary. If it doesn't exist appends None value. | def get_item_rating(self, soup: BeautifulSoup) -> None:
try:
rating = soup.find("span", class_="_10fy1f8").get_text()
except AttributeError:
rating = None
self.__collected_dic["rating"].append(rating) | [
"def get_item_reviews(self, soup: BeautifulSoup) -> None:\n try:\n reviews = soup.find(\"span\", class_=\"_a7a5sx\").get_text()\n reviews = re.findall(\"[0-9]+\", reviews)[0]\n except AttributeError:\n reviews = None\n self.__collected_dic[\"reviews\"].append(re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes beautiful soup object, tries to find and append item reviews count to collected_dic dictionary. If it doesn't exist appends None value. | def get_item_reviews(self, soup: BeautifulSoup) -> None:
try:
reviews = soup.find("span", class_="_a7a5sx").get_text()
reviews = re.findall("[0-9]+", reviews)[0]
except AttributeError:
reviews = None
self.__collected_dic["reviews"].append(reviews) | [
"def get_item_rating(self, soup: BeautifulSoup) -> None:\n try:\n rating = soup.find(\"span\", class_=\"_10fy1f8\").get_text()\n except AttributeError:\n rating = None\n self.__collected_dic[\"rating\"].append(rating)",
"def __extract_ratings(self, soup):\n try:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes beautiful soup object, tries to find and append item price to collected_dic dictionary. If it doesn't exist appends None value. | def get_item_price(self, soup: BeautifulSoup) -> None:
try:
price = soup.find("span", class_="_olc9rf0").get_text()
price = re.findall("\d+(?:\.\d+)?", price)[0]
except (AttributeError, IndexError):
price = None
self.__collected_dic["price"].append(price) | [
"def get_house_price(Beautiful_Soup_object):\n try:\n price_html = Beautiful_Soup_object.find(\"strong\", {\"class\":\"price\"}) # selects the strong tag\n price = price_html.text.replace(\",\", \"\") # select the actual price as a string\n return price\n except:\n pass",
"def ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |