query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Test that the enrypt/decrypt cycle completes successfully for a single frame message using the aes_256_gcm_iv12_tag16_hkdf_sha256 algorithm.
def test_encryption_cycle_aes_256_gcm_iv12_tag16_hkdf_sha256_single_frame(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=10...
[ "def test_encryption_cycle_aes_192_gcm_iv12_tag16_hkdf_sha256_single_frame(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a nonframed message using the aes_256_gcm_iv12_tag16_hkdf_sha256 algorithm.
def test_encryption_cycle_aes_256_gcm_iv12_tag16_hkdf_sha256_non_framed(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=0, ...
[ "def test_encryption_cycle_aes_192_gcm_iv12_tag16_hkdf_sha256_non_framed(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n fra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a single frame message using the aes_192_gcm_iv12_tag16_hkdf_sha384_ecdsa_p384 algorithm.
def test_encryption_cycle_aes_192_gcm_iv12_tag16_hkdf_sha384_ecdsa_p384_single_frame(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], fram...
[ "def test_encryption_cycle_aes_192_gcm_iv12_tag16_hkdf_sha256_single_frame(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get key for metrics list
def get_metrics_key(self, project): return "{0}-metrics".format(project)
[ "def metrics_key(self) -> str:\n pass", "def _metric_keys(self) -> str:\n return self.metricKeys", "def get_metrics_list():\n return list(metrics_dict.keys())", "def metric_identifier(self) -> str:\n return self._metric_identifier", "def _get_metric(self, key):\n # type: (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get key for metrics filters names
def get_filters_names_key(self, project, metric_name): return u"{0}-metrics-filters:{1}".format(project, to_unicode(metric_name))
[ "def get_filter_name(self):\n pass", "def metrics_key(self) -> str:\n pass", "def filterk(self):\n return self._get_filterk()", "def _get_category_filter_key_set(category_filter_group):\n keys = {'lot'}\n\n if category_filter_group is not None and category_filter_group['filters']:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert filter value to string object
def clean_filter_value(self, filter_value): if isinstance(filter_value, bool) or isinstance(filter_value, NoneType): return str(bool) return filter_value
[ "def filter_to_string(filt):\n try:\n if hasattr(filt, \"filters\") and filt.filters:\n return expr_to_str(filt.filters[0])\n elif hasattr(filt, \"havings\") and filt.havings:\n return expr_to_str(filt.havings[0])\n elif isinstance(filt, bool):\n return str(f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a Kafka consumer and apply process_func to incoming messages.
def consume_messages(process_func: Callable[[str], None]): consumer = get_consumer() for message in consumer: log.debug(f'Received a message: {message}') try: process_func(message.value) except Exception as e: log.error(f'Failed to process a message: {message.val...
[ "def process(func, consumer, *args, **kwargs):\n while True:\n item = yield\n consumer.send(func(item, *args, **kwargs))", "def start_consuming():\n consumer = KafkaConsumer('app_messages', bootstrap_servers=KAFKA_HOST)\n\n for msg in consumer:\n message = json.loads(msg.value)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up an Arlo media player.
async def async_setup_platform(hass, _config, async_add_entities, _discovery_info=None): arlo = hass.data.get(COMPONENT_DATA) if not arlo: return players = [] for camera in arlo.cameras: if camera.has_capability(MEDIA_PLAYER_KEY): name = "{0}".format(camera.name) ...
[ "async def setup_media_source(hass: HomeAssistant) -> None:\n assert await async_setup_component(hass, \"media_source\", {})", "def setup_player(self):\n self.player = MortalPlayer(self.player_sprite_image, self.player_scaling)\n self.player.center_x = self.player_initial_x\n self.player.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize an Arlo media player.
def __init__(self, name, device): self._name = name self._unique_id = device.entity_id self._device = device self._name = name self._volume = None self._muted = None self._state = None self._shuffle = None self._position = 0 self._track_id...
[ "def init_player(self, player: Player) -> None:\r\n pass", "def __init__(self):\n self.audio = pyaudio.PyAudio()", "def _createAudioStream(self):\r\n if not os.access(self.filename, os.R_OK):\r\n raise RuntimeError('Error: %s file not readable' % self.filename)\r\n self._v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Audit vault and strategy configuration.
def audit(): governance = web3.ens.resolve('ychad.eth') registry = load_registry() vaults = load_vaults(registry) for v in vaults: if v.vault.governance() != governance: secho(f'{v.name} vault governance == {v.vault.governance()}', fg='red') print(f'{v.vault}.setGovernanc...
[ "async def audit(self, ctx):", "def describe_account_audit_configuration():\n pass", "def _setup_audit_log(self):\n from collective.fingerpointing.config import fingerpointing_config\n from collective.fingerpointing.logger import log_info\n self.temp_dir = tempfile.mkdtemp()\n fin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
n = number of sides, s = side length, both positive integers this function returns the sum of the area and square perimeter of the polygon described by n and s
def polysum(n, s): area = 0 #avoiding division by zero if n != 0: area = (0.25 * n * (s**2)) / math.tan(math.pi / n) perimeter = n * s return (round(area + perimeter**2, 4))
[ "def polySum(n, s):\n area = (0.25*n*s**2)/math.tan(math.pi/n)\n\n perimeter = n*s\n\n return round(area + perimeter**2, 4)", "def area_polygon(n, s):\n area = ((float(1)/float(4)) * n * s ** 2) / (math.tan(math.pi / n))\n return area", "def perimeter(n, s):\n return n * s", "def polygon...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print the \n separated lines in the string s, indented lvl levels.
def printIndent(s,lvl) : for line in s.split('\n') : print('%s%s' % (' '*lvl,line))
[ "def indent_lines(s, n):\n return \"\\n\".join(map(lambda line: \" \" * n + line, \n s.split('\\n')))", "def indent(s, depth):\n # type: (str, int) -> str\n spaces = \" \"*depth\n interline_separator = \"\\n\" + spaces\n return spaces + interline_separator.join(s.split(\"\\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the score of the game if L is the next to move. L looks for high scores. The score is the first item in the tuple that is returned. The remaining items are the sequence of games that led to this score.
def scoreL(self) : if self.leafL() : # # Here L has no possible moves. Return # the leaf score at the current leaf. # return self.leafScore(), self else : games = self.L() max_g = games[0] max_score = max_g....
[ "def scoreR(self) :\n if self.leafR() :\n return self.leafScore(), self\n else :\n games = self.R()\n min_g = games[0]\n min_score = min_g.scoreL()\n for g in games[1:] :\n score = g.scoreL()\n if score[0] < min_score...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the score of the game if R is the next to move. R looks for low scores
def scoreR(self) : if self.leafR() : return self.leafScore(), self else : games = self.R() min_g = games[0] min_score = min_g.scoreL() for g in games[1:] : score = g.scoreL() if score[0] < min_score[0] : ...
[ "def getscore(self, searchdepth):\n win = self.checkwin()\n if win:\n # this is a winning position - the score is known\n self.score = win\n return [], self.score\n elif searchdepth:\n nextmoves = self._possiblemoves()\n if len(nextmoves):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inverse current selected image by multiplying with 1.
def inverse_image(model): # get data and name from current selected image current_row = model.currentIndex().row() source_vol = model.data(model.index(current_row), Qt.UserRole + 6) source_name = model.data(model.index(current_row), Qt.DisplayRole) # inverse process inversed_vol = imtool.invers...
[ "def inv_img(img):\n return np.abs(img - 1.)", "def inverse(im): \t \n x,y = np.shape(im)\n img = np.zeros([x,y])\n\t\n for i in range(x):\n for j in range(y):\n img[i,j] = 255 - im[i,j]\n return img", "def __call__(self, images: tf.Tensor, level: tf.Tensor) -> tf.Tenso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
draw a tile returns None if bag is empty returns first tile first
def draw(self): tiles = list(self.bag.elements()) if len(tiles) == 0: return None if self.first_tile: chosen_tile = self.first_tile self.first_tile = None # done, we've drawn the first tile else: chosen_tile = random.choice(tiles) self.bag[chosen_tile] -= 1 return chos...
[ "def draw_tile(self, tile):\n raise NotImplemented()", "def get_tile(self, x, y):\n return None", "def render(self,tile):\n pass", "def draw_tile(self):\n if not self.selected:\n pygame.draw.rect(self.screen, self.color, self.rect)\n else:\n pygame.draw.rec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
does tile T fit in location L?
def tile_fits(self, location, tile): x, y = location CONNECTIONS_TO_CHECK = [ [(x+1, y), 'east', 'west'], [(x-1, y), 'west', 'east'], [(x, y+1), 'north', 'south'], [(x, y-1), 'south', 'north'] ] for neighbor_loc, my_offset, their_offset in CONNECTIONS_TO_CHECK: neighbor_ti...
[ "def in_grid(self, tile):\n return 0 <= tile[0] < self.gs[0] and 0 <= tile[1] < self.gs[1]", "def tileExist(x, y, maxX, maxY):\n # if the x and y values are in the map\n if x >= 0 and y >= 0:\n if x <= maxX and y <= maxY:\n return True\n else:\n return False", "def test_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lookup the 'all' and 'all_count' views from the metadata or construct defaults.
def get_views(view_args, model_type): # XXX Why pop? metadata = view_args.pop('metadata') all_view = metadata.get('views', {}).get('all') if not all_view: all_view= '%s/all'%model_type all_count_view = metadata.get('views', {}).get('all_count') if not all_count_view: all_count_vi...
[ "def documents(self, schema=None, wrapper=None, **params):\n return ViewResults(self.raw_view, '_all_docs',\n wrapper=wrapper, schema=schema, params=params)", "def _get_view_args(self, all_args):\n view_args = dict((k, v) for k,v in all_args.iteritems() if k in ('descending', 'stale',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a flash message box element.
def flash_message(self, request): return FlashMessagesElement()
[ "def getMessageBox(self, id):\n try:\n messageBoxWrapUp = self._getMessageBoxCompactWrapUp(id)\n\n return messageBoxWrapUp.messageBox\n except:\n return None", "def msg_box(msg, title=\"Information\", buttons=OK_LAYOUT):\n assert str(acm.Class()) == \"FTmServer\",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Confirm that the src and dest docs match in terms of id and rev, raising an HTTP exception on failure. A BadRequestError is raised if the ids do not match. A ConflictError is raised if the revs do not match.d
def confirm_doc_and_rev(src, dest): if src['_id'] != dest['_id']: raise http.BadRequestError('incorrect id') if src['_rev'] != dest['_rev']: raise http.ConflictError([('Content-Type', 'text/plain')], 'rev is out of date')
[ "def check_revision(self, request):\n assert hasattr(self, 'doc'), \"dispatcher document must be set\"\n try:\n rev = request.cgi_fields['_rev'].value\n except KeyError:\n return\n if rev != self.doc.rev:\n raise HTTP_CONFLICT(\"Your edit was based on an ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a form for the given model type.
def _form_for_type(request, C, defn, add_id_and_rev=False): form = build(defn, C, add_id_and_rev=add_id_and_rev, widget_registry=_widget_registry(request)) form.renderer = request.environ['restish.templating'].renderer return form
[ "def create_form_model(self, *args, **kwargs) -> Form:\n return Form.create_model(client=self, *args, **kwargs)", "def instantiate_form(self, model, *args, **kwargs) -> Form:\n return Form.instantiate(self=model, *args, **kwargs)", "def _form_class_factory(model_class):\n class FormClass(Member...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new doc from the model type and form data.
def _doc_create(type, data): doc = dict(data) doc.update({'model_type': type}) return doc
[ "def document_new():\n\n t = request.form['type']\n if t == 'book':\n doc = Book(\n title=request.form['title'],\n price=request.form['price'],\n keywords=comma_to_list(request.form['keywords']),\n authors=comma_to_list(request.form['authors']),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the adminish config from the request.
def _config(request): return request.environ['adminish']
[ "def _get_lsp_config_admin_up(self):\n return self.__lsp_config_admin_up", "def get_info_admin(self):\n return self.get_info(\"HS_ADMIN\")", "def getAdmin(self) -> Address:\n\t\treturn self._admin.get()", "def get_admin(self):\n pass", "def getConfiguration(self):\n # TODO what other...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a widget registry from the config, defaulting to couchish's default.
def _widget_registry(request): factory = _config(request).get('widget_registry_factory') or WidgetRegistry return factory(_store(request))
[ "def __init__(self, config_file):\r\n\t\t#Create empty list of widgets\r\n\t\tself.widgets = []\r\n\t\t#Read the json file into a data dictionary\r\n\t\twith open(config_file) as data_file:\r\n\t\t\tdata = json.load(data_file)\r\n\t\t#In this data dictionary, go to the value of widgets, which contains the informati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the correct errors are raised if Biopython is not available.
def test_config_no_biopython(monkeypatch): monkeypatch.setattr(core, 'HAVE_BIOPYTHON', False) assert core.HAVE_BIOPYTHON is False args = Namespace(extended_validation='all') with pytest.raises(ValueError): core.Config.from_args(args)
[ "def test_mbis_available():\n if which_import(\"psi4\", return_bool=True, raise_error=False):\n assert MBISCharges.is_available() is True\n else:\n with pytest.raises(ModuleNotFoundError):\n MBISCharges.is_available()", "def test_config_have_biopython():\n assert core.HAVE_BIOPYT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test we detect Biopython.
def test_config_have_biopython(): assert core.HAVE_BIOPYTHON args = Namespace(extended_validation='all') config = core.Config.from_args(args) assert config.extended_validation == 'all'
[ "def check_genome():", "def canUseBsPbgi(bi, bc, bgi):\n if Spec.spec.memory_type == 'DDR4' and bi > 1 and bc > 1:\n return bgi\n return False", "def test_mbis_available():\n if which_import(\"psi4\", return_bool=True, raise_error=False):\n assert MBISCharges.is_available() is True\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test appending multiple downloads into a single file.
def test_download_to_file_append(req, tmpdir): req.get(ENTREZ_URL, text='This works.\n') outdir = tmpdir.mkdir('outdir') filename = outdir.join('foo.txt') expected = outdir.join('foo.txt') config = core.Config(molecule='nucleotide', verbose=False, out='foo.txt') core.download_to_file('FOO', con...
[ "def test_download1(self):\n pass", "def test_download2(self):\n pass", "def test_download_strings():\n for download_method in (\"reuse_resources\", \"download_resources\"):\n check_download_method_updates(download_method)", "def download_files(self):", "def test_populate_downloads_m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test extended validation before writing.
def test_validate_and_write_extended_validation(req): handle = StringIO() req.get('http://fake/', text=u'>foo\nMAGIC') r = requests.get('http://fake/') config = core.Config(extended_validation='loads', molecule='protein') core._validate_and_write(r, handle, 'FAKE', config) assert handle.getvalu...
[ "def log_extra_validation(self):\n pass", "def test_extensions(self):\n field = TypedFileField(required=False, ext_whitelist=self.good_extensions)\n\n for ext in self.good_extensions:\n name = 'somefooname.%s' % ext\n file = UploadedFile(name=name, size=1)\n a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test getting a download stream handles exceptions.
def test_get_stream_exception(req): req.get(ENTREZ_URL, exc=requests.exceptions.RequestException) params = dict(id='FAKE') with pytest.raises(DownloadError): core.get_stream(ENTREZ_URL, params)
[ "def test_get_stream(self):\n pass", "def testLocalFileOpenFails(self):\n os.path.join(IsA(str), IsA(str)).AndReturn('')\n urllib.urlopen('test_url').AndReturn(self.test_file)\n self.mox.ReplayAll()\n self.assertFalse(cb_url_lib.Download(self.url))", "def test_download_url_not_found(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test getting a download stream handles bad status codes.
def test_get_stream_bad_status(req): req.get(ENTREZ_URL, text=u'Nope!', status_code=404) params = dict(id='FAKE') with pytest.raises(InvalidIdError): core.get_stream(ENTREZ_URL, params)
[ "def test_get_stream_exception(req):\n req.get(ENTREZ_URL, exc=requests.exceptions.RequestException)\n params = dict(id='FAKE')\n with pytest.raises(DownloadError):\n core.get_stream(ENTREZ_URL, params)", "def test_file_chunk_generator_with_bad_url(mock_get):\n url = 'www.example.com'\n mock...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test URL generation for API key
def test_generate_url_with_api_key(): config = core.Config(api_key='FAKE') expected = "{}?{}".format(ENTREZ_URL, "retmode=text&id=FAKE&db=nucleotide&api_key=FAKE&rettype=gbwithparts") assert expected == core.generate_url("FAKE", config) config.format = 'gff3' expected = "{}?{}".format(SVIEWER_URL, ...
[ "def test_create_api_key(self):\n pass", "def test_api_key_decorator_valid_call(self):\n api_key = self.owner.get_profile().key\n r = self.client.get(reverse('api_things_list', args=[api_key]))\n self.assertEquals(200, r.status_code)", "def test_api_key(self):\n self.assertEqu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the small tree contains a root value.
def test_root_value(small_tree): assert small_tree.root.value == 3
[ "def test_small_tree_has_root_value(small_tree):\n assert small_tree.root.right.value == 11", "def test_contains_true_small_tree_root(small_tree):\n assert small_tree.contains(50) is True", "def test_small_tree_has_no_root(small_tree):\n assert small_tree.root.left is None", "def test_val_root_filled...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that there is no left child of the small tree.
def test_small_tree_has_no_root(small_tree): assert small_tree.root.left is None
[ "def has_left_child(self: object) -> bool:\n return self.left is not None", "def test_root_left_empty():\n tree = BST()\n tree.insert(5)\n assert tree.root.left is None", "def has_left(self):\n return self.left != None", "def has_left_child(self, val):\n if self.contains(val) is ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that there is a value of the right child in the small tree.
def test_small_tree_has_root_value(small_tree): assert small_tree.root.right.value == 11
[ "def test_small_tree_has_right_child_child(small_tree):\n assert small_tree.root.right.right.value == 27", "def has_right_child(self, val):\n if self.contains(val) is False:\n return False\n return self.find(val).right is not None", "def test_search_for_a_node_value_on_left(small_tre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that there is a right child of the small tree.
def test_small_tree_has_right_child_child(small_tree): assert small_tree.root.right.right.value == 27
[ "def has_right_child(self: object) -> bool:\n return self.right is not None", "def is_right_child(self):\r\n return self.parent and self == self.parent.right", "def is_right_child(self):\n if self.parent == None:\n return False\n\n return self.parent.right == self", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a set with a minimal number of banknotes
def generate(self): # prepare data banknote_quantity_max = [int(math.floor(self.money / self.banknotes[i])) for i in range(0, self.n)] # model mdl = Model(name='MinSetGenerator') # decision variables mdl.banknote_quantity = {i: mdl.integer_var(lb=0, ub=banknote_quan...
[ "def create_set(max_num: int) -> List:\n missing = random.randint(1, max_num)\n num_set = [x for x in range(1, max_num + 1) if x != missing]\n random.shuffle(num_set)\n\n return num_set", "def buildSet(barcode,NrecMin):\r\n\t#set of possibilities that the string could be\r\n\t#if it were actually nucl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether exists another set with a minimal number of banknotes
def is_exist_another_solution(self): # prepare data notes_quantity_min = sum(self.banknote_quantity) banknote_quantity_max = [int(math.floor(self.money / self.banknotes[i])) for i in range(0, self.n)] # model mdl = Model(name='MinSetChecker') # decision variables ...
[ "def problem4():\n\n s2 = set(range(0, 21)[::2])\n s3 = set(range(0, 21)[::3])\n s4 = set(range(0, 21)[::4])\n print(s2)\n print(s3)\n print(s4)\n print(s3.issubset(s2))\n print(s4.issubset(s2))", "def has_infrequent_subset(Ck, Lks):\n ksSubset = combinations(Ck, r=len(Ck)-1)\n for k...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From Sqlmap Returns (basic conversion) HTML unescaped value >>> htmlunescape('a&lt;b') 'a<b'
def htmlunescape(value): retVal = value if value and isinstance(value, str): codes = (("&lt;", '<'), ("&gt;", '>'), ("&quot;", '"'), ("&nbsp;", ' '), ("&amp;", '&'), ("&apos;", "'")) retVal = reduce(lambda x, y: x.replace(y[0], y[1]), codes, retVal) try: ret...
[ "def htmlunescape(value):\n ret_val = value\n codes = (('&lt;', '<'), ('&gt;', '>'), ('&quot;', '\"'), ('&nbsp;', ' '), ('&amp;', '&'))\n ret_val = reduce(lambda x, y: x.replace(y[0], y[1]), codes, ret_val)\n try:\n ret_val = re.sub(r\"&#x([^ ;]+);\", lambda match: unichr(int(match.group(1), 16))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From Sqlmap Returns filtered page content without script, style and/or comments or all HTML tags >>> getFilteredPageContent(u'foobartest') u'foobar test'
def get_filtered_page_content(page, onlyText=True, split=" "): retVal = page # only if the page's charset has been successfully identified if isinstance(page, str): retVal = re.sub(r"(?si)<script.+?</script>|<!--.+?-->|<style.+?</style>%s" % (r"|<[^>]+>|\t|\n|\r" if onlyTex...
[ "def get_filtered_page_content(page, only_text=True, split=\" \"):\n ret_val = page\n ret_val = re.sub(r\"(?si)<script.+?</script>|<!--.+?-->|<style.+?</style>%s\" % (r\"|<[^>]+>|\\t|\\n|\\r\" if only_text else \"\"),split, page)\n while ret_val.find(2 * split) != -1:\n ret_val = ret_val.replace(2 *...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that an event admin for a different event can't get a tag.
def test_get_event_admin_correct_event(self): self.seed_static_data() params = {'id': 1, 'event_id': 1} response = self.app.get('/api/v1/tag', headers=self.user2_headers, data=params) self.assertEqual(response.status_code, 403)
[ "def test_conflict_with_tags(self):\n character = self.create_character()\n\n # Add a permission and a tag\n character.permissions.add(\"admin\")\n character.tags.add(\"blue\")\n\n # Make sure 'blue' is not a permission\n self.assertEqual(character.permissions.search(\"blue...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse file into list of strings, some of which are hoped to have valid XML for a docket. Returns list of all 'good' dockets, where good means the string is wellformed XML. If any string in list has '' or '' in it, entire file will be rejected.
def parseBadFileAsString(self,myfile): def removeTopDocketTags(string): return re.sub(r'<dockets>\n<docket>','',string) def removeBottomDocketTags(string): return re.sub(r'</docket>\n</dockets>$','',string) def makeListOfDocketsAsText(string): ...
[ "def xmlCheck(filename):\n #return(filename.read())\n final = []\n wordList = []\n openTag = Stack()\n closeTag = Stack()\n word = []\n checkClose = []\n checkOpen = []\n text = ''.join(filename.read())\n #print(text)\n tagging = False\n close = False\n valid = True\n for i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Overriding a forms' __init__ method to perform validation checks on the verb category level within the taxonomy
def initialise(self, FormClass, *args, **kwargs): self.taxonomy = kwargs.pop('taxonomy', None) # The original/old category, for update view case self.old_category = kwargs.pop('category', None) super(FormClass, self).__init__(*args, **kwargs)
[ "def clean_level_(self):\n try:\n # Get the verb categories of the taxonomy\n verb_cats = VerbCategory.objects.filter(taxonomy=self.taxonomy)\n except Taxonomy.DoesNotExist:\n raise Http404('The taxonomy does not exist!')\n else:\n\n # Check categorie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure the user does not input a level value equal to that of a preexisting verb category of the taxonomy
def clean_level_(self): try: # Get the verb categories of the taxonomy verb_cats = VerbCategory.objects.filter(taxonomy=self.taxonomy) except Taxonomy.DoesNotExist: raise Http404('The taxonomy does not exist!') else: # Check categories for the ent...
[ "def category_validation(user_category, level_data_info):\n\n count = 0\n for data in level_data_info:\n if data[\"category\"] == user_category:\n count = count + 1\n else:\n pass\n \n if count == 0:\n return print(\"You chose an invalid category, please try ag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
dexterity should be installed when we install documentgenerator
def test_dexterity_is_dependency_of_documentgenerator(self): dependencies = self.portal.portal_setup.getProfileDependencyChain('collective.documentgenerator:default') self.assertTrue(u'profile-plone.app.dexterity:default' in dependencies)
[ "def docfx(session):\n\n session.install(\"-e\", \".\")\n session.install(\n \"gcp-sphinx-docfx-yaml\",\n \"alabaster\",\n \"recommonmark\",\n )\n\n shutil.rmtree(os.path.join(\"docs\", \"_build\"), ignore_errors=True)\n session.run(\n \"sphinx-build\",\n \"-T\", #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
z3cform.datagridfield should be installed when we install documentgenerator
def test_z3cformdatagridfield_is_dependency_of_documentgenerator(self): dependencies = self.portal.portal_setup.getProfileDependencyChain('collective.documentgenerator:default') self.assertTrue(u'profile-collective.z3cform.datagridfield:default' in dependencies)
[ "def define_fields(cls, dbmanager):\n return []", "def addProductFields(form, forCreation=False, restWriter=None, hasOptions=False):\n form.addField('code', formal.String(required=True, strip=True))\n form.addField('title', formal.String(required=True, strip=True))\n\n images = formal.Group('image...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LOADs a React.js component into the action's document
def RLOAD(url, mount_point=None, jsx_compile_expire=1, content='bitte warten ...', **attr): # Element ID (mount_point) zuweisen mount_point = mount_point or 'c' + str(random.random())[2:] attr['_id'] = mount_point """ JSX in JS umwandeln (react.js) """ jsx_filepath = os.path.join(...
[ "def render_react_view(request, component_name=None):\n template = 'index.html'\n context = {\n 'component_name': component_name,\n }\n return render(request, template, context)", "def component_route():\n return render_template(\"component.html\")", "def Component(self) -> object:", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
web2py .jsx View compilieren und js als String zurückgeben
def transform_jsx_view(jsx_filepath): js = '' if jsx_filepath.endswith('.jsx'): # .jsx Datei wird geöffnenet und umgewandelt js_filepath = jsx_filepath.replace('.jsx', '.js') js = jsx.transform(jsx_filepath) return js
[ "def get_js_component(self):\n return 'View';", "def RLOAD(url, mount_point=None, jsx_compile_expire=1, content='bitte warten ...', **attr):\n \n # Element ID (mount_point) zuweisen \n mount_point = mount_point or 'c' + str(random.random())[2:]\n attr['_id'] = mount_point\n \n \"\"\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset a exponent alpha.
def reset_alpha(self, alpha): self.alpha, old_alpha = alpha, self.alpha priorities = [(self.tree.get_val(i) + self.__e) ** - old_alpha for i in range(self.tree.filled_size())] self.priority_update(range(self.tree.filled_size()), priorities)
[ "def reset_alpha(self, alpha: float):\n tree_len = len(self.tree)\n self.alpha, old_alpha = alpha, self.alpha\n priorities = [pow(self.tree[i], -old_alpha) for i in range(tree_len)]\n self.priority_update(range(tree_len), priorities)", "def reset_alpha(self, alpha):\n self.alpha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
you can provde a key or a session to sign the URL if none provided will use the global Session.SECRET salt is some salt that can be used in signing if desired. variables_to_sign is a list of variables to be included in the signature.
def __init__(self, session=None, key=None, salt=b"", variables_to_sign=None): super().__init__() # Yes, I know that this currently doesn't do anything. self.session = session self.key = key or Session.SECRET self.salt = salt self.variables_to_sign = variables_to_sign or [] ...
[ "def sign_vars(self, url, vars):\n vars[\"_signature\"] = self._sign(url, vars)", "def test_sign_with_key(self):\n data = {\n 'name': 'wechat'\n }\n resp = SignUtil.sign(data, 'secret')\n self.assertEqual(resp, '10B479F834276384C96A0F074A1A7AF8')", "def get_signed(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the signing key, creating it if necessary.
def _get_key(self): if not self.session: key = self.key else: key = self.session.get("_signature_key") if key is None: key = str(uuid.uuid1()) self.session["_signature_key"] = key return key
[ "def createSigningRequest(self, keyName):\n return self._identityManager.getPublicKey(keyName).getKeyDer()", "def generate_signing_key(self):\n sk = SigningKey.generate(curve=SECP256k1)\n vk = sk.get_verifying_key()\n self.sign_private_key = sk\n self.sign_public_key = vk", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Signs a URL, adding to vars (the variables of the URL) a signature.
def sign_vars(self, url, vars): vars["_signature"] = self._sign(url, vars)
[ "def sign_url(input_url=None, secret=None):\n\n if not input_url or not secret:\n raise Exception(\"Both input_url and secret are required\")\n\n url = urlparse.urlparse(input_url)\n\n # We only need to sign the path+query part of the string\n url_to_sign = url.path + \"?\" + url.query\n\n # D...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark given class as the entity for User.
def register_user(self, cls): return self.register_entity('user', cls)
[ "def user_objectclass(self, user_objectclass):\n\n self._user_objectclass = user_objectclass", "def set_user(self, user):\r\n self.user = user", "def setUser(user):", "def set_as_type_user(self):\n self.type = MessageTypes.USER", "def save_user(self):\n db.session.add(self)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark given class as the entity for Permission.
def register_permission(self, cls): return self.register_entity('permission', cls)
[ "def command_set_entity_acl(syn, args):\n permissions.set_entity_permissions(\n syn,\n args.entityid,\n principalid=args.principalid,\n permission_level=args.permission_level,\n )", "def setPermission(self, request):\n pass", "def set_permission(\n permission: Permission,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark given class as the entity for Bundle.
def register_bundle(self, cls): return self.register_entity('bundle', cls)
[ "def bundle(self, bundle):\n\n self._bundle = bundle", "def asset_class(self, asset_class):\n\n self._asset_class = asset_class", "def register_class(self, entity_class):\n key = entity_class.__collection_name__\n\n if key not in self._registered_types:\n self._registered_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark given class as the entity for Group.
def register_group(self, cls): return self.register_entity('group', cls)
[ "def group(self, group):\n self._group = group", "def group(self, group):\n \n self._group = group", "def group(self, group):\n\n self._group = group", "def set_group(self, group):\n self._group = group", "def assign_group(self, group):\n self[\"case group\"] = grou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark given class as the entity for Attempt.
def register_attempt(self, cls): return self.register_entity('attempt', cls)
[ "def attempt(self, attempt):\n\n self._attempt = attempt", "def attempt_cls(self):\n return self.get_entity_cls('attempt')", "def _class(self, _class):\n\n self.__class = _class", "def entity(self, entity):\n\n self._entity = entity", "def clazz(self, clazz):\n\n self._cla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the entity registered for Bundle.
def bundle_cls(self): return self.get_entity_cls('bundle')
[ "def get_entity(self):\n return self.__entity", "def GetEntity(self):\n return self.__entity", "def getEntity(self):\n return self._entity", "def entity(self):\n return self._entity", "def get_entity(self):\n entity = None\n obj = self.get_object()\n if obj:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the entity registered for Attempt.
def attempt_cls(self): return self.get_entity_cls('attempt')
[ "def get_entity(self):\n return self.__entity", "def GetEntity(self):\n return self.__entity", "async def get_entity(self):\n if not self.entity and await self.get_input_entity():\n try:\n self._entity =\\\n await self._client.get_entity(self._inpu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return True if N is square number
def is_square(N): if N < 0: print("N is negative number @is_square in ModulesFactorization.") sys.exit() sqrt_N=round(math.sqrt(N)) if N == sqrt_N*sqrt_N: return True else: return False
[ "def is_square(N):\n return N == round(N**(0.5))**2", "def is_square(n):\r\n m = int(sqrt(n))\r\n return m * m == n", "def is_square(n):\n return int(math.sqrt(n)) ** 2 == n", "def is_square(n):\n if type(n) is not int:\n raise ValueError(\"Wrong given type, should be integer instead\")\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return positive integer N for string N_str
def PositiveInt(N_str): try: N = int(N_str) except ValueError: print("整数を入力してください。") sys.exit() if N <= 0: print("0以下の整数です。1以上の自然数を入力してください。") sys.exit() return N
[ "def string_times(str, n):\n if n <= 0:\n return('n has to be non-negative')\n else:\n return(str * n)", "def n_gram_number(string_length, n):\n return string_length - n + 1", "def getNumStr(self, idx):\r\n\r\n if idx<0:\r\n idx = self.numCount()+idx\r\n if idx<0 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the user was mentioned in the given message.
def mentioned(self, message: "Message") -> bool: raise NotImplementedError
[ "def mentioned_in(self, message: Message) -> bool:\n if message.guild is None or message.guild.id != self.guild.id:\n return False\n\n if self._user.mentioned_in(message):\n return True\n\n return any(self._roles.has(role.id) for role in message.role_mentions)", "def has...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the given string is an action.
def is_action_str(string: str) -> bool:
[ "def is_action(self) -> bool:\n return self.is_action_str(self.content)", "def _isAction(url, action):\n return \"/%s/\"%action in url or \"/%s?\"%action in url or url.endswith(\"/%s\"%action)", "def isActionKey(event_string):\n\n actionKeys = [ \"Return\", \"Escape\", \"Tab\", \"BackSpace\", \"Del...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the given string as an action.
def as_action_str(string: str) -> str:
[ "def str_to_action(str):\n raise NotImplementedError", "def str2action(s: str) -> Netio.ACTION:\n try:\n return Netio.ACTION[s.upper()]\n except KeyError or AttributeError:\n try:\n return Netio.ACTION(int(s))\n except ValueError:\n raise argparse.ArgumentTy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Strip the action formatting from the given string.
def strip_action_str(string: str) -> str:
[ "def strip_action(self) -> str:\n return self.strip_action_str(self.content)", "def stripFormatting(self, s):\n # stripColor has to go first because of some strings, check the tests.\n s = stripColor(s)\n s = stripBold(s)\n s = stripReverse(s)\n s = stripUnderline(s)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether the message is an action.
def is_action(self) -> bool: return self.is_action_str(self.content)
[ "def check_if_event_is_action(msg):\n\treturn dict(msg).__contains__('entityID')", "def is_valid_action(self, action):\n if self.board[action[0]][action[1]] == None:\n return True\n \n return False", "def match_action(self, action):\n\n return hasattr(self, self._action_ha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the message as an action.
def as_action(self) -> str: return self.as_action_str(self.content)
[ "def get_rabbit_action(self, action):\n return action", "def _construct_action_message(self):\n prep = self.action_type.preposition\n target_obj = self.target_content_object\n\n if prep and target_obj:\n msg = \"%s has %s %s %s %s\" % (self.user, self.action_type.verb,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Strip the action formatting from the message.
def strip_action(self) -> str: return self.strip_action_str(self.content)
[ "def strip_formatting(self, msg):\n return re.sub('([\\x02\\x1D\\x1F\\x16\\x0F]|\\x03([0-9]{2})?)', '', msg)", "def strip_action_str(string: str) -> str:", "def clean_message(self, message):\n return message", "def clean(self, message):\n\n for color in self.colors.keys():\n me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all available stream names of a module
def getAllStreams(name): global index module = index.get_module(name) if not module: return None streams = set() for s in module.get_all_streams(): streams.add(s.get_stream_name()) return list(streams)
[ "def _GetStreamNames(self):\n if self._zipfile:\n for stream_name in self._zipfile.namelist():\n yield stream_name", "def get_log_stream_names(log_group_name):\r\n client = boto3.client('logs')\r\n streams = client.describe_log_streams(logGroupName=log_group_name)\r\n log_stream_names = []...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the default stream name of a module
def getDefaultStream(name): global index module = index.get_module(name) if not module: raise ValueError("Module '{}' not found".format(name)) defaults = module.get_defaults() if defaults: return defaults.get_default_stream() return module.get_all_streams()[0].get_stream_name()
[ "def get_stream_name(self) -> str:\n return getattr(self.stream, \"name\", \"\")", "def get_stream_name(self) -> str:\n return self.stream.name or \"\"", "def stream_name(self):\n return self._stream_name", "def get_stream_alias(self) -> str:", "def log_stream_name(self) -> str:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the enabled stream name of a module, or the default stream if not enabled
def getEnabledOrDefault(name): if name == 'platform': return 'el8' if name not in enabledStreams: return getDefaultStream(name) enabled = enabledStreams[name] return enabled.get_stream_name()
[ "def getDefaultStream(name):\n global index\n module = index.get_module(name)\n if not module:\n raise ValueError(\"Module '{}' not found\".format(name))\n defaults = module.get_defaults()\n\n if defaults:\n return defaults.get_default_stream()\n\n return module.get_all_streams()[0]....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get module names that a stream depends on
def getDeps(stream): return stream.get_dependencies()[0].get_runtime_modules()
[ "def get_module_names(self):\n raise NotImplementedError", "def getModuleNames():\n import setup\n names = [e.name[1:] for e in setup.wxpExtensions]\n return names", "def get_module_names(config):\n lambdas_path = config['lambdas_path']\n return [f.strip('.py') for f in os.listdir(lambdas_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all available context for a module and a stream name
def getAllContexts(name, stream): global index module = index.get_module(name) if not module: return [] allStreams = module.get_all_streams() allContexts = [] for s in allStreams: if s.get_stream_name() == stream: allContexts.append(s) return allContexts
[ "def get_contexts(self):\n return self.__contexts", "def xontrib_context(name):\n spec = find_xontrib(name)\n if spec is None:\n return None\n m = importlib.import_module(spec.name)\n pubnames = getattr(m, \"__all__\", None)\n if pubnames is not None:\n ctx = {k: getattr(m, k) for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively enable a stream and its dependencies with their default streams, unless already enabled with a different stream.
def pickStream(name, stream): if isEnabled(name): return allDeps = set() allContexts = getAllContexts(name, stream) for c in allContexts: allDeps = allDeps.union(getDeps(c)) enabledDeps = [] for d in allDeps: enabledDeps.append((d ,getEnabledOrDefault(d))) for ctx ...
[ "def enableRecursiveProcessing(self, enabled: bool) -> None:\n ...", "def attach_streams(plot, obj, precedence=1.1):\n def append_refresh(dmap):\n for stream in get_nested_streams(dmap):\n if plot.refresh not in stream._subscribers:\n stream.add_subscriber(plot.refresh, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of RPMs to blacklist
def getRpmBlacklist(): global index enabledRpms = set() for stream in enabledStreams.values(): enabledRpms = enabledRpms.union(stream.get_rpm_artifacts()) allRpms = set() for name in index.get_module_names(): module = index.get_module(name) for stream in module.get_all_strea...
[ "def wildcard_blacklists(connection):\n PiholeCLI(connection).get_wildcard_blacklist()", "def getUnblockers():", "def blacklist(self) -> List[str]:\n return self.raw_config.get(\"blacklist\", [])", "def get_blacklist():\n with BLACKLIST_LOCK:\n return dict(BLACKLIST)", "def black...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all modular rpms in the repository
def getAllPackages(metadataPaths): global index index = createModuleIndex(metadataPaths) allRpms = [] for name in index.get_module_names(): module = index.get_module(name) for stream in module.get_all_streams(): allRpms.extend(stream.get_rpm_artifacts()) return allRpms
[ "def modules(self):\n for modpath in self.modpaths():\n yield modpath.module", "def module_list(self):\n return self.mod.modules()", "def modules():\n return [os.path.relpath(os.path.join(root, filename), 'groot_ansible')\n for root, _, filenames in os.walk('groot_ansible/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert data into an empty linked list and check whether header node's next has None
def test_insert_head_empty_list_2(test_linkedlist): test_linkedlist.insert_head('A') assert test_linkedlist.head.next is None
[ "def insert_head(self, data):\n node = Node(data)\n node.next = self.head\n self.head = node", "def insert_end(self, data):\n\n if self.head is None:\n self.head = ListNode(data)\n else:\n temp = self.head\n while temp.next is not None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert head element to a single element linked list and check whether header node has expected data.
def test_insert_head_one_element_list_1(test_linkedlist): test_linkedlist.insert_head('A') test_linkedlist.insert_head('B') assert test_linkedlist.head.data == 'B'
[ "def test_insert_head_empty_list_2(test_linkedlist):\n test_linkedlist.insert_head('A')\n assert test_linkedlist.head.next is None", "def test_insert_head_one_element_list_2(test_linkedlist):\n test_linkedlist.insert_head('A')\n test_linkedlist.insert_head('B')\n assert test_linkedlist.head.next.da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert head element to a single element linked list and check whether header node.next points to second element
def test_insert_head_one_element_list_2(test_linkedlist): test_linkedlist.insert_head('A') test_linkedlist.insert_head('B') assert test_linkedlist.head.next.data == 'A'
[ "def test_insert_head_empty_list_2(test_linkedlist):\n test_linkedlist.insert_head('A')\n assert test_linkedlist.head.next is None", "def test_insert_head_one_element_list_1(test_linkedlist):\n test_linkedlist.insert_head('A')\n test_linkedlist.insert_head('B')\n assert test_linkedlist.head.data ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert head element to a two element linked list and check whether header node has expected data.
def test_insert_head_for_two_element_list_1(test_linkedlist): test_linkedlist.insert_head('A') test_linkedlist.insert_head('B') test_linkedlist.insert_head('C') assert test_linkedlist.head.data == 'C'
[ "def test_insert_head_one_element_list_2(test_linkedlist):\n test_linkedlist.insert_head('A')\n test_linkedlist.insert_head('B')\n assert test_linkedlist.head.next.data == 'A'", "def test_insert_head_empty_list_2(test_linkedlist):\n test_linkedlist.insert_head('A')\n assert test_linkedlist.head.nex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert last element to an empty element linked list and check whether header node has expected data
def test_insert_end_for_empty_list(test_linkedlist): test_linkedlist.insert_end('A') assert test_linkedlist.head.data == 'A'
[ "def insertAtEnd(self, e):\n # self.insertBeforeHeader(e) # this is not true since the head will be changed\n \n if self.is_empty(): # if this is the first insert method call,\n print(\"As you do not have any start node yet, the given element will be a start node.\")\n self._first_insert(e)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert last element to a single element linked list and check whether the last node has expected data
def test_insert_end_for_one_element_list(test_linkedlist): test_linkedlist.insert_end('A') test_linkedlist.insert_end('B') assert test_linkedlist.head.data == 'A'
[ "def test_insert_end_for_empty_list(test_linkedlist):\n test_linkedlist.insert_end('A')\n assert test_linkedlist.head.data == 'A'", "def test_insert_end(self):\n sll = SinglyLinkedList()\n a = Node('a')\n b = Node('b')\n c = Node('c')\n sll.insert_beg(a)\n sll.inser...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a 3 element linked list with a cycle and test whether cycle_present() function detects it
def test_cycle_present_true(test_linkedlist): test_linkedlist.insert_end('A') test_linkedlist.insert_end('B') test_linkedlist.insert_end('C') # create a cycle - connection from 3rd to 2nd element test_linkedlist.head.next.next.next = test_linkedlist.head.next # assert cycle_present() function re...
[ "def has_cycle(link):\n lst=[]\n while link.rest:\n if link in lst:\n return True\n lst.append(link)\n link = link.rest\n return False", "def has_cycle(link):\r\n # collect_list = [link]\r\n # while not link == Link.empty:\r\n # collect_list.append(link.first)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Class constructor. Creates one of seven basic shapes.
def __init__(self, shape_num): self.shape_num = shape_num if shape_num == 1: self.width = 4 self.height = 4 self.grid = [[0 for x in range(self.height)] for y in range(self.width)] self.grid[0][2] = 1 self.grid[1][2] = 1 self.grid[2...
[ "def __init__(self, width, height, relevant_colors, number_of_objects):\n self.shapes = []\n for i in range(0, number_of_objects):\n s = Shape(width, height, relevant_colors)\n self.shapes.append(s)", "def __init__(self, shape):\n self.eyes = [(), ()]\n self.shape...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A high level description of the cell with global identifier gid. For example the morphology, synapses and ion channels required to build a multicompartment neuron.
def cell_description(self, gid): tree = arbor.segment_tree() tree.append( arbor.mnpos, arbor.mpoint(0, 0, 0, self.radius), arbor.mpoint(self.length, 0, 0, self.radius), tag=1, ) labels = arbor.label_dict({"cable": "(tag 1)", "start": "(l...
[ "def gid(self):\n return int(self._owned_book_dict[\"id\"][\"#text\"])", "def gid(self):\n return safeInt(self.tag(\"gid\"))", "def global_replication_group_description(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"global_replication_group_description\")", "def __repr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify LMBiSeNet.post_process() is the same as Bilinear and Softmax post process
def test_lm_bisenet_post_process(): tf.InteractiveSession() image_size = [96, 64] batch_size = 2 classes = Camvid.classes data_format = "NHWC" model = LMBiSeNet( image_size=image_size, batch_size=batch_size, classes=classes, data_format=data_format, ) p...
[ "def test_postprocess_out_framesize(self):\n config = self.read_config()\n mean = config['quantization']['mean']\n std = config['quantization']['std']\n frame = np.zeros(shape=(config['input_shape'] + [3]), dtype=np.float32)\n mask = np.zeros(shape=(192 * 192,), dtype=np.uint8)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Custom Modules Menu for help
def menu_help(cls, **attr): menu_help = MM("Help", c="default", f="help", **attr)( MM("Contact us", f="contact"), MM("About", f="about"), MM(current.T("Ask MSW"), c="org", f="ask_msw"), MM("spiegel.de", c="org", f="spiegel"), ) return menu_help
[ "def __help_menu(self):\n\n help_menu = ControllableMenu(self.menubar,tearoff=0,name='help')\n self.menubar.add_cascade(label='Help',menu=help_menu)\n\n help_menu.add_command(label='About',command=self.new_about_window)\n help_menu.add_command(label=\"User Manual\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ORG / Organization Registry
def org(): settings = current.deployment_settings ADMIN = current.session.s3.system_roles.ADMIN SECTORS = "Clusters" if settings.get_ui_label_cluster() \ else "Sectors" stats = lambda i: settings.has_module("stats") return M(c="org")( ...
[ "def atlas_organizations():\n pass", "def organizations(self):\n self.elements('organizations')", "def _get_organizations(self):\n return self.__organizations", "def obj2org(self, obj):\n return obj.organization", "def test_get_organization(self):\n pass", "def test_retrieve_l_o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a new naturally sorted list from the items in iterable. The returned list is in natural sort order. The string is ordered lexicographically (using the Unicode code point number to order individual characters), except that multidigit numbers are ordered as a single character. Has two optional arguments which must...
def natural_sorted(iterable, key=None, reverse=False): prog = re.compile(r"(\d+)") def alphanum_key(element): """Split given key in list of strings and digits""" return [int(c) if c.isdigit() else c for c in prog.split(element[0])] return sorted(iterable, key=alphanum_key, reverse=reverse)
[ "def sort_mixed(iterable):\n return sorted(iterable, key=lambda x: split_string_at_numbers(x))", "def natsorted(iterable):\n return sorted(iterable, key=ft.cmp_to_key(natcmp))", "def natural_sort(arr):\n\n def atoi(text):\n 'natural sorting'\n return int(text) if text.isdigit() else text\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the selection method.
def selection(self) -> str: return self._selection
[ "def selection_function(self) -> SelectionFunction:\n return self._selection_function", "def getSelection(self): # real signature unknown; restored from __doc__\r\n pass", "def sel_mode(self):\n return self._sel_mode", "def get_selection(self):\r\n return self.value", "def get_me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill the internal buffer with domains.
def fill_buffer(self, num_domains: int): if self._randomizer is None: raise pyrado.TypeErr(msg="The randomizer must not be None to call fill_buffer()!") if not isinstance(num_domains, int) or num_domains < 0: raise pyrado.ValueErr(given=num_domains, g_constraint="0 (int)") ...
[ "def _set_domains(self, domains):\n\n #resort and reshape data according to mirror transforms\n O = self.orientation_from_basis(self.basis_from_domains(domains))\n I = np.argsort(O, axis=1) #sort along transform axis\n mdim = len(np.unique(O[0])) #number of orientations encount...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Go through the environment chain and remove all wrappers of type `DomainRandWrapper` (and subclasses).
def remove_all_dr_wrappers(env: Env, verbose: bool = False): while any(isinstance(subenv, DomainRandWrapper) for subenv in all_envs(env)): if verbose: with completion_context( f"Found domain randomization wrapper of type {type(env).__name__}. Removing it now", col...
[ "def env_cleanup(self):\n pass", "def clean_env():\n for key in ['FOO', 'THOR', 'IRON', 'NAME', 'PERSONAL_DIR']:\n os.environ.pop(key, None)", "def clean_environment():\n for key in ['GEM_PATH', 'LD_LIBRARY_PATH', 'LD_PRELOAD']:\n os.environ.pop(key, None)", "def reset_sys_modules()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test draw an empty circuit
def test_empty_circuit(self): filename = self._get_resource_path('test_empty.tex') qc = QuantumCircuit(1) circuit_drawer(qc, filename=filename, output='latex_source') self.assertEqualToReference(filename)
[ "def test_ionq_empty_circuit():\n backend = _ionq.IonQBackend(verbose=True)\n eng = MainEngine(backend=backend)\n eng.flush()", "def test_include_empty_wires(self):\r\n\r\n dev = qml.device(\"default.qubit\", wires=[-1, \"a\", \"q2\", 0])\r\n\r\n @qml.beta.qnode(dev)\r\n def circuit(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test draw tiny circuit.
def test_tiny_circuit(self): filename = self._get_resource_path('test_tiny.tex') qc = QuantumCircuit(1) qc.h(0) circuit_drawer(qc, filename=filename, output='latex_source') self.assertEqualToReference(filename)
[ "def testdraw():", "def test_simple_circuit_example(self):\n self.assertEqual(\"\\nL\\ng1:AND(N(w1),w2)\\nL\\ng2:OR(g1,w3)\\nL\\nog:XOR(g1,g2)\",\n self.circ.display())\n self.assertEqual(3, self.circ.get_num_inputs())\n self.assertEqual(False, self.circ.evaluate([True...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test draw deep circuit.
def test_deep_circuit(self): filename = self._get_resource_path('test_deep.tex') qc = QuantumCircuit(1) for _ in range(100): qc.h(0) circuit_drawer(qc, filename=filename, output='latex_source') self.assertEqualToReference(filename)
[ "def test_selfinnerproduct(self):\n qkclass = QuantumKernel(feature_map=self.feature_map)\n qc = qkclass.construct_circuit(self.x)\n self.assertEqual(qc.decompose().size(), 4)", "def test_simple_circuit_example(self):\n self.assertEqual(\"\\nL\\ng1:AND(N(w1),w2)\\nL\\ng2:OR(g1,w3)\\nL\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test draw huge circuit.
def test_huge_circuit(self): filename = self._get_resource_path('test_huge.tex') qc = QuantumCircuit(40) for qubit in range(39): qc.h(qubit) qc.cx(qubit, 39) circuit_drawer(qc, filename=filename, output='latex_source') self.assertEqualToReference(filenam...
[ "def test_deep_circuit(self):\n filename = self._get_resource_path('test_deep.tex')\n qc = QuantumCircuit(1)\n for _ in range(100):\n qc.h(0)\n\n circuit_drawer(qc, filename=filename, output='latex_source')\n\n self.assertEqualToReference(filename)", "def test_tiny_ci...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test draw teleport circuit.
def test_teleport(self): from qiskit.circuit.library import U3Gate filename = self._get_resource_path('test_teleport.tex') qr = QuantumRegister(3, 'q') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, cr) # Prepare an initial state qc.append(U3Gate(0.3, 0.2,...
[ "def test_teleport(self):\n self.log.info('test_teleport')\n pi = np.pi\n shots = 2000\n qr = QuantumRegister(3, 'qr')\n cr0 = ClassicalRegister(1, 'cr0')\n cr1 = ClassicalRegister(1, 'cr1')\n cr2 = ClassicalRegister(1, 'cr2')\n circuit = QuantumCircuit(qr, cr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test circuit with global phase
def test_global_phase(self): filename = self._get_resource_path('test_global_phase.tex') circuit = QuantumCircuit(3, global_phase=1.57079632679) circuit.h(range(3)) circuit_drawer(circuit, filename=filename, output='latex_source') self.assertEqualToReference(filename)
[ "def test_circuit_init(self):\n circuit, target = self.simple_circuit_no_measure()\n op = Chi(circuit)\n target = Chi(target)\n self.assertEqual(op, target)", "def test_circuit_init(self):\n circuit, target = self.simple_circuit_no_measure()\n op = Operator(circuit)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a new Activity Stream feed URL to update every interval seconds.
def register(self, url, interval=300): param_d = { 'url': url, 'interval': interval, # seconds } r = self._send_request('feeds/register', param_d, http_post=False) # Return True on success. if 'result' in r and r['result'] == 'success': return ...
[ "def add_rss(url):", "def add_feed(self, url, feed):\n print \"Adding the podcast: %s\" % url\n self.t.click(\"Sidebar\")\n self.shortcut('n')\n time.sleep(2)\n type(url + \"\\n\")\n time.sleep(10) #give it 10 seconds to add and update the feed\n self.click_podcast...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a certain URL form the list of Activity Stream feeds registered earlier.
def unregister(self, url): param_d = { 'url': url, } r = self._send_request('feeds/unregister', param_d, http_post=False) # Return True on success. if 'result' in r and r['result'] == 'success': return True else: return False
[ "def remove_seen(self, url):\n self.seen.delete(url)", "def remove_feed(self, feed):\n url = feed_argument(feed)\n with self.db:\n rows = self.db.execute(\"\"\"\n DELETE FROM feeds\n WHERE url = :url;\n \"\"\", locals())\n if rows...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints sorted item of the list data structure formated using the rows and columns parameters
def print_sorted_list(data, rows=0, columns=0, ljust=10): if not data: return if rows: # column-wise sorting # we must know the number of rows to print on each column # before we print the next column. But since we cannot # move the cursor backwards (unless using ncurse...
[ "def printGrid(self):\n for row in self.content:\n print_list = []\n for tuble in row:\n print_list.append(str(tuble[0])+tuble[1])\n print(print_list)\n print()", "def show(items):\n\n for item in sorted(items):\n print(item)", "def print_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }