query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Sets the list of outputs Needs to be saved for later since they cannot be set until the solver is created after a connect.
def SetOutputs(self, outputs): self.outputs = outputs
[ "def add_output_list_opt(self, opt, outputs):\n self.add_opt(opt)\n for out in outputs:\n self.add_opt(out)\n self._add_output(out)", "def _do_outputs(self):\n for action in self._actions.get_actions(OutputAction):\n action.execute(self._actors, self._actions,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
! Parses the set outputs from the schedule configuration. Outputs can also be set via a yaml string fed to the parse method.
def _ParseOutputs(self): if not self.outputs is None and not self.outputs_parsed: # # Could be possible to move this loop to it's own method # for loading outputs. # component_name = "" field = "" for i, o in enumerate(self.o...
[ "def _parse_output(self):\n\n logging.info(u\"Parsing specification file: output ...\")\n\n idx = self._get_type_index(u\"output\")\n if idx is None:\n raise PresentationError(u\"No output defined.\")\n\n try:\n self._specification[u\"output\"] = self._cfg_yaml[idx]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test Handle features reply.
def test_handle_features_reply(self): mock_event = MagicMock() mock_features = MagicMock() mock_controller = MagicMock() self.mock_switch.get_interface_by_port_no.side_effect = [MagicMock(), False] type(mock_feature...
[ "def test_get_feature_flag(self):\n pass", "def test_process_feature_action_runs(self):\n # Get all the actions that the game should recognize.\n data_dir = os.path.abspath('data')\n verbs_full_path = os.path.join(data_dir, VERBS_FILENAME)\n with open(verbs_full_path, \"r\") as...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Up round a decimal number to next, 0.5 multiple
def round5(n): res = n % 0.5 plus = 0.5 - res if n < 0: rounded = n - res elif n > 0: rounded = n + plus else: rounded = n return rounded
[ "def _round_up(value, n):\n return n * ((value + (n - 1)) // n)", "def round_up(number, sig_fig=3):\n return float(('%.'+('%i' % sig_fig)+'g') % number)", "def _round_to_multiple_of(val: float, divisor: int, round_up_bias: float=0.9\n ) ->int:\n assert 0.0 < round_up_bias < 1.0\n new_val = max(divi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update cloudsql_instance when the identifier is generated.
def generate_cloudsql_instance(self): self.cloudsql_instance = '{}-{}-db-{}'.format('forseti', self.installation_type, self.identifier)
[ "def save_instance(self, instance):\n dictionary = instance.to_dict()\n instance_id = instance.get_id()\n collection = instance.get_collection()\n instance.use_connector(self)\n self.database[collection].update({'_id': instance_id}, {\"$set\": dictionary}, upsert=True)", "def update(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preload required by some MNE functions.
def preload(self): return True
[ "def preload():\n if not path.exists(BIRB_MODEL):\n makedirs(BIRB_MODEL)\n if not path.exists(TEMP):\n makedirs(TEMP)\n \n #cut to pre-load single model for now...\n prepareYolo(BIRB_MODEL+'bird_first_gather.pt',confidence=CONF)", "def preload(self):\n\n self.get_mtime()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if the value change needs to be traced or not.
def _needs_to_track_change(self, instance, value) -> bool: try: current_value = instance.__dict__[self._name] except KeyError: return True return value != current_value
[ "def has_changed(self):\n new_value = self.port.value\n return new_value != self.last_read_value", "def isDoingBatchChanges(self):\r\n return self._batchChangeDepth > 0", "def has_changes(self):\n return self.dynamic_changes != {}", "def _can_be_changed(self, graph):\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method pulls all public leagues currently available in Path of Exile
def get_active_leagues(): response = requests.get(url="https://www.pathofexile.com/api/trade/data/leagues") response_data = response.json() for item in response.headers.items(): print(item) return [League(league_data['id'], league_data['text']) for league_data in response_data['result']]
[ "def get_available_leagues():\n request_url = f'https://apiv2.apifootball.com/?action=get_leagues&APIkey={Requests.APIkey}'\n response = requests.get(request_url)\n\n return response.json()", "def get_leagues():\n return get_week_leagues()", "def get(self):\n leagues = LeagueModel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test response data is compressed correctly
def test_response_data(self): tester = app.test_client(self) response = tester.get(DUMMY_ROUTE) self.assertEqual(response.content_encoding,"gzip")
[ "def test_prepare_output_data_effective_compression(self):\n # Use dictionary to share data between threads\n thread_dict = {}\n original_compress = zlib.compress\n\n def my_compress(data):\n thread_dict['compress'] = threading.current_thread()\n return original_com...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test incorrect query params returns error and error message
def test_incorrect_query_params(self): tester = app.test_client(self) response = tester.get(DUMMY_ROUTE_INCORRECT) self.assertEqual(response.status_code, 400) self.assertTrue(b'error' in response.data)
[ "def test_missing_query_params(self):\n tester = app.test_client(self)\n response = tester.get(DUMMY_ROUTE_MISSING)\n self.assertEqual(response.status_code, 400)\n self.assertTrue(b'error' in response.data)", "def test_invalid_query_params(self):\n for param in ((\"\", \"\"), (\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test missing query params returns error and error message
def test_missing_query_params(self): tester = app.test_client(self) response = tester.get(DUMMY_ROUTE_MISSING) self.assertEqual(response.status_code, 400) self.assertTrue(b'error' in response.data)
[ "def test_incorrect_query_params(self):\n tester = app.test_client(self)\n response = tester.get(DUMMY_ROUTE_INCORRECT)\n self.assertEqual(response.status_code, 400)\n self.assertTrue(b'error' in response.data)", "def test_invalid_query_params(self):\n for param in ((\"\", \"\")...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that mandelbrot_generate.py loads mandelbrot set correctly
def test_generate_mandelbrot_data(self): compare_data = generate() self.assertIsNone(npt.assert_almost_equal(compare_data,EXAMPLE_DATA))
[ "def main(pixels):\n print(f\"Generating Mandelbrot Set with {pixels} pixels...\")\n\n img = mandelbrot(int(pixels), max_steps=100)\n plt.imshow(img, cmap=\"plasma\")\n plt.axis(\"off\")\n plt.savefig(\"mandelbrot.png\")\n plt.show()\n\n print(\"Mandelbrot set successfully generated!\")", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dryrun aware wrapper around statusdb save
def _save(self, con, obj): def runpipe(): con.save(obj) return self.app.cmd.dry("storing object {} in {}".format(obj.get('_id'),con.db), runpipe)
[ "def save_run(self, run_result: RunResult) -> None:", "def dbGenerateSaveQuery(self, env):", "def _write_status(self):\n\n # write active flag to the db and reset the status da\n if self._db_client.write_points(self._status_data):\n self._status_data = list()", "def dbSave(self, env):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds samples with uncompressed fastq files in project/fc_id/sample_id directories Returns a list of sample names
def _find_uncompressed_fastq_files(self, proj_base_dir, samples): uncompressed = [] for sample in samples: date = sample.get("date",False) fcid = sample.get("flowcell",False) dname = sample.get("barcode_name","") runname = "{}_{}".format(date,fcid) ...
[ "def getFastqFiles(folder):\n all_files = os.listdir(folder)\n\n fastq_files = []\n for filename in all_files:\n if '.fastq' in filename.lower():\n fastq_files.append(os.path.join(folder, filename))\n\n return fastq_files", "def get_all_fastq_files(data_dir):\r\n\r\n pattern = fn_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns json data of all events
def get_all_events(request): events = Event.objects.all() data = serializers.serialize("json", events) return HttpResponse(data, content_type="application/json")
[ "def get_events():\n\n #immplementation\n\n return json.dumps(events)", "def events(self):\n r = requests.get(self.uri+'events')\n r.raise_for_status()\n return r.json()", "def get_all_events():\n\n events = Event.query.all() # list of objs\n\n events_list = []\n\n for event...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new event based on form input from partials/create_event.html UNTESTED Args request object
def create_event(request): # info from create_event.html form; comes in on response object argument data = request.body.decode("utf-8") data2 = json.loads(data) eventName = data2["eventName"] description = data2["description"] city = data2["city"] beginTime = data2["beginTime"] endTime...
[ "def post(self, request):\n context = {}\n form = EventForm(request.POST or None)\n if form.is_valid():\n _update_form_in_model(request, form, set_creator=True)\n return redirect('home')\n context['form'] = form\n return render(request, 'event/create_event.ht...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws this object (Candy) on the given coordinate.\n
def draw(self, coordinate): (xPixels, yPixels) = (coordinate.get_pixel_tuple()) self._game_Display.blit(self._image, (xPixels, yPixels))
[ "def draw(self, screen):\n screen.draw_asteroid(self, self.__x, self.__y)", "def point(x: float, y: float) -> None:\n __canvas.drawPath(skia.Path().moveTo(x, y).close(), __stroke_paint())", "def draw(self, window):\n # usar sprite para desenhar drone\n pygame.draw.circle(window, BLUE, RA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It returns the coordinate of this candyobject.\n
def get_coord(self): return self._coord
[ "def coord(self):\n return self._coord", "def coordinate(self):\n return Coordinate.load(self.position)", "def get_coord(self):\n return self.board_coordinate", "def get_coords(self):\n\t\treturn self.x, self.y, self.z", "def getCoords(self): # real signature unknown; restored from __do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Esta funcao testa se um jogador especifico vence.
def vitoria(estado, jogador): global tam_tabuleiro win_estado = possiveis_estados_vitoria(estado) # Se um, dentre todos os alinhamentos pertence um mesmo jogador, # então o jogador vence! if [jogador for z in range(N)] in win_estado: return True else: return False
[ "def test_g_et_cob(self):\n pass", "def boas_vindas():\r\n print 'Bem-vindo ao jogo!'", "def test_vicars_get(self):\n pass", "def juiz(jogador1, jogador2):\r\n\treturn 'Casa'", "def test_get_new_voter(self):\n voter = self.data_import._get_voter_object('Test Voter 2')\n self.assertEqu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Limpa o console para SO Windows
def limpa_console(): os_name = platform.system().lower() if 'windows' in os_name: system('cls') else: system('clear')
[ "def console(self):\n mwrank_console()", "def cli_target(self):\r\n if os.name == 'nt':\r\n cmd=['start','python',os.path.join(self._path,'cli_target.py')]\r\n self._execute(cmd)\r\n else:\r\n cmd=['xterm','-e','python '+os.path.join(self._path,'cli_target.py'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get chart area info. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response.
def cells_chart_area_get_chart_area(self, name, sheet_name, chart_index, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cells_chart_area_get_chart_area_with_http_info(name, sheet_name, chart_index, **kwargs) else: (data) = self.c...
[ "def cells_chart_area_get_chart_area_with_http_info(self, name, sheet_name, chart_index, **kwargs):\n\n all_params = ['name', 'sheet_name', 'chart_index', 'folder', 'storage']\n all_params.append('callback')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_cont...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get chart area info. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response.
def cells_chart_area_get_chart_area_with_http_info(self, name, sheet_name, chart_index, **kwargs): all_params = ['name', 'sheet_name', 'chart_index', 'folder', 'storage'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') ...
[ "def cells_chart_area_get_chart_area(self, name, sheet_name, chart_index, **kwargs):\n kwargs['_return_http_data_only'] = True\n if kwargs.get('callback'):\n return self.cells_chart_area_get_chart_area_with_http_info(name, sheet_name, chart_index, **kwargs)\n else:\n (data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get chart area border info. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response.
def cells_chart_area_get_chart_area_border(self, name, sheet_name, chart_index, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cells_chart_area_get_chart_area_border_with_http_info(name, sheet_name, chart_index, **kwargs) else: (...
[ "def cells_chart_area_get_chart_area_border_with_http_info(self, name, sheet_name, chart_index, **kwargs):\n\n all_params = ['name', 'sheet_name', 'chart_index', 'folder', 'storage']\n all_params.append('callback')\n all_params.append('_return_http_data_only')\n all_params.append('_prelo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get chart area border info. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response.
def cells_chart_area_get_chart_area_border_with_http_info(self, name, sheet_name, chart_index, **kwargs): all_params = ['name', 'sheet_name', 'chart_index', 'folder', 'storage'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content...
[ "def cells_chart_area_get_chart_area_border(self, name, sheet_name, chart_index, **kwargs):\n kwargs['_return_http_data_only'] = True\n if kwargs.get('callback'):\n return self.cells_chart_area_get_chart_area_border_with_http_info(name, sheet_name, chart_index, **kwargs)\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get chart area fill format info. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response.
def cells_chart_area_get_chart_area_fill_format(self, name, sheet_name, chart_index, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cells_chart_area_get_chart_area_fill_format_with_http_info(name, sheet_name, chart_index, **kwargs) else: ...
[ "def cells_chart_area_get_chart_area_fill_format_with_http_info(self, name, sheet_name, chart_index, **kwargs):\n\n all_params = ['name', 'sheet_name', 'chart_index', 'folder', 'storage']\n all_params.append('callback')\n all_params.append('_return_http_data_only')\n all_params.append('_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get chart area fill format info. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response.
def cells_chart_area_get_chart_area_fill_format_with_http_info(self, name, sheet_name, chart_index, **kwargs): all_params = ['name', 'sheet_name', 'chart_index', 'folder', 'storage'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_co...
[ "def cells_chart_area_get_chart_area_fill_format(self, name, sheet_name, chart_index, **kwargs):\n kwargs['_return_http_data_only'] = True\n if kwargs.get('callback'):\n return self.cells_chart_area_get_chart_area_fill_format_with_http_info(name, sheet_name, chart_index, **kwargs)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiates the ``Paginator`` and allows for some configuration. The ``request_data`` argument ought to be a dictionarylike object. May provide ``limit`` and/or ``offset`` to override the defaults. Commonly provided ``request.GET``. Required. The ``objects`` should be a listlike object of ``Resources``. This is typica...
def __init__(self, request_data, objects, resource_uri=None, limit=None, offset=0, max_limit=1000, collection_name='objects', format=None, params=None, method=None): self.request_data = request_data self.objects = objects self.limit = limit self.max_limit = max_limit ...
[ "def do_pagination(self, request, queryset):\n limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)\n\n try:\n offset = int(request.GET.get('offset', 0))\n assert offset >= 0\n except (ValueError, AssertionError):\n raise BadRequestError(\"offset must be a ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates all pertinent data about the requested page. Handles getting the correct ``limit`` & ``offset``, then slices off the correct set of results and returns all pertinent metadata.
def page(self): limit = self.get_limit() offset = self.get_offset() count = self.get_count() objects = self.get_slice(limit, offset) meta = { 'offset': offset, 'limit': limit, 'total_count': count, } if limit and self.method.up...
[ "def __handle_requests(per_page, meta_dict, output_file):\n\n # iterate through dictionary. we are assuming that the\n # number of regions is 0-9 based on the documentation.\n for region in range(10):\n\n # get the record count from the dict.\n total_region = meta_dict[region]\n\n # ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test link link_href and link_set methods.
def test15_link(self): r = Resource(uri='ln1') self.assertEqual(r.link('up'), None) self.assertEqual(r.link_href('up'), None) r.link_set('up', 'uri:up') self.assertEqual(r.link('up'), {'rel': 'up', 'href': 'uri:up'}) self.assertEqual(r.link_href('up'), 'uri:up') r...
[ "def test_created_link(self):\n link = create_tiny_link(\"https://google.com/\")\n url = reverse('links:index')\n response = self.client.get(url)\n self.assertContains(response, link.tiny_link)", "def test_link(self):\n response = self.node.query(type=LINK)\n path = self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test setters/getters for specific link types.
def test16_specific_links(self): r = Resource(uri='laughing') r.describedby = 'uri:db' self.assertEqual(r.describedby, 'uri:db') r.up = 'uri:up' self.assertEqual(r.up, 'uri:up') r.index = 'uri:index' self.assertEqual(r.index, 'uri:index') r.contents = 'uri...
[ "def test15_link(self):\n r = Resource(uri='ln1')\n self.assertEqual(r.link('up'), None)\n self.assertEqual(r.link_href('up'), None)\n r.link_set('up', 'uri:up')\n self.assertEqual(r.link('up'), {'rel': 'up', 'href': 'uri:up'})\n self.assertEqual(r.link_href('up'), 'uri:up'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test basename property derived from uri.
def test17_basename(self): r = Resource(uri='http://example.org/any/complex/path/file') self.assertEqual(r.basename, 'file') r.uri = 'http://example.org/any/complex/path/' self.assertEqual(r.basename, '') r.uri = 'http://example.org' self.assertEqual(r.basename, '')
[ "def test_get_basename(self):\n self.assertEquals(util.fileops.get_basename('/home/brandon/test/test.py'),\n 'test.py')\n self.assertEquals(util.fileops.get_basename('poopies.html'),\n 'poopies.html')\n self.assertEquals(util.fileops.get_basename('raw'), 'raw')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test error from bad change type.
def test19_change_type_error(self): cte = ChangeTypeError('unk') self.assertIn('ChangeTypeError: got unk, expected one of ', str(cte))
[ "def test_invalid_change_changetype():\n statement = copy.deepcopy(CHANGE_STATEMENT)\n del statement['baseDebtor']\n statement['changeType'] = 'XX'\n\n is_valid, errors = validate(statement, 'changeStatement', 'ppr')\n\n if errors:\n for err in errors:\n print(err.message)\n prin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
figure out who is leaving and store it figure out who is joining and store it for each leaving node, remove it collect tasks reassign tasks for each joining add new node reassign tasks from affected nodes generate new ids and add them to pool
def churnNetwork(self): leaving = [] joining = [] for nodeID in self.superNodes: if random.random() < self.churnRate: leaving.append(nodeID) for j in self.pool: if random.random() < self.churnRate: joining.append(j) ...
[ "def remove(self, task_id, node_id=None):", "def all_to_all_check_time_out(self): \n mutex.acquire()\n all_ip = list(self.membership_dict.keys())\n for checking_ip_address in all_ip:\n if (checking_ip_address == self.IP_ADDRESS):\n continue\n local_time = dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the missing seat in the middle of the number sequence
def find_missing_seat(seat_ids: typing.List[int]) -> int: seat_ids = set(seat_ids) for i in range(min(seat_ids), max(seat_ids)): if i not in seat_ids: return i raise ValueError()
[ "def find_seat():\n dat = data_parser()\n seat_set = set()\n for bp in dat:\n seat_set.add(get_seat(bp))\n missing_seats = set(range(128 * 8 - 1)) - seat_set\n for seat in missing_seats:\n if 0 < seat < 128 * 8 - 1 and seat - 1 in seat_set and seat + 1 in seat_set:\n print(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns detname like XcsEndstation0Epix100a1
def detector_name(det): return gu.string_from_source(det.pyda.source).replace(':','-').replace('.','-')
[ "def get_station_name(self):\n pass", "def get_det_name(self, det):\n if isinstance(det, tuple):\n # The \"detector\" is a mosaic.\n if det not in self.allowed_mosaics:\n msgs.error(f'{det} is not an allowed mosaic for {self.name}.')\n return Mosaic.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
merge constants of all status_ ctypes saved in ctype status_merged
def merge_status_extra(detid, fname_prefix, pattern, _tstamp, **kwa): import numpy as np repoman = kwa.get('repoman', None) ctype = kwa.get('ctype', 'status_extra') # None fmt_status = kwa.get('fmt_status', '%d') filemode = kwa.get('filemode', 0o664) group = kwa.get('group', '...
[ "def _format_statuses(type_, statuses):\n formatted_statuses = type_.upper() + \"\\n\"\n for stat_name, stat_value in statuses.items():\n formatted_statuses += f\"{stat_name}: {stat_value}\\n\"\n\n return formatted_statuses", "def _GetIssueStatusesNeedingUpdating():\n statuses = [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots the data, baseline, and thresholds of the debug group in the event_database, if they exist, in the main plot.
def plot_debug(self, event_database): if not event_database.is_debug(): return self.eventview_plotwid.clear() sample_rate = event_database.get_sample_rate() # TODO remove the step_size. step_size = 1000 data = event_database.root.debug.data[0][::step_size]...
[ "def plot_bgd(e, edir):\n slots = [int(s) for s in e['slots_for_sum'].split(',')]\n plt.figure(figsize=(4, 4.5))\n max_bgd = 0\n for slot in slots:\n l0_telem = aca_l0.get_slot_data(e['cross_time'] - 100,\n e['cross_time'] + 300,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes the event displayed on the event display plot to current value + count
def move_event_display_by(self, count): h5_event_count = 0 try: h5file = eD.open_file(self.event_view_item.get_file_name()) h5_event_count = h5file.get_event_count() h5file.close() except: return try: event_count = int(self.even...
[ "def on_range_update(event):\n label = event.currentTarget.nextElementSibling\n label.innerText = event.currentTarget.value\n plot_waveform()", "def count(self, event='Visit'):\r\n self.Counts[event] += 1", "def _updateValue(self,event):\n self.gain.set(self.slider.get())\n self.va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert Task object to JSON encoded string. The build interface needs to pass Task data on the command line, because each compute node needs to understand the Task description. JSON format is a convenient way to describe the Task object at the command line.
def task2arg(task): return jsonpickle.encode(task)
[ "def serialize(self, task):", "def task_result_to_json(result: dict) -> str:\n try:\n if type(result) != dict:\n error = \"The task '{}' returned an object with type '{}', \" \\\n \"instead of expected type 'dict'.\"\n logger.error(error)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get and process the CWL compliant dockerPull dockerRequirement.
def process_docker_pull(self, addr, force):
[ "def cli(ctx, image, tag):\n\n # Setup subprocesses for all of our tools\n docker = Command(\"docker\")\n\n # Format Docker pull command with image and tag if provided\n if image and tag:\n image_name = \"{}:{}\".format(image, tag)\n else:\n image_name = \"{}:latest\".format(image)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get and process the CWL compliant dockerLoad dockerRequirement.
def process_docker_load(self):
[ "def process_docker_import(self, param_import):", "def check_docker_installation() -> Optional[dict]:\n try:\n return docker.from_env().version()\n except requests.exceptions.ConnectionError:\n return None", "def load_requirements(cfg):\n reqs = parse_req(cfg['setup_requirements'])\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get and process the CWL compliant dockerFile dockerRequirement.
def process_docker_file(self, task_dockerfile, force):
[ "def check_dockerfile(self):\n\n with open(self.pf('Dockerfile')) as d_file:\n content = d_file.readlines()\n\n if not content:\n self.failed.append((2, 'Dockerfile seems to be empty.'))\n return\n\n labels = {}\n base_img = []\n environment_def = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get and process the CWL compliant dockerImport dockerRequirement.
def process_docker_import(self, param_import):
[ "def process_docker_file(self, task_dockerfile, force):", "def check_docker_installation() -> Optional[dict]:\n try:\n return docker.from_env().version()\n except requests.exceptions.ConnectionError:\n return None", "def check_dockerfile(self):\n\n with open(self.pf('Dockerfile')) as ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get and process the CWL compliant dockerImageId dockerRequirement.
def process_docker_image_id(self, param_imageid):
[ "def task_docker_image(conf):\n # type: (dict) -> str\n return (\n _kv_read_checked(conf, 'docker_image') or\n _kv_read_checked(conf, 'image')\n )", "def docker_id(self):\n return self._docker_id", "def get_image_name(target, command):\n try:\n output = subprocess.Popen([...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get and process the CWL compliant dockerOutputDirectory dockerRequirement.
def process_docker_output_directory(self, param_output_directory):
[ "def getDockerfilePath(programSrcDir):\r\n return os.path.join(programSrcDir,\"docker-image\",\"Dockerfile\")", "def get_output_directories(self):\r\n pass", "def __build_dockerfile(self, script_file, requirements_file, port):\n\n # try to write Dockerfile\n try:\n\n # Dockerfil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given multiple DockerRequirements, set order of execution. The CWL spec as of 04152021 does not specify order of execution, but the cwltool gives some guidance by example. We mimic cwltool in how we resolve priority, favoring fast, cached container specs over slower specs. For example, if both a docker pull and a docke...
def resolve_priority(self): # cwl spec priority list consists of: # (bound method, method name, priority, terminal case bool) cwl_spec = [(self.process_docker_pull, 'dockerPull', 5, True), (self.process_docker_load, 'dockerLoad', 6, True), (self.process_do...
[ "def multi_build(request, recipes_fixture, config_fixture):\n if request.param:\n docker_builder = docker_utils.RecipeBuilder(\n use_host_conda_bld=True,\n docker_base_image=DOCKER_BASE_IMAGE)\n mulled_test = True\n else:\n docker_builder = None\n mulled_test ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The forest 'grows' for a set amount of iterations given in years .
def grow(self, rate=1, years=1): for y in range(1, years+1): r = rate # all trees age one year self.age() # aging means root growth, check for new connections for t in self.trees: t.getnewneighbors() # birthing process u...
[ "def evolve(self, years):\n world_file = fldr + os.sep + self.name + '.txt'\n self.build_base()\n self.world.add_mountains()\n self.add_life()\n self.world.grd.save(world_file)\n \n print('TODO - run ' + str(years) + ' years')\n # time.sleep(3)\n # gui....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Age every tree in the forest by one year.
def age(self): for t in self.trees: t.age += 1
[ "def grow(self, rate=1, years=1):\n\n for y in range(1, years+1):\n r = rate\n\n # all trees age one year\n self.age()\n\n # aging means root growth, check for new connections\n for t in self.trees:\n t.getnewneighbors()\n\n # b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds the critic models.
def _build_critic(self,): critic_settings = { 'input_size': self.state_dim, 'output_size': self.action_dim, 'output_activation': 'linear', } self.critic = models.build_dnn_models(**critic_settings) self.critic_target = models.build_dnn_models(**...
[ "def define_critic(self):\n # done once for every joint\n self.picked_actions = {}\n self.critic_values = {}\n self.returns = {}\n self.critic_loss = {}\n self.greedy_actions_indices = {}\n self.sampled_actions_indices = {}\n self.joint_summary = {}\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute for binary variable (y_true_, y_pred) roc auc, accuracy, recall, precision and f1
def calcul_metric_binary(y_true_, y_pred, thr_1=0.5, print_score=True): if isinstance(y_true_, pd.DataFrame): # pass y_true_ to array type y_true = y_true_.values.copy() else: y_true = y_true_.copy() report = classification_report(y_true.reshape(-1), np.where(y_pred > thr_1, 1, 0).reshape(...
[ "def calculate_AUROC(y_true, y_pred):\n return roc_auc_score(y_true, y_pred)", "def evaluate_model(y_true, y_pred):\n prec= precision_score(y_true, y_pred, average = 'weighted')\n rec = recall_score(y_true, y_pred, average = 'weighted')\n f1_s = f1_score(y_true, y_pred, average = 'weighted')\n acc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translates openAI spaces into YARL Space classes.
def translate_space(space): if isinstance(space, gym.spaces.Discrete): return IntBox(space.n) elif isinstance(space, gym.spaces.MultiBinary): return BoolBox(shape=(space.n,)) elif isinstance(space, gym.spaces.MultiDiscrete): return IntBox(low=np.zeros((space.n...
[ "def convert_yara_rules_to_yara_model(\n yara_rules_str: str, imports_at_top: bool = False\n) -> Yara:\n yara_data = convert_yara_rules_to_map(yara_rules_str, imports_at_top=imports_at_top)\n return Yara.parse_obj(yara_data)", "def space():\n space = Space()\n categories = {'asdfa': 0.1, 2: 0.2, 3:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a argparse parser for the command.
def build_parser(self, parser: ArgumentParser) -> None:
[ "def build_parser(self, parser: ArgumentParser):", "def create_parser(self, prog_name, subcommand):\n parser = CommandParser(\n self, prog=f'{os.path.basename(prog_name)} {subcommand}',\n description=self.help or None)\n\n # Add any arguments that all commands should accept her...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should the command appear in the global help info or not.
def should_appear_in_global_help(self) -> bool: return True
[ "def should_appear_in_global_help(self) -> bool:\n return False", "def showhelp():\n\tusage()", "def check_help(data):\n args = get_args(data)\n if len(args) == 0:\n return True\n if args[0] == \"help\":\n return True\n return False", "def help_help(self):\n return self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is this command allowed for a particular workspace.
def is_allowed_for_workspace(self, workspace: Workspace) -> bool: return True
[ "def is_allowed_for_workspace(self, workspace: Workspace) -> bool:\n scoped_feature = self._use_case.get_scoped_to_feature()\n if scoped_feature is None:\n return True\n if isinstance(scoped_feature, Feature):\n return workspace.is_feature_available(scoped_feature)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether the main script should have a streaming progress reporter.
def should_have_streaming_progress_report(self) -> bool: return True
[ "def is_streaming(self):\n return self.has_user_request(\"streaming\") or self.has_remote_user(\"streaming\")", "def reporting_enabled(self):\n\n return hasattr(self, 'results_gallery')", "def is_worker():\n return _IN_WORKER is True", "def check_no_progress(self):\n return self.no_pro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is this command allowed for a particular workspace.
def is_allowed_for_workspace(self, workspace: Workspace) -> bool: scoped_feature = self._use_case.get_scoped_to_feature() if scoped_feature is None: return True if isinstance(scoped_feature, Feature): return workspace.is_feature_available(scoped_feature) for featu...
[ "def is_allowed_for_workspace(self, workspace: Workspace) -> bool:\n return True", "def allowed(self):\n return command_allowed(self.name(), self.user_id())", "def can_delete_workspace(func, workspace, user):\n if user.is_superuser:\n return func(workspace, user)\n\n _check_is_owner_works...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether the main script should have a streaming progress reporter.
def should_have_streaming_progress_report(self) -> bool: return False
[ "def should_have_streaming_progress_report(self) -> bool:\n return True", "def is_streaming(self):\n return self.has_user_request(\"streaming\") or self.has_remote_user(\"streaming\")", "def reporting_enabled(self):\n\n return hasattr(self, 'results_gallery')", "def is_worker():\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should the command appear in the global help info or not.
def should_appear_in_global_help(self) -> bool: return False
[ "def should_appear_in_global_help(self) -> bool:\n return True", "def showhelp():\n\tusage()", "def check_help(data):\n args = get_args(data)\n if len(args) == 0:\n return True\n if args[0] == \"help\":\n return True\n return False", "def help_help(self):\n return self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to do some pre processing (simplification of emails). Comments throughout implementation describe what it does. Input = raw email Output = processed (simplified) email
def preProcess(email: str): # Make entire email to lower case email = email.lower() # Strip html tags (strings that look like <blah> where 'blah' does not # contain '<' or '>')... replace with a space email = re.sub('<[^<>]+>', ' ', email) # Replace any number with a string 'number' em...
[ "def process(string_in):\n email_contents = string_in.lower()\n\n email_contents = remove_header(email_contents)\n\n email_contents = strip_html(email_contents)\n\n # newline fix\n email_contents = email_contents.replace(\"=\\n\", \"\")\n\n # Http addresses corrected\n # Replace occurrence of \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to read in the supplied vocab list text file into a dictionary. I'll use this for now, but since I'm using a slightly different stemmer, I'd like to generate this list myself from some sort of data set... Dictionary key is the stemmed word, value is the index in the text file If "reverse", the keys and values ...
def getVocabDict(reversed=False): vocab_dict = {} with open(vocabDictPath, 'r') as f: for line in f: (val, key) = line.split() if not reversed: vocab_dict[key] = int(val) else: vocab_dict[int(val)] = key return vocab_dict
[ "def _read_vocab(self, filename):\n\t\twith open(filename) as lines:\n\t\t\tix_to_word = [line.strip() for line in lines]\n\t\t\tword_to_ix = {word: ix for ix, word in enumerate(ix_to_word)}\n\t\t\treturn ix_to_word, word_to_ix", "def vocab2id(file_path):\n with open(file_path, 'r') as file:\n lines = f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that takes in a raw email and returns a list of indices corresponding to the location in vocab_dict for each stemmed word in the email.
def emailToVocabIndices(email, vocab_list): tokenList = emailToTokenList(email) indexList = [vocab_list[token] for token in tokenList if token in vocab_list] return indexList
[ "def build_firstword_index(sentences):\n index = defaultdict(list)\n for i in range(len(sentences)):\n tokens = utils.tokenize(sentences[i])\n index[tokens[1]].append(i) #Excluding start tokens\n return index", "def sentence_to_indices(sentence, word_dict):\n return [word_dict.to_index(w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that takes as input a raw email, and returns a vector of shape (n,1) where n is the size of the vocab_dict. The first element in this vector is 1 if the vocab word with index == 1 is in the raw_email, 0 otherwise.
def email2FeatureVector(email: str, vocab_list: dict): n = len(vocab_list) result = np.zeros((n,1)) vocal_indices = emailToVocabIndices(email, vocab_list) for i in vocal_indices: result[i] = 1 return result
[ "def binary_feature_vector_builder(dictionary, email):\n feature_vector=[]\n email_words=email.split()\n for word in dictionary:\n if word in email_words:\n feature_vector.append(1)\n else:\n feature_vector.append(0)\n return feature_vector", "def emailToVocabIndice...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns name of the next image
def get_next_image(self): raise NotImplementedError
[ "def next_image(self):\n if self.session_folder is None:\n return None\n\n file_path = join(self.session_folder,\n 'frame_' +\n str(self.current_image).zfill(3) +\n '.jpg')\n self.current_image += 1\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns list of installed images
def get_installed_images(self): raise NotImplementedError
[ "def avail_images(call=None):\n vm_ = get_configured_provider()\n return {\"Profiles\": [profile for profile in vm_[\"profiles\"]]}", "def docker_images_list(self):\n images = Images.objects()\n if len(images) == 0:\n print(\"No images exist\")\n return\n\n for ima...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set default image to boot from
def set_default_image(self, image): raise NotImplementedError
[ "def load_default_image(self):\n self._send_to_ztv('load-default-image')", "def set_image(self):\r\n self.sc.set_image()", "def _get_default_image(self):\n with open(modules.get_module_resource('school', 'static/description', 'user.png'), 'rb') as img:\n image = base64.b64encode(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set next image to boot from
def set_next_image(self, image): raise NotImplementedError
[ "def setNext(self, img_time, img):", "def next_image(self):\n self.index = (self.index + 1) % len(self.images)\n self.show_image(self.images[self.index])", "def image_chooser(self):\n self.__image = pg.image.load(\"res/ghost/\" + Ghost.image_names[self.__id] + \"/start.png\")", "def set_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
verify that the image is of the same platform than running platform
def verify_image_platform(self, image_path): raise NotImplementedError
[ "def target_system_image_is_currently_running():\n version = get_version(1)\n if legacy == False:\n image_parts = [part for part in re.split(\"[\\.()]\", version) if part]\n image_parts.insert(0, \"nxos\")\n image_parts.append(\"bin\")\n \n is_cs = is_image_cs_or_msll()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
verify that the image is secure running image
def verify_secureboot_image(self, image_path): raise NotImplementedError
[ "def test_vmware_service_resources_image_get_private(self):\n pass", "def verify_fw_image(self, image_number):\n image_number = int(image_number, 0)\n (status, image_ok) = self.__device.check_active_image(0xFE, image_number)\n self.__device.decode_error_status(status, 'check_active_ima...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
verify the next image for reboot
def verify_next_image(self): image = self.get_next_image() image_path = self.get_image_path(image) return path.exists(image_path)
[ "def check_reboot():\n return os.path.exists(\"/run/reboot-required\")", "def verify_secureboot_image(self, image_path):\n raise NotImplementedError", "def _get_image_info(self, img_id):\n rs = None\n rc = None\n for i in range(100):\n rc, rs = self.cal.get_image(self._a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tells if the image supports package migration
def supports_package_migration(self, image): return True
[ "def _can_use_driver_migration(self, diff):\n # We can if there's no retype or there are no difference in the types\n if not diff:\n return True\n\n extra_specs = diff.get('extra_specs')\n qos = diff.get('qos_specs')\n enc = diff.get('encryption')\n\n # We cant' ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an argument to the list of received attacks counter examples (received_attacks_counter_examples)
def add_received_attacks_counter_examples(self, new_arg: Argument): self.received_attacks_counter_examples.append(new_arg)
[ "def add_example(self, example):\n self.examples.append(example)", "def addAttackInUse(self):\n params = []\n toAdd = []\n \n for key in self.vals.keys():\n if self.vals[key] is None:\n continue \n \n params += [key]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the actual entity that this placeholder refers to, if it exists; returns UNASSIGNED if the entity no longer exists. EntityDoesNotExist errors are not propagated because in some cases, such as in complex cascade delete scenarios, several related entities must be deleted in one transaction. Such a transaction appe...
def restore(self, db): if self.entity is not None and self.db_sync_count == db._sync_count: # Use the attached entity if it's there; only foolishness # would result in it being the wrong one. return self.entity extent = db.extent(self.extent_id) oid = self.oid...
[ "def remove_entity(self, x, y):\n tile = map.tiles[x][y]\n entity = tile.entity\n \n if entity is None:\n raise LogicException(\"Tried to remove entity from (%d,%d) but there was nothing there.\" % (x, y))\n\n entity.x = -1\n entity.y = -1\n entity.owner =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a pseudoprime of the form p1 p2 p3 which passes the MillerRabin primality test for the provided bases.
def generate_pseudoprime(A, min_bitsize=0): A.sort() k2 = int(next_prime(A[-1])) k3 = int(next_prime(k2)) while True: logging.info(f"Trying k2 = {k2} and k3 = {k3}...") rems = [pow(-k3, -1, k2), pow(-k2, -1, k3)] mods = [k2, k3] s = _generate_s(A, mods) z, m = _ba...
[ "def gen_prime(nbits):\n while True:\n p = random.getrandbits(nbits)\n # force p to have nbits and be odd\n p |= 2**nbits | 1\n if miller_rabin(p):\n return p\n break", "def miller_rabin(n, base=2):\n # http://en.wikipedia.org/wiki/Mi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This script will take the file, transferFile.txt, which contains a text version of the database, and input all the book metadata into the database. When you run it make sure you switch the variables in the creation of conn and the path to the file transferFile
def File_to_DB(): conn = mysql.connector.connect( user='root', password='MaximumHaze16', host='localhost', database='seniordesign' ) cur = conn.cursor() fr = open("C:\\users\\sarah\\desktop\\dbtransfer2\\transferFile.txt", 'r') count =0 for line in fr: id ...
[ "def sig_point_txt_file_into_database(self, data_file, host, database, user, password):\n if data_file.strip() != '':\n # Check if data file exists\n if os.path.isfile(data_file):\n with open(data_file, 'r', encoding='utf-8') as file:\n # Connect to dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Spam a channel with dumb things
async def spam(self, args, mobj): if not args or len(args) > 10: return await self.client.send_message(mobj.channel, "Invalid spam input") y = args * randint(5, 20) return await self.client.send_message(mobj.channel, f"{' '.join(y)}")
[ "async def spam_all_channels(ctx,*,arg):\r\n await ctx.message.delete()\r\n await ctx.send('✅ **Spamming initiated!** Type `stop` to stop.')\r\n\r\n def check_reply(m):\r\n return m.content == 'stop' and m.author == ctx.author and m.channel == ctx.channel\r\n\r\n async def spam_text():\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Both min and max are divisible, range is empty
def test_only_min_max(self): self.assertEqual(1, solution(12, 12, 12))
[ "def in_range(val, min_val, max_val):\n return min(max(val, min_val), max_val)", "def number_within_range(number, min, max):\n try:\n if min <= number <= max:\n return True\n return False\n except Exception:\n return False", "def map_range_constra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This script opens the image and when clicked on a part of the image, the coordinates of the mouse click will be printed and saved into a txt file. The input of this function must be a string describing the species and the path to the directory containing the images to be annotated
def data_annotation(image_path): #This for loop iterates over all images in the given data path and plots the individual images. #The coordinates of the landmarks are saved into a text file after clicking. for i in os.listdir(image_path): #Only continue with the the jpg files in the directory ...
[ "def cv_extract_and_annotate(image_path, annotation_path, color = (255, 255, 255),\n name = 'image', shape = (500, 500), xy = (0,0), line_width = 2):\n image = cv2.imread(image_path)\n cv_annotate(image, annotation_path, color = color, line_width = line_width)\n cv_loopshow(image, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the date of the current week's Friday.
def get_friday() -> datetime.date: today = datetime.date.today() return today + datetime.timedelta(days=4-today.weekday())
[ "def get_this_sunday(cur_date):\n cur_date = dt.strptime(cur_date, \"%Y-%m-%d\") if type(cur_date) is str else cur_date\n return cur_date - timedelta(cur_date.weekday() - 6)", "def generate_fridays():\n fridays = []\n start_date = datetime.date(2014,1,1)\n today = datetime.date.today()\n end_dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the Freitagsfoo wiki page for the given date.
def load_page_for_date(site: Site, date: datetime.date) -> Page: return site.pages["Freitagsfoo/{}".format(date)]
[ "def fetch(date, refresh=False):\n if isinstance(date, datetime.datetime):\n date = date.date()\n\n if date > datetime.date.today():\n raise ValueError(f\"{date} is in the future\")\n datestring = date.strftime(DATE_FORMAT)\n\n if not CACHE.exists():\n CACHE.mkdir()\n\n cache = C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the top section, return hosts and date as YYYYMMDD.
def parse_top_section(page: Page) -> Tuple[List[str], str]: top_section = page.text(section=0) parsed_top_section = wtp.parse(top_section) parsed_event = parsed_top_section.templates[0] hosts = list() for host in parsed_event.get_arg("Host").value.split(","): hosts.append(host.strip().lower(...
[ "def date_parser():", "def prv_header_parser(prv_file: str) -> (int, datetime, List[int], List[List[Dict]]):\n # Gets header's line\n opened_prv_file = open(prv_file, 'r')\n prv_header = opened_prv_file.readline()\n opened_prv_file.close()\n\n time = prv_header_time(prv_header)\n date = prv_head...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the given sections returning a dict. If given a render_function, use it to convert the wikitext descriptions to plain text.
def parse_page( page: Page, render_function: Callable[[str], str] = None ) -> Result: hosts, date = parse_top_section(page) sections = wtp.parse(page.text()).sections talks = parse_talks(sections, render_function) return { "hosts": hosts, "date": date, "talks": talks }
[ "def parse(context: Context, module_id: int, linker_map_path: Path, executable_sections, base_folder=True):\r\n\r\n sections = dict()\r\n lines = []\r\n\r\n # read linker map line-by-line\r\n with linker_map_path.open('r') as file:\r\n lines = file.readlines()\r\n\r\n # group linker map lines ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert wikitext to plain text by rendering it on the server.
def online_html_render_function(wikitext: str) -> str: html = site.parse(text=wikitext)["text"]["*"] soup = BeautifulSoup(html) return soup.text.strip()
[ "def RenderText(self, text, status=200):\r\n self.response.headers['Content-Type'] = 'text/plain; charset=UTF-8'\r\n self.response.headers['Content-Disposition'] = 'inline'\r\n self.response.set_status(status)\r\n self.response.write(text)", "def html2text(self, text):\n try:\n impor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Return the tensor type of ``self``.
def tensor_type(self): return self._tensor_type
[ "def type_as(self, tensor): # real signature unknown; restored from __doc__\n pass", "def type(self) -> type or TypeVar:\n return self._type", "def _type(x):\n\n if isinstance(x, PondPublicTensor):\n return PondPublicTensor\n\n if isinstance(x, PondPrivateTensor):\n return Pond...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the Db class, initialise table.
def __init__(self) -> None: self.db = Db() self.init_db()
[ "def init_from_db(self, db):\n\n with db.session.begin():\n for name, table in self.tables.items():\n table.init_from_table(getattr(db, name))", "def initialize_database(self):\n self.database = self.loader.request_library(\"common_libs\", \"database\")\n self.databa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialise the session db if it doesn't exist.
def init_db(self) -> Any: sql = """ CREATE TABLE IF NOT EXISTS session ( key TEXT UNIQUE, value TEXT, date_last_access TIMESTAMP, PRIMARY KEY (key) ) ...
[ "def initialize_sessions_table(self):\n self.execute_queries(queryutils.sql.INIT_SESSIONS[self.dbtype])", "def init_db(self):\n\n # is there a DB already?\n if os.path.exists(self.db_base_path):\n raise DatabaseExists\n \n # create the dir\n os.mkdir(self.db_ba...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all session info (i.e. drop the table).
def clear_session(self) -> None: sql = """ DROP TABLE IF EXISTS session """ self.query(sql)
[ "def delete_all(self):\n local_session = self.conn()\n count = local_session.Profiler_Sessions.query.delete()\n local_session.commit()\n local_session.remove()\n return count", "def tearDown(self):\n\n\t\tdb.session.remove()\n\t\tdb.drop_all()", "def policy_sessions_delete_all...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get status of the printer as ``Status`` object
def get_status(self) -> Status: with self.io.lock: self.io.write(b'\x1B\x69\x53') data = self.io.read(32) if not data: raise IOError("No Response from printer") if len(data) < 32: raise IOError("Invalid Response from printer") ...
[ "def _printer_status(self,printer):\n\n\t\t(stdout,stderr,status) = self._shell_command(['/usr/bin/lpstat','-p',printer],{'LANG':'C'})\n\t\tif status == 0:\n\t\t\tif ' enabled ' in stdout:\n\t\t\t\treturn 'enabled'\n\t\t\tif ' disabled ' in stdout:\n\t\t\t\treturn 'disabled'\n\t\treturn 'unknown'", "def get_statu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method extracts features of a single sentence. We have following list of features being extracted. 1. Full sentence Polarity 2. Full sentence Subjectivity 3. Half sentence Polarity (1/2 and 2/2) 4. Half sentence Subjectivity (1/2 and 2/2) 5. Difference between polarities of two halves 6. Third sentence Polarity (1...
def extract_feature_of_sentence(self, sen): # type: (object) -> object features = [] # Tokenize the sentence and then convert everything to lower case. tokens = nltk.word_tokenize(exp_replace.replace_emo(str(sen))) tokens = [(t.lower()) for t in tokens] # Extract featur...
[ "def extract_features_sent(sentence, w_size, feature_names):\n\n # We pad the sentence to extract the context window more easily\n start = \"BOS BOS BOS BOS\\n\"\n end = \"\\nEOS EOS EOS EOS\"\n start *= w_size\n end *= w_size\n sentence = start + sentence\n sentence += end\n\n # Each senten...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method joins tokes into a single text avoiding punctuations and special characters as required by the textblob api.
def join_tokens(self, t): s = "" for i in t: if i not in string.punctuation and not i.startswith("'"): s += (" " + i) return s.strip()
[ "def tokenize_join(text):\n return \" \".join(tokenize(text))", "def tokenize(self):", "def join(tokens):\n joined_tokens = ' '.join(tokens)\n return joined_tokens", "def join(self, tokens):\n return \" \".join(tokens)", "def tokenization(text):\r\n list_of_punctuations_and_more = ['(', '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set default instance of configuration. It stores default configuration, which can be returned by get_default_copy method.
def set_default(cls, default): cls._default = copy.deepcopy(default)
[ "def set_default_config(self, name):\n self.local.defaults.config = name", "def set_default(self, default=None):\r\n self.default = default", "def default_(self, default_):\n\n self._default_ = default_", "def set_defaults(self):\n self._config[\"DEFAULT\"] = Config.Default\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return new instance of configuration. This method returns newly created, based on default constructor, object of Configuration class or returns a copy of default configuration passed by the set_default method.
def get_default_copy(cls): if cls._default is not None: return copy.deepcopy(cls._default) return Configuration()
[ "def get(cls):\n if not cls.config:\n cls.config = Config()\n cls.config.load()\n\n return cls.config", "def get_config():\n return copy.deepcopy(_config)", "def get_configuration(self):\n return get_configuration_from_settings()", "def configuration(self) -> Conn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The logger file. If the logger_file is None, then add stream handler and remove file handler. Otherwise, add file handler and remove stream handler.
def logger_file(self, value): self.__logger_file = value if self.__logger_file: # If set logging file, # then add file handler and remove stream handler. self.logger_file_handler = logging.FileHandler(self.__logger_file) self.logger_file_handler.setFormatt...
[ "def logger_file_handler(self):\n return self._file_handler", "def logger_file_handler(self, fh):\n if self._file_handler is not None:\n self.log.removeHandler(self._file_handler)\n\n self._file_handler = fh\n if fh is not None:\n self.log.addHandler(fh)", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The logger format. The logger_formatter will be updated when sets logger_format.
def logger_format(self): return self.__logger_format
[ "def log_format(self) -> str:\n return self._log_format", "def get_formatter(log_format: str) -> logging.Formatter:\n return logging.Formatter(log_format)", "def __set_formatter(self, log_format=None, default=False):\n if not default:\n self.stream_handler.setFormatter(MyFormatter(lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets API key (with prefix if set).
def get_api_key_with_prefix(self, identifier): if self.refresh_api_key_hook is not None: self.refresh_api_key_hook(self) key = self.api_key.get(identifier) if key: prefix = self.api_key_prefix.get(identifier) if prefix: return "%s %s" % (prefix...
[ "def get_apikey(self):\n return self.apikeys[self.apikey_index]", "def Get_Key(apig,key_id: str,include_value=False):\n\t\t\t\treturn apig.client.get_api_key(apiKey=key_id,includeValue=include_value)", "def get_key():\n config = configparser.ConfigParser()\n config.read(\"key.ini\")\n api_key = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets HTTP basic authentication header (string).
def get_basic_auth_token(self): username = "" if self.username is not None: username = self.username password = "" if self.password is not None: password = self.password return urllib3.util.make_headers( basic_auth=username + ':' + password ...
[ "def basic_auth_header(user, password):\n return {'Authorization': BasicAuth(user, password).encode()}", "def create_auth_header(self):\n encode_password = base64.b64encode(self._module.paramgram[\"username\"] + \":\" +\n self._module.paramgram[\"password\"])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets Auth Settings dict for api client.
def auth_settings(self): auth = {} if 'X-Auth-Key' in self.api_key: auth['APIKeyHeader'] = { 'type': 'api_key', 'in': 'header', 'key': 'X-Auth-Key', 'value': self.get_api_key_with_prefix('X-Auth-Key') } if 'X...
[ "def get_auth(self):\n if not self.api_key:\n raise ConfigError('Api Key is not set')\n return (self.api_key, self.api_secret_key)", "def get_auth_options(self):\n return self._fields['auth_options']", "def ApiSettings() -> _ApiSettings:\n return _ApiSettings()", "async def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets an array of host settings
def get_host_settings(self): return [ { 'url': "https://custom-ocr.klippa.com/api/v1", 'description': "No description provided", } ]
[ "def get_host_list(self):", "def get_hostnames(self):\n hosts = set()\n for entry in self._config:\n hosts.update(entry['host'])\n return hosts", "def getHosts(self):\n req = requests.get(self.baseURL+\"host\", headers=self.header)\n return req.json()['hosts']", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets host URL based on the index and variables
def get_host_from_settings(self, index, variables=None): variables = {} if variables is None else variables servers = self.get_host_settings() try: server = servers[index] except IndexError: raise ValueError( "Invalid index {0} when selecting the ...
[ "def getHostFrom(fromHost):", "def getServerURL(environ):\n scheme = environ.get('wsgi.url_scheme')\n if scheme is None:\n scheme = 'HTTPS' in environ and 'https' or 'http'\n\n http_host = environ.get('HTTP_HOST')\n\n # if vhm specifies a virtual host base, prefer it over the http\n # host\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds an SE GP with the dataset.
def build_se_gp_with_dataset(dataset): return build_euc_gp_with_dataset(dataset, 'se')
[ "def build_matern_gp_with_dataset(dataset):\n return build_euc_gp_with_dataset(dataset, 'matern')", "def fit_se_gp_with_dataset(dataset, method='slice'):\n options = load_options(euclidean_gp_args)\n options.kernel_type = 'se'\n if method is not None:\n options.hp_tune_criterion = 'post_sampling'\n opti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
builds an se gp with the dataset.
def build_matern_gp_with_dataset(dataset): return build_euc_gp_with_dataset(dataset, 'matern')
[ "def fit_se_gp_with_dataset(dataset, method='slice'):\n options = load_options(euclidean_gp_args)\n options.kernel_type = 'se'\n if method is not None:\n options.hp_tune_criterion = 'post_sampling'\n options.post_hp_tune_method = method\n ret_fit_gp = (EuclideanGPFitter(dataset[0], dataset[1],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }