query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Checks that the actor is not entering something that they are holding. | def before_entering_check_not_possession(actor, x, ctxt) :
loc = ctxt.world[Location(x)]
while not ctxt.world[IsA(loc, "room")] :
if loc == actor :
raise AbortAction("{Bob|cap} can't enter what {bob} {is} holding.", actor=actor)
loc = ctxt.world[Location(loc)] | [
"def check_invincibility(self):\n if not self.hittable and self.time_hit + 1200 <= pygame.time.get_ticks():\n self.hittable = True\n else:\n pass",
"def before_taking_check_not_inside(actor, x, ctxt) :\n loc = ctxt.world[Location(actor)]\n while not ctxt.world[IsA(loc, \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For a container, put the actor in it. | def when_entering_container(actor, x, ctxt) :
ctxt.world.activity.put_in(actor, x) | [
"def add_container(self, container):\n self.__container_list.append(container)",
"def add_actor(self, actor):\n self._actors.append(actor)",
"def merge_container(self, container):\n logger.debug('Merging containers')\n print(type(self))\n\n self._add_to_container(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Describes the contents of the new location if the actor is the actor of the context, disabling the location heading and the location description, unless there is a locale description, in which case a complete room description is given. | def report_entering_describe_contents(actor, x, ctxt) :
if ctxt.actor == actor :
if ctxt.world[LocaleDescription(x)] :
ctxt.write("[newline]")
ctxt.activity.describe_current_location(actor)
else :
vis_cont = ctxt.world[VisibleContainer(x)]
ctxt.world[G... | [
"def describe_location_Description(actor, loc, vis_cont, ctxt) :\n if ctxt.world[ContainsLight(vis_cont)] :\n # It's possible it makes more sense to walk up the chain of\n # locations until we hit a LocaleDescription. I have no\n # examples yet.\n localedesc = ctxt.world[IsA(loc, \"t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the event.exit_from attribute if it's not already set. If we're exiting from a supporter, then instead do GettingOff. | def before_Exiting_set_exit_from(event, actor, ctxt) :
if not event.exit_from :
event.exit_from = ctxt.world[Location(actor)]
if ctxt.world[IsA(event.exit_from, "supporter")] :
newaction = GettingOff(actor)
newaction.get_off_from = event.exit_from
raise DoInstead(newaction, suppr... | [
"def before_GettingOff_set_get_off_from(event, actor, ctxt) :\n if not event.get_off_from :\n event.get_off_from = ctxt.world[Location(actor)]\n if ctxt.world[IsA(event.get_off_from, \"container\")] :\n newaction = Exiting(actor)\n newaction.exit_from = event.get_off_from\n raise D... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the actor is just in a room, then it gets converted to going out. | def before_Exiting_needs_not_be_room(event, actor, ctxt) :
if ctxt.world[IsA(event.exit_from, "room")] :
raise DoInstead(Going(actor, "out")) | [
"def enterRoom(self):\n # put tile if there isn't one\n if not self.hasTile():\n self.putTile()\n # get this rooms mob depending on certain circumstances\n self.mob = self.getMob()",
"def other_side_from(self, room):\n return self.rooms[room.room_number]",
"def play... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If we are exiting a closed container, try to open it first. | def before_Exiting_open_container(event, actor, ctxt) :
if ctxt.world[IsA(event.exit_from, "container")] :
if ctxt.world[Openable(event.exit_from)] and not ctxt.world[IsOpen(event.exit_from)] :
ctxt.actionsystem.do_first(Opening(actor, event.exit_from), ctxt, silently=True)
if not ct... | [
"def _check_container(self):\n if self._container is None:\n self._create_container()\n\n try:\n self._container.reload()\n except docker.errors.NotFound:\n logger.warning(\"Container cannot be found, creating a new one.\")\n self._create_container()\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the event.get_off_from attribute if it's not already set. If we're getting off a container, then instead do Exiting. | def before_GettingOff_set_get_off_from(event, actor, ctxt) :
if not event.get_off_from :
event.get_off_from = ctxt.world[Location(actor)]
if ctxt.world[IsA(event.get_off_from, "container")] :
newaction = Exiting(actor)
newaction.exit_from = event.get_off_from
raise DoInstead(newa... | [
"def before_Exiting_set_exit_from(event, actor, ctxt) :\n if not event.exit_from :\n event.exit_from = ctxt.world[Location(actor)]\n if ctxt.world[IsA(event.exit_from, \"supporter\")] :\n newaction = GettingOff(actor)\n newaction.get_off_from = event.exit_from\n raise DoInstead(new... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fails trying to get off a non supporter or a room. | def before_GettingOff_non_supporter(event, actor, ctxt) :
if ctxt.world[IsA(event.get_off_from, "room")] :
raise AbortAction("There's nothing to get off.", actor=actor)
if not ctxt.world[IsA(event.get_off_from, "supporter")] :
raise AbortAction(str_with_objs("{Bob|cap} can't get off of [the $z].... | [
"def before_Exiting_needs_not_be_room(event, actor, ctxt) :\n if ctxt.world[IsA(event.exit_from, \"room\")] :\n raise DoInstead(Going(actor, \"out\"))",
"def test_for_room_avaialble(self):\n\t\tself.assertIs(self.office.is_filled(),False)",
"def test_fight_until_player_dead(self):\n # TODO: imp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Just checks that the actor is on the x, and then redirects to GettingOff. | def before_GettingOffParticular_needs_to_be_on_x(actor, x, ctxt) :
if x != ctxt.world[Location(actor)] :
raise AbortAction(str_with_objs("{Bob|cap} {is} not on [the $x].", x=x), actor=actor)
raise DoInstead(GettingOff(actor), suppress_message=True) | [
"def before_askingto_check_willing(actor, x, y, ctxt) :\n y.update_actor(x)\n ctxt.activity.npc_is_willing(actor, y)",
"def before_GettingOff_set_get_off_from(event, actor, ctxt) :\n if not event.get_off_from :\n event.get_off_from = ctxt.world[Location(actor)]\n if ctxt.world[IsA(event.get_off... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One can't place something into a closed container. | def before_InsertingInto_closed_container(actor, x, y, ctxt) :
ctxt.actionsystem.do_first(Opening(actor, y), ctxt=ctxt)
if not ctxt.world[IsOpen(y)] :
raise AbortAction(str_with_objs("[The $y] is closed.", y=y)) | [
"def test_putClosedFails(self):\n self.containerContainer.closed = True\n self._test(\n \"put foo in bar\",\n [\"The bar is closed.\"])\n self.assertEquals(list(self.containerContainer.getContents()), [])\n self.assertIdentical(self.object.location, self.player)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One can only insert things into a container. | def before_InsertingInto_needs_container(actor, x, y, ctxt) :
raise AbortAction(str_with_objs("{Bob|cap} can't put [the $x] into [the $y].", x=x, y=y), actor=actor) | [
"def _inserted(self, container):\n pass",
"def insert(self, thing):\n\n d = self.ensure_driver(thing,\n \"Can only insert an Entity or a Driver. \"\n \"Tried to insert %s.\" % str(type(thing)))\n\n if d in self:\n raise Po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rewrite PlacingOn as InsertingInto for containers. | def before_PlacingOn_rewrite_container(actor, x, y, ctxt) :
raise DoInstead(InsertingInto(actor, x, y)) | [
"def _inserted(self, container):\n pass",
"def replace(self,after):\n self.insert_after(after)\n self.pop()",
"def ModifyContainer(self, container):",
"def before_InsertingInto_needs_container(actor, x, y, ctxt) :\n raise AbortAction(str_with_objs(\"{Bob|cap} can't put [the $x] into [the $y].\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One can't lock with the wrong key. | def before_locking_locked(actor, x, y, ctxt) :
raise AbortAction(ctxt.world[WrongKeyMessages(x, y)], actor=actor) | [
"def has_lock_permission(self, caller):\n if caller and not caller.check_permstring(\"builders\") and not self.access(caller, 'usekey'):\n caller.msg(\"You do not have a key to %s.\" % self)\n return False\n return True",
"def test_key_override(self):\n new_mutex = Redis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes the actor wear the wearable. | def when_wearing_default(actor, x, ctxt) :
ctxt.world.activity.make_wear(actor, x) | [
"def become_warrior(self):\n\n self.isalover = False\n self.hungry += 110\n self.wanderlust = 0",
"def arm_away(self):\n self.armable.arm(ArmType.AWAY)",
"def eat(self, amount):\n self.__weight += amount",
"def arm_stay(self):\n self.armable.arm(ArmType.STAY)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
That which isn't switchable can't be switched on. | def before_switching_on_unswitchable(actor, x, ctxt) :
raise AbortAction(ctxt.world[NoSwitchMessages(x, "no_switch_on")], actor=actor) | [
"def before_switching_unswitchable(actor, x, ctxt) :\n raise AbortAction(ctxt.world[NoSwitchMessages(x, \"no_switch\")], actor=actor)",
"def susceptible(self):\r\n self.state = NodeState.SUSCEPTIBLE",
"def cantchange(self):\n return self.level == SLC_CANTCHANGE",
"def state_coaccesible(self,s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
That which isn't switchable can't be switched. | def before_switching_unswitchable(actor, x, ctxt) :
raise AbortAction(ctxt.world[NoSwitchMessages(x, "no_switch")], actor=actor) | [
"def before_switching_on_unswitchable(actor, x, ctxt) :\n raise AbortAction(ctxt.world[NoSwitchMessages(x, \"no_switch_on\")], actor=actor)",
"def switch(self, state):\n if state.name in self.allowed:\n print('Current:',self,' => switched to new state',state.name) \n self._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the actor for y to x and then verifies that action. | def verify_askingto_by_verify_y(actor, x, y, ctxt) :
y.update_actor(x)
return ctxt.actionsystem.verify_action(y, ctxt) | [
"def when_askingto_make_it_happen(actor, x, y, ctxt) :\n y.update_actor(x)\n ctxt.actionsystem.run_action(y, ctxt)",
"def before_askingto_check_willing(actor, x, y, ctxt) :\n y.update_actor(x)\n ctxt.activity.npc_is_willing(actor, y)",
"def beam_affects(self, x, y):\n # print(x, y)\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the askee is willing to do the action by calling the actor activity 'npc_is_willing'. | def before_askingto_check_willing(actor, x, y, ctxt) :
y.update_actor(x)
ctxt.activity.npc_is_willing(actor, y) | [
"def checkGoalState(self): \n #check if the place is AI Lab\n return self.place == \"AI Lab\"",
"def check_status(self):\n print(\"Yamcha: Let go!\")\n print(\"Piccolo: It's over\")\n print(\"*Loud explosion*\")\n self.is_dead = True",
"def before_giving_to_person_npc_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes the actor x do the action. | def when_askingto_make_it_happen(actor, x, y, ctxt) :
y.update_actor(x)
ctxt.actionsystem.run_action(y, ctxt) | [
"def doAction(self, action: 'SoAction') -> \"void\":\n return _coin.SoMaterial_doAction(self, action)",
"def doAction(self, action: 'SoAction') -> \"void\":\n return _coin.SoVRMLParent_doAction(self, action)",
"def doAction(self, action: 'SoAction') -> \"void\":\n return _coin.SoNormal_doAc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether the NPC is wanting the object from the actor using the npc_is_wanting activity. | def before_giving_to_person_npc_is_wanting(actor, x, y, ctxt) :
ctxt.activity.npc_is_wanting(actor, x, y) | [
"def before_askingto_check_willing(actor, x, y, ctxt) :\n y.update_actor(x)\n ctxt.activity.npc_is_willing(actor, y)",
"def isGenuine(self):\n actor = self.getMsgDict().get(\"actor\")\n return actor == self.actor",
"def on_target(agent):\n\n if agent.ship.position == agent.target.position... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gives the default message for eating. | def report_eating_default(actor, x, ctxt) :
ctxt.write(str_with_objs("{Bob} {eats} [the $x].", x=x), actor=actor) | [
"def default_message():\n return Message()",
"def format_message(self, op_name) -> str: # type: ignore[override]\n return self.message_default_template.format(op_name=op_name)",
"def __defaultMessageFunc(self, msg):\n self.SetMessage(msg)",
"def default_emoji():\n default_emojis = [':cale... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
By default, you can't swim in anything. | def before_swimming_in_default(actor, x, ctxt) :
raise AbortAction("{Bob|cap} can't swim in that.", actor=actor) | [
"def fly():\n raise Exception('I cannot fly by myself')",
"def minimizeApp():\n pass",
"def startup_once():\n # detect_screens(qtile)\n execute(\"urxvtd -q -o -f\")\n execute(\"compton\")\n execute(\"nm-applet\")\n execute(\"xautolock -time 5 -locker slock \"\n \"-notify 30 -... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
By default, you can't climb. | def before_climbing_default(actor, x, ctxt) :
raise AbortAction(str_with_objs("{Bob|cap} can't climb [the $x].", x=x), actor=actor) | [
"def climb(self, itemToClimb): \n tile = itemToClimb.getTile() \n if tile.getDepth() <= MAX_DEPTH and tile.stepOn():\n self.setDestination(itemToClimb.getPosition())\n self.setUnselectedItem()\n else:\n self.newChatMessage(\"No puedo subirme ahí\", 1)",
"def cut(other):\n if other... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode an initialize mint token instruction and retrieve the instruction params. | def decode_initialize_mint(instruction: TransactionInstruction) -> InitializeMintParams:
parsed_data = __parse_and_validate_instruction(instruction, 2, InstructionType.INITIALIZE_MINT)
return InitializeMintParams(
decimals=parsed_data.args.decimals,
program_id=instruction.program_id,
min... | [
"def decode_initialize_account(instruction: TransactionInstruction) -> InitializeAccountParams:\n _ = __parse_and_validate_instruction(instruction, 4, InstructionType.INITIALIZE_ACCOUNT)\n return InitializeAccountParams(\n program_id=instruction.program_id,\n account=instruction.keys[0].pubkey,\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode an initialize account token instruction and retrieve the instruction params. | def decode_initialize_account(instruction: TransactionInstruction) -> InitializeAccountParams:
_ = __parse_and_validate_instruction(instruction, 4, InstructionType.INITIALIZE_ACCOUNT)
return InitializeAccountParams(
program_id=instruction.program_id,
account=instruction.keys[0].pubkey,
m... | [
"def initialize_account(params: InitializeAccountParams) -> TransactionInstruction:\n data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.INITIALIZE_ACCOUNT, args=None))\n return TransactionInstruction(\n keys=[\n AccountMeta(pubkey=params.account, is_signer=False, is_writ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode an initialize multisig account token instruction and retrieve the instruction params. | def decode_initialize_multisig(instruction: TransactionInstruction) -> InitializeMultisigParams:
parsed_data = __parse_and_validate_instruction(instruction, 2, InstructionType.INITIALIZE_MULTISIG)
num_signers = parsed_data.args.m
validate_instruction_keys(instruction, 2 + num_signers)
return InitializeM... | [
"def decode_initialize_account(instruction: TransactionInstruction) -> InitializeAccountParams:\n _ = __parse_and_validate_instruction(instruction, 4, InstructionType.INITIALIZE_ACCOUNT)\n return InitializeAccountParams(\n program_id=instruction.program_id,\n account=instruction.keys[0].pubkey,\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a transfer token transaction and retrieve the instruction params. | def decode_transfer(instruction: TransactionInstruction) -> TransferParams:
parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.TRANSFER)
return TransferParams(
program_id=instruction.program_id,
source=instruction.keys[0].pubkey,
dest=instruction.keys[1].pubke... | [
"def decode_mint_to(instruction: TransactionInstruction) -> MintToParams:\n parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.MINT_TO)\n return MintToParams(\n program_id=instruction.program_id,\n amount=parsed_data.args.amount,\n mint=instruction.keys[0].pubk... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a approve token transaction and retrieve the instruction params. | def decode_approve(instruction: TransactionInstruction) -> ApproveParams:
parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.APPROVE)
return ApproveParams(
program_id=instruction.program_id,
source=instruction.keys[0].pubkey,
delegate=instruction.keys[1].pubke... | [
"def decode_approve_checked(instruction: TransactionInstruction) -> ApproveCheckedParams:\n parsed_data = __parse_and_validate_instruction(instruction, 4, InstructionType.APPROVE2)\n return ApproveCheckedParams(\n program_id=instruction.program_id,\n amount=parsed_data.args.amount,\n deci... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a revoke token transaction and retrieve the instruction params. | def decode_revoke(instruction: TransactionInstruction) -> RevokeParams:
_ = __parse_and_validate_instruction(instruction, 2, InstructionType.REVOKE)
return RevokeParams(
program_id=instruction.program_id,
account=instruction.keys[0].pubkey,
owner=instruction.keys[1].pubkey,
signe... | [
"def decode_approve(instruction: TransactionInstruction) -> ApproveParams:\n parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.APPROVE)\n return ApproveParams(\n program_id=instruction.program_id,\n source=instruction.keys[0].pubkey,\n delegate=instruction.key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a set authority token transaction and retrieve the instruction params. | def decode_set_authority(instruction: TransactionInstruction) -> SetAuthorityParams:
parsed_data = __parse_and_validate_instruction(instruction, 2, InstructionType.SET_AUTHORITY)
return SetAuthorityParams(
program_id=instruction.program_id,
account=instruction.keys[0].pubkey,
authority=A... | [
"def decode_mint_to(instruction: TransactionInstruction) -> MintToParams:\n parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.MINT_TO)\n return MintToParams(\n program_id=instruction.program_id,\n amount=parsed_data.args.amount,\n mint=instruction.keys[0].pubk... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a mint to token transaction and retrieve the instruction params. | def decode_mint_to(instruction: TransactionInstruction) -> MintToParams:
parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.MINT_TO)
return MintToParams(
program_id=instruction.program_id,
amount=parsed_data.args.amount,
mint=instruction.keys[0].pubkey,
... | [
"def decode_initialize_mint(instruction: TransactionInstruction) -> InitializeMintParams:\n parsed_data = __parse_and_validate_instruction(instruction, 2, InstructionType.INITIALIZE_MINT)\n return InitializeMintParams(\n decimals=parsed_data.args.decimals,\n program_id=instruction.program_id,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a burn token transaction and retrieve the instruction params. | def decode_burn(instruction: TransactionInstruction) -> BurnParams:
parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.BURN)
return BurnParams(
program_id=instruction.program_id,
amount=parsed_data.args.amount,
account=instruction.keys[0].pubkey,
mint=... | [
"def decode_transfer(instruction: TransactionInstruction) -> TransferParams:\n parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.TRANSFER)\n return TransferParams(\n program_id=instruction.program_id,\n source=instruction.keys[0].pubkey,\n dest=instruction.key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a close account token transaction and retrieve the instruction params. | def decode_close_account(instruction: TransactionInstruction) -> CloseAccountParams:
_ = __parse_and_validate_instruction(instruction, 3, InstructionType.CLOSE_ACCOUNT)
return CloseAccountParams(
program_id=instruction.program_id,
account=instruction.keys[0].pubkey,
dest=instruction.keys... | [
"def close_account(params: CloseAccountParams) -> TransactionInstruction:\n data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.CLOSE_ACCOUNT, args=None))\n keys = [\n AccountMeta(pubkey=params.account, is_signer=False, is_writable=True),\n AccountMeta(pubkey=params.dest, is_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a freeze account token transaction and retrieve the instruction params. | def decode_freeze_account(instruction: TransactionInstruction) -> FreezeAccountParams:
_ = __parse_and_validate_instruction(instruction, 3, InstructionType.FREEZE_ACCOUNT)
return FreezeAccountParams(
program_id=instruction.program_id,
account=instruction.keys[0].pubkey,
mint=instruction.... | [
"def decode_thaw_account(instruction: TransactionInstruction) -> ThawAccountParams:\n _ = __parse_and_validate_instruction(instruction, 3, InstructionType.THAW_ACCOUNT)\n return ThawAccountParams(\n program_id=instruction.program_id,\n account=instruction.keys[0].pubkey,\n mint=instructio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a thaw account token transaction and retrieve the instruction params. | def decode_thaw_account(instruction: TransactionInstruction) -> ThawAccountParams:
_ = __parse_and_validate_instruction(instruction, 3, InstructionType.THAW_ACCOUNT)
return ThawAccountParams(
program_id=instruction.program_id,
account=instruction.keys[0].pubkey,
mint=instruction.keys[1].... | [
"def decode_mint_to(instruction: TransactionInstruction) -> MintToParams:\n parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.MINT_TO)\n return MintToParams(\n program_id=instruction.program_id,\n amount=parsed_data.args.amount,\n mint=instruction.keys[0].pubk... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a transfer_checked token transaction and retrieve the instruction params. | def decode_transfer_checked(instruction: TransactionInstruction) -> TransferCheckedParams:
parsed_data = __parse_and_validate_instruction(instruction, 4, InstructionType.TRANSFER2)
return TransferCheckedParams(
program_id=instruction.program_id,
amount=parsed_data.args.amount,
decimals=p... | [
"def decode_transfer(instruction: TransactionInstruction) -> TransferParams:\n parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.TRANSFER)\n return TransferParams(\n program_id=instruction.program_id,\n source=instruction.keys[0].pubkey,\n dest=instruction.key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a approve_checked token transaction and retrieve the instruction params. | def decode_approve_checked(instruction: TransactionInstruction) -> ApproveCheckedParams:
parsed_data = __parse_and_validate_instruction(instruction, 4, InstructionType.APPROVE2)
return ApproveCheckedParams(
program_id=instruction.program_id,
amount=parsed_data.args.amount,
decimals=parse... | [
"def decode_approve(instruction: TransactionInstruction) -> ApproveParams:\n parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.APPROVE)\n return ApproveParams(\n program_id=instruction.program_id,\n source=instruction.keys[0].pubkey,\n delegate=instruction.key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a mintTo2 token transaction and retrieve the instruction params. | def decode_mint_to_checked(instruction: TransactionInstruction) -> MintToCheckedParams:
parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.MINT_TO2)
return MintToCheckedParams(
program_id=instruction.program_id,
amount=parsed_data.args.amount,
decimals=parsed_... | [
"def decode_mint_to(instruction: TransactionInstruction) -> MintToParams:\n parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.MINT_TO)\n return MintToParams(\n program_id=instruction.program_id,\n amount=parsed_data.args.amount,\n mint=instruction.keys[0].pubk... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a burn_checked token transaction and retrieve the instruction params. | def decode_burn_checked(instruction: TransactionInstruction) -> BurnCheckedParams:
parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.BURN2)
return BurnCheckedParams(
program_id=instruction.program_id,
amount=parsed_data.args.amount,
decimals=parsed_data.args.... | [
"def decode_mint_to_checked(instruction: TransactionInstruction) -> MintToCheckedParams:\n parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.MINT_TO2)\n return MintToCheckedParams(\n program_id=instruction.program_id,\n amount=parsed_data.args.amount,\n decima... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction to initialize a new mint newly. This instruction requires no signers and MUST be included within the same Transaction as the system program's `CreateInstruction` that creates the account being initialized. Otherwise another party can acquire ownership of the uninitialized account. | def initialize_mint(params: InitializeMintParams) -> TransactionInstruction: # noqa: E501 # pylint: disable=line-too-long
freeze_authority, opt = (params.freeze_authority, 1) if params.freeze_authority else (PublicKey(0), 0)
data = INSTRUCTIONS_LAYOUT.build(
dict(
instruction_type=Instructi... | [
"def initialize_account(params: InitializeAccountParams) -> TransactionInstruction:\n data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.INITIALIZE_ACCOUNT, args=None))\n return TransactionInstruction(\n keys=[\n AccountMeta(pubkey=params.account, is_signer=False, is_writ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction to initialize a new account to hold tokens. This instruction requires no signers and MUST be included within the same Transaction as the system program's `CreateInstruction` that creates the account being initialized. Otherwise another party can acquire ownership of the uninitialized a... | def initialize_account(params: InitializeAccountParams) -> TransactionInstruction:
data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.INITIALIZE_ACCOUNT, args=None))
return TransactionInstruction(
keys=[
AccountMeta(pubkey=params.account, is_signer=False, is_writable=True... | [
"def decode_initialize_account(instruction: TransactionInstruction) -> InitializeAccountParams:\n _ = __parse_and_validate_instruction(instruction, 4, InstructionType.INITIALIZE_ACCOUNT)\n return InitializeAccountParams(\n program_id=instruction.program_id,\n account=instruction.keys[0].pubkey,\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction to initialize a multisignature account with N provided signers. This instruction requires no signers and MUST be included within the same Transaction as the system program's `CreateInstruction` that creates the account being initialized. Otherwise another party can acquire ownership of... | def initialize_multisig(params: InitializeMultisigParams) -> TransactionInstruction:
data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.INITIALIZE_MULTISIG, args=dict(m=params.m)))
keys = [
AccountMeta(pubkey=params.multisig, is_signer=False, is_writable=True),
AccountMeta(pu... | [
"def initialize_account(params: InitializeAccountParams) -> TransactionInstruction:\n data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.INITIALIZE_ACCOUNT, args=None))\n return TransactionInstruction(\n keys=[\n AccountMeta(pubkey=params.account, is_signer=False, is_writ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction to transfers tokens from one account to another. Either directly or via a delegate. | def transfer(params: TransferParams) -> TransactionInstruction:
data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.TRANSFER, args=dict(amount=params.amount)))
keys = [
AccountMeta(pubkey=params.source, is_signer=False, is_writable=True),
AccountMeta(pubkey=params.dest, is_sig... | [
"def create_associated_token_account(payer: PublicKey, owner: PublicKey, mint: PublicKey) -> TransactionInstruction:\n associated_token_address = get_associated_token_address(owner, mint)\n return TransactionInstruction(\n keys=[\n AccountMeta(pubkey=payer, is_signer=True, is_writable=True),... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction to approve a delegate. | def approve(params: ApproveParams) -> TransactionInstruction:
data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.APPROVE, args=dict(amount=params.amount)))
keys = [
AccountMeta(pubkey=params.source, is_signer=False, is_writable=True),
AccountMeta(pubkey=params.delegate, is_si... | [
"def approve(owner, spender, tokenId, amount):\n assert (_whenNotPaused())\n # make sure the invoker is the owner address\n assert (CheckWitness(owner))\n # make sure the address is legal\n assert (len(spender) == 20)\n assert (_tokenExist(tokenId))\n\n ownerBalance = balanceOf(owner, tokenId)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction that revokes delegate authority for a given account. | def revoke(params: RevokeParams) -> TransactionInstruction:
data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.REVOKE, args=None))
keys = [AccountMeta(pubkey=params.account, is_signer=False, is_writable=True)]
__add_signers(keys, params.owner, params.signers)
return TransactionInstr... | [
"def close_account(params: CloseAccountParams) -> TransactionInstruction:\n data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.CLOSE_ACCOUNT, args=None))\n keys = [\n AccountMeta(pubkey=params.account, is_signer=False, is_writable=True),\n AccountMeta(pubkey=params.dest, is_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction to sets a new authority of a mint or account. | def set_authority(params: SetAuthorityParams) -> TransactionInstruction:
new_authority, opt = (params.new_authority, 1) if params.new_authority else (PublicKey(0), 0)
data = INSTRUCTIONS_LAYOUT.build(
dict(
instruction_type=InstructionType.SET_AUTHORITY,
args=dict(authority_type=... | [
"def create_associated_token_account(payer: PublicKey, owner: PublicKey, mint: PublicKey) -> TransactionInstruction:\n associated_token_address = get_associated_token_address(owner, mint)\n return TransactionInstruction(\n keys=[\n AccountMeta(pubkey=payer, is_signer=True, is_writable=True),... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction to close an account by transferring all its SOL to the destination account. Nonnative accounts may only be closed if its token amount is zero. | def close_account(params: CloseAccountParams) -> TransactionInstruction:
data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.CLOSE_ACCOUNT, args=None))
keys = [
AccountMeta(pubkey=params.account, is_signer=False, is_writable=True),
AccountMeta(pubkey=params.dest, is_signer=Fal... | [
"def decode_close_account(instruction: TransactionInstruction) -> CloseAccountParams:\n _ = __parse_and_validate_instruction(instruction, 3, InstructionType.CLOSE_ACCOUNT)\n return CloseAccountParams(\n program_id=instruction.program_id,\n account=instruction.keys[0].pubkey,\n dest=instru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction to freeze an initialized account using the mint's freeze_authority (if set). | def freeze_account(params: FreezeAccountParams) -> TransactionInstruction:
return __freeze_or_thaw_instruction(params, InstructionType.FREEZE_ACCOUNT) | [
"def decode_freeze_account(instruction: TransactionInstruction) -> FreezeAccountParams:\n _ = __parse_and_validate_instruction(instruction, 3, InstructionType.FREEZE_ACCOUNT)\n return FreezeAccountParams(\n program_id=instruction.program_id,\n account=instruction.keys[0].pubkey,\n mint=in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction to thaw a frozen account using the Mint's freeze_authority (if set). | def thaw_account(params: ThawAccountParams) -> TransactionInstruction:
return __freeze_or_thaw_instruction(params, InstructionType.THAW_ACCOUNT) | [
"def freeze_account(params: FreezeAccountParams) -> TransactionInstruction:\n return __freeze_or_thaw_instruction(params, InstructionType.FREEZE_ACCOUNT)",
"def decode_freeze_account(instruction: TransactionInstruction) -> FreezeAccountParams:\n _ = __parse_and_validate_instruction(instruction, 3, Instructi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Derives the associated token address for the given wallet address and token mint. | def get_associated_token_address(owner: PublicKey, mint: PublicKey) -> PublicKey:
key, _ = PublicKey.find_program_address(
seeds=[bytes(owner), bytes(TOKEN_PROGRAM_ID), bytes(mint)], program_id=ASSOCIATED_TOKEN_PROGRAM_ID
)
return key | [
"def tokenAddress() -> address:\n return self.token",
"def get_address(self, address: str) -> Address:",
"def create_associated_token_account(payer: PublicKey, owner: PublicKey, mint: PublicKey) -> TransactionInstruction:\n associated_token_address = get_associated_token_address(owner, mint)\n return T... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a transaction instruction to create an associated token account. | def create_associated_token_account(payer: PublicKey, owner: PublicKey, mint: PublicKey) -> TransactionInstruction:
associated_token_address = get_associated_token_address(owner, mint)
return TransactionInstruction(
keys=[
AccountMeta(pubkey=payer, is_signer=True, is_writable=True),
... | [
"def create_account(name):\n return wallet['obj'].create_account(name)",
"def initialize_account(params: InitializeAccountParams) -> TransactionInstruction:\n data = INSTRUCTIONS_LAYOUT.build(dict(instruction_type=InstructionType.INITIALIZE_ACCOUNT, args=None))\n return TransactionInstruction(\n k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a string with an opening curly brace, this method finds the substring up to the matching closing curly brace. | def get_text_through_matching_brace(text):
if not text:
return ''
if text[0] == '{':
# Find the matching closing brace.
count = 0
r_index = 0
for i in xrange(len(text)):
char = text[i]
if char == '{':
count += 1
elif cha... | [
"def find_closing_curly(self, s):\n\t\t#logging.debug('s: %s', s)\n\t\tlevels=1\n\t\ti=1\n\t\tlen_s = len(s)\n\t\twhile(levels>0 and i<len_s):\n\t\t\tif s[i]=='{':\n\t\t\t\tlevels+=1\n\t\t\telif s[i]=='}':\n\t\t\t\tlevels-=1\n\t\t\ti+=1\n\t\t#logging.debug('i: %d', i)\n\t\treturn i",
"def get_curly_brace_scope_en... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a string and finds the smallest possible complete KExpression beginning with the first character. | def get_smallest_kexp_from_string(text):
if not text.strip():
# Ensure that we don't throw an error if the text is blank.
return ""
if text[0] == "'" and text[1] == '{':
# Find the shortest matching brace expression starting after the
# quote mark.
return "'" + get_text_t... | [
"def test_returns_first_recurring_char_short_string(self):\n result = find_first_recurring_char(\"abcdagtf\")\n self.assertEqual(result, \"a\")",
"def test_returns_first_recurring_char_long_string(self):\n result = find_first_recurring_char(\"abcdefghijkajcdbeadbe\")\n self.assertEqual... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the number of "absolute" symbols in a list of symbols. This is just the number of symbols that aren't REPEAT. | def absolute_symbol_count(symbols):
return len([symbol for symbol in symbols if symbol != REPEAT]) | [
"def num_symbols(self):\r\n return self['sh_size'] // self['sh_entsize']",
"def symbol_count (self):\n \n raise NotImplementedError",
"def max_symbols (self):\n \n raise NotImplementedError",
"def num_specials(self):\n return len(self.special_symbols)",
"def n_neg(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compares an expression text to the speciallyformatted symbolic_text to determine whether they are equivalent. | def kexp_match(symbolic_text, literal_text):
if not symbolic_text or not literal_text:
return symbolic_text == literal_text
# Check if the symbolic text starts with a brace..
if symbolic_text[0] == '{':
# If it does, convert the strings to kexps.
try:
symbols = kexp_to_l... | [
"def equivalent(self, expr):\n expr = parse(expr)\n return Biconditional(self, expr).is_tautology()",
"def inequal_symbols(a: Union[sympy.Expr, Any], b: Union[sympy.Expr, Any]) -> bool:\n if not isinstance(a, sympy.Expr) or not isinstance(b, sympy.Expr):\n return a != b\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a KExpression, converts its interior into a list of KExpressions. This is useful for parsing things. | def kexp_to_list(kexp):
if kexp[0] != '{' or kexp[-1] != '}':
raise ParseException("kexp_to_list: not a list: {}".format(kexp))
kexp = kexp[1:-1]
return string_to_kexp_strings(kexp) | [
"def __split_to_elements(self, math_expr: str) -> list:\n regex_of_element = r'\\d*\\.\\d+|\\d+|[' + \"\".join(self.__operations) + \"]|[\" + \"\".join([self.__open_parenthesis,\n self.__close_parenthesis]) + \"]\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
insert content by username | def insert_content_by_username(self, username, title, content, tag):
try:
userid = self.cursor.execute('SELECT id FROM user WHERE name=?',
(username, )).fetchone()
count = self.cursor.execute('SELECT COUNT(*) FROM user_content').fetchone()
rows = count[0]
... | [
"def add_user_post(uname, content):\n if valid_post_params(uname, content):\n p = UserPost(author_username=uname, content=content)\n db.session.add(p)\n db.session.commit()\n return p\n return None",
"def createContent(self, entry):\n uri = \"/content/\" + self.username + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get content list of user by username | def get_content_by_username(self, name):
list = []
userid = self.cursor.execute(
'SELECT id FROM user WHERE name=?', (name, )).fetchone()
id = self.cursor.execute(
'SELECT id FROM user_content WHERE userid=?', userid).fetchall()
for item in id:
if item... | [
"def listUsers():\n exec_get_all('SELECT username FROM users')",
"async def listall(self, ctx, user:discord.User=None):\n\n async with self.bot.database() as db:\n if user is not None:\n full = await db(\"SELECT * FROM keywords WHERE userid = $1;\", user.id)\n else:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns and clears the list of collected errors in ErrorCollector. The RetrieveCollectedErrors function in C++ returns a list of serialized proto messages. This function will convert them to ConverterErrorData instances. | def retrieve_collected_errors():
serialized_message_list = wrap_toco.wrapped_retrieve_collected_errors()
return list(
map(converter_error_data_pb2.ConverterErrorData.FromString,
serialized_message_list)) | [
"def get_all_errs(self):\n thiserr = self.get_err()\n errors = []\n while thiserr != '+0,\"No error\"':\n thiserr = self.get_err()\n errors.append(thiserr)\n return errors",
"def get_validation_errors(self):\n errors = []\n try:\n self.xsd_validate()\n except ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to calculate date for Monday of first week of year >>> monday_of_week_one(1970) datetime.date(1969, 12, 29) | def monday_of_week_one(yyyy):
ref_day = date(yyyy, 1, 4)
dow = ref_day.weekday()
monday = ref_day - timedelta(days=dow)
return monday | [
"def next_monday(date):\n if date.weekday():\n one_day = datetime.timedelta(days=1)\n return date + ((7 - date.weekday()) * one_day)\n else:\n return date",
"def for_date(d):\n thursday = d + datetime.timedelta(3 - d.weekday()) # Thursday this week\n first = thursday.repla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View for deleting a firmware build (with confirmation) | def delete_build_view(request, node_id):
node = get_object_or_404(Node, pk=node_id)
build = get_object_or_404(Build, node=node)
# Check that the user has delete permission for the actual model
node_modeladmin = get_modeladmin(Node)
if not node_modeladmin.has_change_permission(request, obj=node,... | [
"def delete_file(request):\n\n if request.method == 'POST':\n form = DeleteFirmwareForm(request.POST)\n\n if form.is_valid():\n logger.info(f\"Form {form} is valid\")\n\n # get relevant data\n firmware_file = form.cleaned_data['firmware']\n firmware_file.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load page from target URL or from local file if debug mode is actived The soup global variable will contain the target html page | def _loadPage(targetUrl: str, debugMode: bool = False, localFile: str = 'localpage.html') -> None:
global soup
# Create a temporary directory if needed
tempDir = 'temp'
if not os.path.exists(tempDir):
os.mkdir(tempDir)
localFile = tempDir + "\\" + localFile
if not debugMode or (debugMo... | [
"def openURL(self, url):\n response = requests.get(url)\n self.soup = BeautifulSoup(response.text, 'html.parser')",
"def open_from_url(self, url):\n self.__html = requests.get(url).text",
"def get_page(_driver, _url):\n _driver.get(_url)\n time.sleep(5)\n return BeautifulSoup(_driv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests convert_deps_to_packageinfo_for_depsolver, but uses more complex version strings. | def test_depsolver_conversion2():
(depsolver_deps, dists_unable_to_convert) = \
depsolver_integrate.convert_packs_to_packageinfo_for_depsolver(
DEPS_EDGE_CASES)
logger.info('Product of DEPS_EDGE_CASES conversion:\n' + str(depsolver_deps))
assert len(dists_unable_to_convert) == 0
logger.info("test... | [
"def test_depsolver_conversion3():\n (depsolver_deps, dists_unable_to_convert) = \\\n depsolver_integrate.convert_packs_to_packageinfo_for_depsolver(\n testdata.DEPS_MODERATE)\n\n logger.info('Product of DEPS_MODERATE conversion:\\n' + str(depsolver_deps))\n\n assert len(dists_unable_to_convert) == 0\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests convert_deps_to_packageinfo_for_depsolver, but uses more complex version strings. | def test_depsolver_conversion3():
(depsolver_deps, dists_unable_to_convert) = \
depsolver_integrate.convert_packs_to_packageinfo_for_depsolver(
testdata.DEPS_MODERATE)
logger.info('Product of DEPS_MODERATE conversion:\n' + str(depsolver_deps))
assert len(dists_unable_to_convert) == 0
logger.info("... | [
"def test_depsolver_conversion2():\n (depsolver_deps, dists_unable_to_convert) = \\\n depsolver_integrate.convert_packs_to_packageinfo_for_depsolver(\n DEPS_EDGE_CASES)\n logger.info('Product of DEPS_EDGE_CASES conversion:\\n' + str(depsolver_deps))\n \n assert len(dists_unable_to_convert) == 0\n log... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get grades using the endpoint specified in uri | def _get_grades(self, uri, params=None):
return self._get_models(Grade, uri, params=self._prepare_params(params)) | [
"def get_course_grades(session, course):\n return get_course_data(session, course, 'GRADES')",
"def get(organisation_id, grade_id):\n grade = Grade.query.get_or_404(str(grade_id))\n\n return Response(repr(grade), mimetype=\"application/json\", status=200)",
"def test_gardens_get(self):\n query_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Download a complete list of final grades for a specified student | def get_final_grades(self, student, params=None):
uri = self.uri_template_final_grade.format(students_pk=student)
return self._get_models(FinalGrade, uri, params=self._prepare_params(params)) | [
"def download_all():\n\n course_id = prompt_for_course_id()\n assignment = prompt_for_assignment(course_id)\n students = get_students(course_id)\n\n for student in sorted(students.items(),\n key=lambda student: student[1]):\n download_submission(course_id, assignment, student[1],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload a final_grade object to the server under the specified student | def add_final_grade(self, final_grade, student):
return self.add_many_final_grades(final_grades=[final_grade], student=student) | [
"def submit_grade():\n\tstudent_github = request.form.get(\"student\")\n\tproject_title = request.form.get(\"title\")\n\tproject_grade = request.form.get(\"grade\")",
"def save(self, student):\n self.connect()\n try:\n sql = \"\"\"insert into {0} values ({1},\"{2}\",\"{3}\",\"{4}\",\"{5}\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload a list of final_grade objects to the server under the specified student | def add_many_final_grades(self, final_grades, student):
uri = self.uri_template_final_grade.format(students_pk=student)
return self._add_many_models(final_grades, uri) | [
"def add_final_grade(self, final_grade, student):\n return self.add_many_final_grades(final_grades=[final_grade], student=student)",
"def get_final_grades(self, student, params=None):\n uri = self.uri_template_final_grade.format(students_pk=student)\n return self._get_models(FinalGrade, uri, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a final_grade object from the server under the specified student | def delete_final_grade(self, final_grade, student):
return self.delete_many_final_grades(final_grades=[final_grade], student=student) | [
"def delete_many_final_grades(self, final_grades, student):\n uri = self.uri_template_final_grade.format(students_pk=student)\n return self._delete_many_models(final_grades, uri)",
"def delStudent(self,st,grades):\r\n if grades==[]:\r\n return st.getID()\r\n if grades[0].get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a list of final_grade objects from the server under the specified student | def delete_many_final_grades(self, final_grades, student):
uri = self.uri_template_final_grade.format(students_pk=student)
return self._delete_many_models(final_grades, uri) | [
"def delete_final_grade(self, final_grade, student):\n return self.delete_many_final_grades(final_grades=[final_grade], student=student)",
"def delStudent(self,st,grades):\r\n if grades==[]:\r\n return st.getID()\r\n if grades[0].getStudent()==st:\r\n self.__listNote.rem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts basic expression to dictionary representation. This procedure will expand given expression and scan it, extracting coefficients and monomials according to a set of symbols, if possible. At this point there is no need for specifying ordering information. If conversion is not possible an exception is raised. Thi... | def _decompose(poly, *symbols):
result, indices, N = {}, {}, len(symbols)
for i, sym in enumerate(symbols):
indices[sym] = i
poly = sympify(poly).expand()
if poly.is_Add:
terms = poly.args
else:
if poly.is_Number:
return { (0... | [
"def parse_equation(equation: str):\n terms = parse_equation_terms(equation)\n\n # Construct standardised and code representations of the equation\n template = re.sub(r'\\s+', ' ', term_re.sub('{}', equation))\n equation = template.format(*[str(t) for t in terms])\n code = template.format(*[t.code fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cancel common factors in a fractional expression. Given a quotient of polynomials, cancel common factors from the numerator and the denominator. The result is formed in an expanded form, even if there was no cancellation. To improve the speed of calculations a list of symbols can be specified. This can be particularly ... | def cancel(f, *symbols):
if type(f) is tuple:
numer, denom = f
else:
if f.is_Atom:
return f
if not symbols:
symbols = f.atoms(Symbol)
if not symbols:
symbols = None
else:
... | [
"def apply_false_cancel(numerator, denominator):\n numerator = list(str(numerator))\n denominator = list(str(denominator))\n\n for char_1 in numerator:\n for char_2 in denominator:\n if char_1 == char_2:\n numerator.remove(char_1)\n denominator.remove(char_2)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return dictionary representation with integer keys. In case of univariate polynomials it is inefficient to to handle exponents as singleton tuples, as an example see multiplication algorithm. This method will return dictionary representation with all tuples converted to explicit integers. >>> from sympy import >>> x,y ... | def as_uv_dict(self):
if self.is_univariate:
return dict(zip([ M[0] for M in self.monoms ], self.coeffs))
else:
raise MultivariatePolyError(self) | [
"def DictOfInts():\n return collections.defaultdict(int)",
"def generate_char_to_int_dict(data: t.List[str]) -> t.Dict[str, int]:\n temp = set(data)\n return {x: i for i, x in enumerate(temp)}",
"def uv_index(self):\n return {(u, v): index for index, (u, v) in enumerate(self.edges_where({'is_edg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns degree of the leading term. | def degree(self):
return sum(self.monoms[0]) | [
"def degree(self):\n return self.defining_polynomial().degree()",
"def relative_degree(self):\n return self.relative_polynomial().degree()",
"def _get_degree(self) -> \"int\" :\n return _core.NurbsCurve2D__get_degree(self)",
"def _get_degree(self) -> \"int\" :\n return _core.NurbsC... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Efficiently multiply sparse and dense polynomials. Given polynomials P and Q, if both of them are dense, then in univariate case perform dense multiplication, otherwise apply Kronecker 'trick', mapping multivariate polynomials to univariate ones in last variable and then multiply. If any of the polynomials is sparse th... | def __mul__(self, other):
try:
self, poly = self.unify_with(other)
except PolynomialError:
return self.as_basic() * other.as_basic()
if self.is_constant:
if self.is_zero:
return self
elif self.is_one:
return poly
... | [
"def _matmul_kronecker_product(self, other, shape_hint):\n return KroneckerProduct([xi @ yi for xi, yi in zip(self.x, other.x)])",
"def internal_product_on_basis(self, I, J):",
"def test_mul_funcs(self):\r\n n = 10\r\n x = Variable(n)\r\n obj = Minimize(norm(x, 1))\r\n constra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if 'self' is dense. Let 'self' be a polynomial in M variables of a total degree N and having L terms (with nonzero coefficients). Let K be the number of monomials in M variables of degree at most N. Then 'self' is considered dense if it's at least 90% filled. The total number of monomials is given by (M + ... | def is_dense(self):
def enum(M, N):
U = float(M+N)
V = (6*M+1)*(6*N+1)
S = 2.4*math.sqrt(U/V)
A = math.pow(U/M, M)
B = math.pow(U/N, N)
return S * A * B
V, N = len(self.symbols), self.total_degree
return (self.length / enu... | [
"def is_reducible(ptn, k):\n rect_dim_list = k_rectangle_dimension_list(\n k) + k_rectangle_dimension_list(k-1)\n for (a, b) in rect_dim_list:\n if is_k_reducible_by_rectangle(ptn, k, (a, b)):\n return True\n return False",
"def poles ( self ) :\n N = len ( self )\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if 'self' has no factors of multiplicity >= 2. >>> from sympy import >>> x,y = symbols('xy') >>> Poly(x1, x).is_squarefree True >>> Poly((x1)2, x).is_squarefree False | def is_squarefree(self):
return self.as_squarefree() is self | [
"def is_square_free(value):\n if isinstance(value, (int, np.integer)):\n return int_is_square_free(value)\n if isinstance(value, Poly):\n return value.is_square_free()\n raise TypeError(f\"Argument 'value' must be either int or Poly, not {type(value)}.\")",
"def is_square(self) -> bool:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a monic polynomial. >>> from sympy import >>> x,y = symbols('xy') >>> Poly(x2 + 4, x).as_monic() Poly(x2 + 4, x) >>> Poly(2x2 + 4, x).as_monic() Poly(x2 + 2, x) >>> Poly(yx2 + y2 + y, x).as_monic() Poly(x2 + 1 + y, x) | def as_monic(self):
LC = self.lead_coeff
if not self or LC is S.One:
return self
coeffs = [ coeff / LC for coeff in self.coeffs ]
for i, coeff in enumerate(coeffs):
coeffs[i] = Poly.cancel(coeff)
return self.__class__((coeffs, self.monoms),
... | [
"def monic(poly):\n assert type(poly) == QPoly\n return poly//poly.coef[-1]",
"def mono_coeff(monomial, x=sym.symbols('x')):\n return sym.sympify(monomial).subs(x, 1)",
"def mulPoly(poly1,poly2):\n if isinstance(poly1,Zero) or isinstance(poly2,Zero):\n return mkZero()\n elif isinstance(pol... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes all coefficients integers if possible. Given a polynomial with rational coefficients, returns a tuple consisting of a common denominator of those coefficients and an integer polynomial. Otherwise an exception is being raised. >>> from sympy import >>> x,y = symbols("xy") >>> Poly(3x2 + x, x).as_integer() (1, Poly... | def as_integer(self):
denom, coeffs = 1, []
for coeff in self.iter_coeffs():
if coeff.is_Rational:
coeffs.append(coeff)
if not coeff.is_Integer:
denom = ilcm(denom, coeff.q)
elif coeff.is_Real and int(coeff) == coeff:
... | [
"def polyInt(p, poly):\n myInt = poly[0]\n for j in range(1, len(poly)):\n myInt = myInt * p + poly[j]\n \n return myInt",
"def inprod(a1, a2, pqr, int_pqr):\n\n coeff = Rational(0)\n b = polymul(a1[:], a2[:], pqr)\n for ii in range(len(b)):\n coeff = coeff + b[ii] * int_pqr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns squarefree part of a polynomial. >>> from sympy import >>> x,y = symbols('xy') >>> Poly((x1)2, x).as_squarefree() Poly(x 1, x) | def as_squarefree(self):
f, A = self, sympy.polys.algorithms
if f.is_univariate:
F = f.as_primitive()[1]
h = f.diff()
g = A.poly_gcd(F, h)
r = A.poly_div(f, g)
return r[0]
else:
raise MultivariatePolyError(f) | [
"def is_squarefree(self):\n return self.as_squarefree() is self",
"def square_tree(t):\n\treturn tree(label(t) ** 2, [square_tree(b) for b in branches(t)])",
"def triangulate(poly):\n poly = closePoly(poly)\n return list(triList(poly,poly2tri(lowerPoly(poly))))",
"def polyToSubdiv(poly, applyMatr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove GCD of monomials from 'self'. >>> from sympy import >>> x,y = symbols('xy') >>> Poly(x3 + x, x).as_reduced() ((1,), Poly(x2 + 1, x)) >>> Poly(x3y+x2y2, x, y).as_reduced() ((2, 1), Poly(x + y, x, y)) | def as_reduced(self):
if self.is_inhomogeneous:
return (0,)*len(self.symbols), self
else:
if self.is_univariate:
gcd = self.monoms[-1]
terms = self.coeffs, [ (monom - gcd[0],)
for (monom,) in self.monoms ]
else:
... | [
"def monic(poly):\n assert type(poly) == QPoly\n return poly//poly.coef[-1]",
"def _quo_rem_naive(self, right):\n K = self.base_ring().fraction_field()\n f = self.base_extend(K)\n g = right.base_extend(K)\n if g == 0:\n raise ZeroDivisionError(\"cannot divide by a poly... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns coefficient of a particular monomial. >>> from sympy import >>> x,y = symbols('xy') >>> p = Poly(3x2y + 4xy2 + 1, x, y) >>> p.coeff(2, 1) 3 >>> p.coeff(1, 2) 4 >>> p.coeff(1, 1) 0 | def coeff(self, *monom):
if not monom:
if all(e == 0 for e in self.monoms[-1]):
return self.coeffs[-1]
else:
for i in xrange(len(self.monoms)):
if self.monoms[i] == monom:
return self.coeffs[i]
return S.Zero | [
"def mono_coeff(monomial, x=sym.symbols('x')):\n return sym.sympify(monomial).subs(x, 1)",
"def _poly(coefficients, x):\n out = coefficients[0]\n for coefficient in coefficients[1:]:\n out = out * x + coefficient\n return out",
"def get_coeff(expression, model_vars):\n\n # assert(constr.bo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Efficiently differentiate polynomials. Differentiate a polynomial with respect to a set of symbols. If a symbol is polynomial's variable, then monomial differentiation is performed and coefficients updated with integer factors. In other case each of the coefficients is differentiated. Additionally, for each of the symb... | def diff(self, *symbols):
if self.is_zero:
return self
new_symbols = []
for s in symbols:
s = sympify(s)
if s.is_Symbol:
new_symbols.append((s, 1))
elif s.is_Integer:
sym, _ = new_symbols.pop()
new... | [
"def _decompose(poly, *symbols):\n result, indices, N = {}, {}, len(symbols)\n\n for i, sym in enumerate(symbols):\n indices[sym] = i\n\n poly = sympify(poly).expand()\n\n if poly.is_Add:\n terms = poly.args\n else:\n if poly.is_Number:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Efficiently integrate polynomials. Integrate a polynomial with respect a set of symbols. If a symbol is polynomial's variable, then monomial integration is performed and coefficients updated with integer factors. In other case each of the coefficients is integrated. Additionally, for each of the symbols you can specify... | def integrate(self, *symbols):
if self.is_zero:
return self
new_symbols = []
for s in symbols:
s = sympify(s)
if s.is_Symbol:
new_symbols.append((s, 1))
elif s.is_Integer:
sym, _ = new_symbols.pop()
... | [
"def polytope_integrate(poly, expr=None, *, clockwise=False, max_degree=None):\n if clockwise:\n if isinstance(poly, Polygon):\n poly = Polygon(*point_sort(poly.vertices), evaluate=False)\n else:\n raise TypeError(\"clockwise=True works for only 2-Polytope\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Efficiently add a single term to 'self'. The list of monomials is sorted at initialization time, this motivates usage of binary search algorithm to find an index of an existing monomial or a suitable place for a new one. This gives O(lg(n)) complexity, where 'n' is the initial number of terms, superior to naive approac... | def add_term(self, coeff, monom):
if self.is_zero:
coeffs = (coeff,)
monoms = (monom,)
else:
coeffs = list(self.coeffs)
monoms = list(self.monoms)
compare = monomial_cmp(self.order)
if compare(monom, monoms[0]) > 0:
... | [
"def add_term(mytrie, word, weight):\r\n assert isinstance(word, str), \"The word to be added should be a string.\"\r\n assert isinstance(weight, int), \"The weight of the word should be an integer\"\r\n mytrie.insertWord(weight, word)",
"def add(self, word: str):\n current_node = self.root\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Efficiently subtract a single term from 'self'. The list of monomials is sorted at initialization time, this motivates usage of binary search algorithm to find an index of an existing monomial or a suitable place for a new one. This gives O(lg(n)) complexity, where 'n' is the initial number of terms, superior to naive ... | def sub_term(self, coeff, monom):
if self.is_zero:
coeffs = (-coeff,)
monoms = (monom,)
else:
coeffs = list(self.coeffs)
monoms = list(self.monoms)
compare = monomial_cmp(self.order)
if compare(monom, monoms[0]) > 0:
... | [
"def subtraction(self, term):\n\n self.complex_num -= term\n self.grade_exponential()",
"def __sub__(self, other):\n\n if type(other).__name__ is 'AutoDiffVector':\n return self.__add__(other.__neg__())\n\n try:\n total = Counter()\n total.update(self.d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes last term from 'self'. | def kill_last_term(self):
terms = self.coeffs[:-1], self.monoms[:-1]
return self.__class__(terms, *self.symbols, **self.flags) | [
"def removeLast(self):\n\t\tnode = self.head\n\t\twhile(node.after is not self.tail):\n\t\t\tnode = node.after\n\t\tnode.after = None",
"def remove(self):\n for word in self.words:\n word._mwt = None # pylint: disable=W0212\n self.root.multiword_tokens = [tok for tok in self.root.multiwo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compare polynomials up to order of symbols and monomials. | def __eq__(self, other):
try:
poly = self.__class__(other, *self.symbols, **self.flags)
except PolynomialError:
return False
if self.length != poly.length:
return False
if hash(self.monoms) != hash(poly.monoms):
return False
if h... | [
"def compare_monomial(t1, t2):\n return term_ord.fast_compare(dest_monomial(t1), dest_monomial(t2))",
"def test_equality(self):\n Mod5 = IntegersModP(5)\n Mod11 = IntegersModP(11)\n\n polysOverQ = polynomials_over(Fraction).factory\n polysMod5 = polynomials_over(Mod5).factory\n polysMod11 = poly... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts the multinomial to Add/Mul/Pow instances. | def multinomial_as_basic(multinomial, *symbols):
l = []
for powers, k in multinomial.iteritems():
term = [k]
for i,e in enumerate(powers):
term.append(Pow(symbols[i], powers[i]))
l.append(Mul(*term))
result = Add(*l)
return result | [
"def multinomial_to_list(mn):\n str_mn = metapy.stats.Multinomial.__repr__(mn)\n list_mn = str_mn.split()\n num_list = []\n for num in list_mn:\n if '0.' in num:\n num = num.replace(',', '')\n num = num.replace('}>', '')\n num_list.append(float(num))\n return n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List Applications Registered on SLATE (json response) | def list_applications_xhr():
if request.method == "GET":
applications = list_applications_request()
return jsonify(applications) | [
"def _get_applications(self) -> List[dict]:\n print('Getting application list...')\n\n #\n # This filter is a bit of a hack. I tried to pick a filter that would\n # return all applications. Without the filter, the command will\n # print a warning message stating that the result se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List Incubator Applications Registered on SLATE (json response) | def list_incubator_applications_xhr():
if request.method == "GET":
incubator_apps = list_incubator_applications_request()
return jsonify(incubator_apps) | [
"def _get_applications(self) -> List[dict]:\n print('Getting application list...')\n\n #\n # This filter is a bit of a hack. I tried to pick a filter that would\n # return all applications. Without the filter, the command will\n # print a warning message stating that the result se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View Known Applications Detail Page on SLATE | def view_application(name):
if request.method == "GET":
applications = list_applications_request()
app_version = None
chart_version = None
for application in applications:
if application["metadata"]["name"] == name:
app_version = application["metadata"]["a... | [
"def _getOrgAppShowUrl(org):\n return '/gsoc/org/application/show2/%s' % org.key.id()",
"def test_applications_page_loads(self):\n response = self.client.get(url_for(\"main.application\"))\n self.assertTrue(b'Application Details' in response.data)",
"def test_app_info_page(self):\n app = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Trains a model with an adaptively decreasing learning rate or gradient clipping. The model will be trained for some number of steps, and the loss is periodically checked. If the loss ever goes up between checks then the training will adapt by reducing the learning rate and/or gradient clipping. | def train_adaptively(model, input_fn, max_steps,
learning_rate=0.01, gradient_clip=1.0,
learning_divisor=10, gradient_divisor=10,
step_check=1000,
start_delay_secs=120,
throttle_secs=60,
**kwarg... | [
"def train(model, x_train, y_train, x_valid, y_valid, config):\n\n # number of times the error can increase before ending training\n threshold = config['early_stop_epoch']\n\n # store current-best model\n # best_model = model\n\n for epoch in range(config['epochs']):\n # for each batch in one ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if the site is being browsed on a mobile phone. | def on_mobile(self):
ua = get_user_agent(self.request)
if ua:
if detect_mobile_browser(ua):
return True
else:
return False
return False | [
"def is_mobile(m):\n return m[0] == 'mobile'",
"def _has_widevine(self):\n if self._os() == 'Android': # widevine is built in on android\n return True\n else:\n if self._widevine_path():\n self._log('Found Widevine binary at {0}'.format(self._widevine_path().... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dictionary with keys being countries (and int. orgs) that have sectors inside them and the values being the available survey langauges. We use ZCatalog directly to bypass permission checks, otherwise we get zero surveys returned for anon users. See 2556. | def get_sectors_dict(self):
context = aq_inner(self.context)
sectorsfolder = getattr(context, 'sectors')
if not sectorsfolder:
return []
client = getattr(context, 'client')
if not client:
return []
resp = {}
ltool = getToolByName(self.con... | [
"def aaq_languages(request):\n return {\"AAQ_LANGUAGES\": QuestionLocale.objects.locales_list()}",
"def available_languages(self):\r\n return Language.objects.filter(\r\n id__in=RLStats.objects.by_resource(\r\n self\r\n ).order_by().values('language').query\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Solve majority element problem using divide and conquer method. >>> majority_element([2, 3, 9, 2, 2]) 2 >>> majority_element([1, 2]) 1 >>> majority_element([1]) 1 | def majority_element(array: List[int]):
return recursive_majority_element(array, 0, len(array) - 1) | [
"def majority_element_naive(elements):\n assert len(elements) <= 10 ** 5\n for e in elements:\n if elements.count(e) > len(elements) / 2:\n return e\n\n return -1",
"def get_majority_element_optimized(elements):\n # Create an empty hash map to keep track of the count of each unique e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the string len is below the max_len, the function returns the same string. If the string is above the max len, the function returns only the last max_len characters plus '...' at the beginning. | def truncate_string_from_end(string: str, max_len: int) -> str:
if len(string) <= max_len:
return string
return f'Last {max_len} chars: "...{string[-max_len:]}"' | [
"def str_ellipsis(string: str, max_length: int = 40) -> str:\n if len(string) <= max_length:\n return string\n n_2 = int(max_length) / 2 - 3\n n_1 = max_length - n_2 - 3\n\n return f\"{string[:int(n_1)]}...{string[-int(n_2):]}\"",
"def truncate_str(s: str, max_len: int, *, suffix: str = \"[...]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns singular or plural of the word depending on the amount. | def get_plural_string(word: str, amount: int) -> str:
if amount == 1:
return f'1 {word}'
else:
return f'{amount} {word}s' | [
"def pluralize(text: str, amount: int) -> str:\n return text + 's' if amount > 1 else text",
"def oneOrSeveral(amount, word):\n if amount != 1:\n word += 's'\n\n return word",
"def pluralized(word):\n defined_plurals = {\"person\": \"people\"}\n if word in defined_plurals:\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns humanreadable string with kilobytes or megabytes depending on the data_size range. \n | def size_to_kb_mb_string(data_size: int, as_additional_info: bool = False) -> str:
if data_size < 1024:
as_additional_info = False
dynamic = f'{data_size} bytes'
elif data_size < 1048576:
dynamic = f'{data_size / 1024:0.1f} kB'
else:
dynamic = f'{data_size / 1048576:0.1f} MB'
if as_additional_info:
retur... | [
"def get_size(self):\n units = (\"B\", \"KB\", \"MB\", \"GB\", \"TB\")\n for i, unit in enumerate(units):\n high = 10**(i*3)\n if self.size < high*1000:\n return f\"{round(self.size/high, 3)} {unit}\"",
"def human_file_size(size):\n suffixes = ' kMGTPEH'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns number of chunks needed to transfer the data_size split to maximum of chunk_size blocks. \n | def calculate_chunks_count(data_size: int, chunk_size: int) -> int:
return (data_size // chunk_size) + (1 if (data_size % chunk_size) > 0 else 0) | [
"def nchunks(self):\n return len(self.chunkings)",
"def calc_chunksize(expected_mb):\n\n expected_mb = limit_es(expected_mb)\n zone = int(math.log10(expected_mb))\n expected_mb = 10**zone\n chunksize = csformula(expected_mb)\n # XXX: Multiply by 8 seems optimal for sequential access\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |