query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Calculates all intramolecular distances for all molecules and sortes the distances by length. | def _get_distances(self):
for molecule in self.values():
molecule.get_distances()
# for atom in self.atoms:
# atom.get_distances() | [
"def _calculate_distances(self):\n all_dists = []\n for ref in range(len(self.atoms)):\n if self.atoms[ref].symbol in self.exclude:\n continue\n indices = list(range(ref+1, len(self.atoms)))\n indices = self._filter_excluded(indices)\n if len(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates the attributes self.atoms and self.invarioms containing lists of all atoms in all molecules and a list of all atoms that are part of the 'exp' molecules and their invarioms respectively. | def _get_atoms(self):
atoms = []
invarioms = []
for molecule in self.values():
atoms += [atom for atom in molecule.atoms]
invarioms += [atom for atom in molecule.atoms if atom.invariom_name is not None]
self.atoms = atoms
self.invarioms = invarioms | [
"def _build_atoms(self) -> None:\n self.atoms, self._id_to_index = list(), dict()\n atom_index = 0\n for residue in self.residues:\n self.topology_files.add(residue.rtf_file_name)\n for atom_data in residue.atoms:\n atom_name, atom_type, charge = atom_data\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the temperature used for ADP calculation. | def set_temperature(self, temperature):
self.Temp = temperature | [
"def set_temperature(self, temperature):\n pass",
"def set_temperature(self, temperature):\n\n self.T = temperature",
"def set_temperature(self, temperature: Number):\n self.temperature = temperature",
"def set_temp(self, temperature):\r\n self.inst.write(\"T \" + str(temperature))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Strips the GENERATOR instance of all unnecessary data to minimize the size of the serialized file. all attributes specified in the 'self.keep' list will be preserved. | def strip(self):
types = [type(self.strip),
type(self.values),
type(self.__ne__),
type(self.__class__)]
for attr in dir(self):
if not type(getattr(self, attr)) in types:
if any(i in attr for i in self.keep) or attr[0:2] == '... | [
"def strip_degenerate(self):\n return self.__class__(self.moltype.strip_degenerate(str(self)), info=self.info)",
"def dumpme(self) :\n fileName = \"./data/oP4_ModelBuilder.dump\"\n with open(fileName,\"wb\") as dumpedFile:\n oPickler = pickle.Pickler(dumpedFile)\n oPickler.d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a unique list of all invariom names in all model compounds. | def _get_invariom_list(self):
self.invariom_list = []
for molecule in self.values():
for atom in molecule.atoms:
for invariom in atom.invarioms:
if not invariom in self.invariom_list:
self.invariom_list.append(invariom) | [
"def romIncs(self):\r\n output = ''\r\n for file in sorted(self.gameFiles.keys(), key=self.gameFiles.__getitem__):\r\n if file.endswith('.s'):\r\n label = self._getBaseFilename(file)\r\n label = label[:label.rindex('.')]\r\n output += '%s:\\n.inc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Maps the invariom names to the 'smallest' model compound containing that invariom. | def _map_invarioms(self):
self.map = {}
for invariom in self.invariom_list:
kill = False
for molecule in self.sorted_molecules:
for atom in molecule.atoms:
if invariom in atom.invarioms:
self.map[invariom] = molecule.nam... | [
"def MAP_labeling(beliefs):\r\n return np.argmin(beliefs, axis=2)",
"def choose_least(me, ifcs, proj):\n \n eqrep = me._eqrep\n eqset = me._eqset\n subs = me._ifc_subs\n m = {}\n for i in ifcs:\n i = eqrep[i]\n x = None\n for i1 in eqset[i]:\n x1 = proj(i)\n if x ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes the error log filepointer and removes the reference. This step is necessary for pickling the GENERATOR instance. | def release(self):
self.errorlog.close()
del self.errorlog
del self.printer | [
"def __del__(self):\n if self.log_file_opened:\n self.log_file.close()",
"def __del__(self):\n\n self.logfd.close()",
"def teardown(self):\r\n __builtin__.open = self._open\r\n\r\n self.log_file.close = self._log_file_close\r\n self.log_file.close()",
"def __del__... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a sorted list of all molecules. The sorting criterion is the molecule.criterion attribute defining the 'size' of an modelcompound. | def _sort_compounds(self):
self.sorted_molecules = sorted(self.values(), key=operator.attrgetter('criterion')) | [
"def test_atom_collection_sort_by_mass():\n atom0 = Atom(mass=0, position=np.array([0, 0, 0]))\n atom1 = Atom(mass=1, position=np.array([1, 1, 1]))\n atom2 = Atom(mass=2, position=np.array([2, 2, 2]))\n collection = AtomCollection([atom1, atom0, atom2])\n collection.sort_by_mass(hl=False)\n masses... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recalculates the ADP from theoretical data. | def _update_adp_calculation(self, Temp):
from sys import stdout
self.printer('\n ...calculating ADPs...\n')
import time
start = time.time()
daba_counter = 0.
max_counter = float(len(self.keys()))
for molecule in self.keys():
daba_counter += 1.
... | [
"def _transfer_adp(self):\n toleratedAtoms = []\n for atom in self['exp'].atoms:\n tolerated = atom.transfer_adp()\n if tolerated:\n toleratedAtoms.append(tolerated)\n for atom in toleratedAtoms:\n atom.averageADP()",
"def _update(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes the 'APD_DABA.txt' file. | def _update_database_file(self, Temp, path):
from datetime import datetime
if path:
filename = path + '/APD_DABA_{:.1f}_.txt'.format(Temp)
else:
filename = 'APD_DABA_{:.1f}_.txt'.format(Temp)
self.printer('\n ...Writing database file: {}...\n'.format(filename))
... | [
"def writeAD(self):\n ofname = self.ad_file\n ofh = open(ofname,'w')\n\n for line in self.lines_ad:\n f = line.strip().split()\n if (len(f) > 1 and f[1] == 'WindFile'):\n if (self.wind_file != None):\n f[0] = \"\\\"\"+self.wind_file+\"\\\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes the 'APD_MAP.txt' file. | def _update_database_map(self, path):
if path:
filename = path + '/APD_MAP.txt'
else:
filename = 'APD_MAP.txt'
filepointer = open(filename, 'w')
for invariom, molecule in self.map.items():
filepointer.write(invariom + ':' + molecule + '\n')
fil... | [
"def _save_mapfile(self):\n if self._mapfile:\n mapfile_path = os.path.join(self.target, self.prefix, \"map.json\")\n if debug:\n print(\"Saving map file to {}\".format(mapfile_path), file=sys.stderr)\n with open(mapfile_path, \"w\") as mapfile:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
a == sqrt(b); a2 == b >>> from euler44 import isqrt, findRoot >>> all( 2 == findRoot( isqrt, i, 1, i ) for i in range(4,9) ) True >>> all( 3 == findRoot( isqrt, i, 1, i ) for i in range(9,16) ) True >>> findRoot( isqrt, 16, 1, 16 ) 4 | def isqrt( a, b ):
return a*a - b | [
"def sqrt(a):",
"def square_root(a):\n return nth_root(a, 2)",
"def get_sqrt_2():\n return 1.41421356",
"def sqrt(self, a):\n raise NotImplementedError",
"def custom_sqrt(n, p):\n\tstart = 0\n\tend = n\n\twhile start <= end:\n\t\tmid = start + (end - start) // 2\n\t\tif mid*mid == n:\n\t\t\tret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of the class names for all registered node types. | def list_node_types(self):
return list(nodelist.all_nodes.keys()) | [
"def list_all_classes(self):\n classes = list(self.extended_class_only_graph.nodes())\n classes = [SchemaClass(_cls, self) for _cls in classes]\n return classes",
"def node_types(self) -> List[str]:\n return list(self[self._node_related_key].keys())",
"def get_all_class_names(self):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a Node subclass with this NodeGroup. This allows custom Node subclasses to be instantiated in this NodeGroup | def register_node_type_from_module(self, modname, classname):
nodelist.register_node_type_from_module(modname, classname) | [
"def add_node(self, *args, **kwargs):\n raise NotImplementedError",
"def register_node(node_cls, library):\n if not issubclass(node_cls, LibraryNode):\n raise TypeError(\"Expected LibraryNode class, got: {}\".format(type(node_cls).__name__))\n if not isinstance(library, types.ModuleType):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call `Node.start()` for all Nodes in this group. | def start_all_nodes(self):
for node in self.nodes:
node.start() | [
"def start_peers(self):\n for i in self.nodes:\n i.start()",
"def start(self):\n self._prepare_zk_configs()\n\n for node_id in self.nodes.keys():\n self.start_node(node_id)\n\n self.fill_node_role()\n log_print('Zookeeper started:\\n{}'.format(repr(self)), color='gre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call `Node.stop()` for all Nodes in this group. | def stop_all_nodes(self):
for node in self.nodes:
if node.running():
node.stop() | [
"def stop_all(self, node=None):\n if node is None:\n node = self.__root\n self.__stop_all(node)",
"def stopall():\n \n for ag in agents:\n ag.stop()",
"def stop(self):\n pass \n #for op_name,op in self.operations.items():\n # op.stop()",
"def stop_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if any of the Nodes in this group are running. | def any_node_running(self):
return any(node.running() for node in self.nodes) | [
"def any_running(self) -> bool:\n return self.counts()[JobStatus.RUNNING] > 0",
"def all_is_running(self):\r\n return all(p.running for p in self._platforms.values())",
"def IsRunning(self):\n return all(agent.is_mission_running for agent in self.agents)",
"def are_worker_nodes_ready(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create contextawareness by giving a callback to handle the user's next message. Raises self.ValueError if timeout_time is not a positive time or None. | def _register_context_callback(self, user, callback=None,
noresponse_callback=None, timeout_time=0):
# architecture: self.response_callbacks is a dict with key "j@i.d"
# and entry [callback_when_response]. If a timeout_time is given
# then we call noresponse_c... | [
"def add_timeout(self, deadline, callback_method):\r\n return self.ioloop.add_timeout(deadline, callback_method)",
"def request_timeout(self, timeout: typing.Union[int, float, aiohttp.ClientTimeout]):\n timeout = self._prepare_timeout(timeout)\n token = self._ctx_timeout.set(timeout)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a function to be called on receipt of a message of type 'typ' (muc/chat), category 'cat' (recv, send, unhandled, _self, _filter) sent from user or room 'name'. | def _register_callback(self, name, typ, cat, callback,
including_self=False, priority=Priority.NORMAL):
logging.info("Registering callback: %s", name)
# self._handlers is a dictionary of form:
# { type : { category : { room/groupname : [Handler objects]}}}
typh... | [
"def register_msgtype_callback(self, path, msg_type, callback_func):",
"def registerCallback(self, msg_type, cb, single_shot=False):\n #print(\"registerCallback: registering '%s' for body type 0x%X\")\n logdebug(\"registerCallback: registering '%s' for body type 0x%X\",cb, msg_type)\n self._c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send muc message to room. The message will be run through any registered filters before it is sent. | def send_muc(self, room, body, source=None, priority=Priority.NORMAL):
# Verify this is a room EnDroid knows about
if source is None:
source = self.wh.my_emails[0]
msg = Message('muc', source, body, self, recipient=room)
# when sending messages we check the filters registe... | [
"def muc_message(self, msg):\n if msg['mucnick'] == self.nick:\n return\n\n if self.muc_hook(msg) is True:\n return\n\n if not msg['body'].startswith(self.nick):\n return\n\n cmdline = re.sub(r'{}[ ]?[,:]? '.format(self.nick), '',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send chat message to person with address user. The message will be run through any registered filters before it is sent. response_cb is an optional callback to be called to handle the next message received from the user. (Note that only the latest such callback | def send_chat(self, user, body, source=None, priority=Priority.NORMAL,
response_cb=None, no_response_cb=None, timeout=None):
if source is None:
source = self.wh.my_emails[0]
# Verify user is known to EnDroid
msg = Message('chat', source, body, self, recipient=user... | [
"async def send_to_user(self, user: User, msg: Msg, address: str = None):\n if address is None:\n address = user.current_address\n\n await self.send(msg, address)",
"def callback_query(r):\n db = DB()\n chat_id = r['callback_query']['message']['chat']['id']\n deleteMessageReplyMa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Notify the message that the caller hasn't handled it. This should only be called by plugins that have registered as a handler (and thus have incremented the handler count for this message). This method takes arbitrary arguments so it can be used as deferred callback or errback. | def unhandled(self, *args):
if self._context_response:
# we asked a context-aware plugin to deal with the message, but it
# did not
self._context_dealt_with = False
else:
self.dec_handlers() | [
"def _on_message_no_ack_callback(self, unused, method, properties, body):\n incoming_message = self._incoming_message_class(\n self._pika_engine, None, method, properties, body\n )\n self._on_incoming_message(incoming_message)",
"def ack_ignore_handler():\n pass",
"def ignore_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all root nodes of techanim setups using an attr from config | def get_all_setups_roots():
ta_roots = cmds.ls("*.{}".format(CONFIG["config_attr"]), r=True, o=True)
return ta_roots | [
"def get_all_setups_nodes():\n ta_roots = get_all_setups_roots()\n ta_nodes = [TechAnim_Setup(x) for x in ta_roots]\n return ta_nodes",
"def get_nodes():\n return conf.config.get_nodes(RELATIVE_PATH_FIXTURES_HOST)",
"def get_nodes():\n nodes_config_file = Settings.CONF_NODES_FILE\n current_nod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This returns instantiated Techanim_setups | def get_all_setups_nodes():
ta_roots = get_all_setups_roots()
ta_nodes = [TechAnim_Setup(x) for x in ta_roots]
return ta_nodes | [
"def setups():\n setups = []\n\n # If you run this in detailed mode, you need to set --t8 to 1e8\n kotani2017_F2 = dict()\n kotani2017_F2['name'] = 'kotani2017_F2'\n kotani2017_F2['piltemplate'] = kotani2017_F2_pil\n kotani2017_F2['pilparams'] = [None]\n kotani2017_F2['pepperargs'] = {'condense... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all of the namespaces | def get_all_namespaces():
cmds.namespace(setNamespace=':')
return cmds.namespaceInfo(listOnlyNamespaces=True, recurse=True) | [
"def _fetch_all_namespaces():\n response = _fetch_herd_session() \\\n .get('{}://{}/{}/{}'.format(HERD_REST_PROTOCOL, HERD_BASE_URL,\n HERD_REST_BASE_PATH, 'namespaces')) \\\n .json()\n\n namespaces = []\n for namespaceKey in response['namespaceKeys']:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add two dictionaries together, return new dictionary. if key in B already exists in A, do not override. None destructive. | def get_added_dicts(a, b):
tmp = copy.deepcopy(a)
for key, val in b.iteritems():
if key not in tmp:
tmp[key] = val
return tmp | [
"def dict_A_add_B_new_only( dctA , dctB ):\n B = dctB.copy()\n for key , val in B.iteritems():\n if key not in dctA:\n dctA[ key ] = val\n return dctA",
"def add_to_dict_if_not_exist(dictionary_one: Dict[Any, Any], dictionary_two: Dict[Any, Any]) -> Dict[Any, Any]:\n if dictionar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
when the target namespace is set, make any changes or prep | def set_target_namespace(self, namespace):
# do shit
self.target_namespace = namespace.strip(":") | [
"def test_patch_net_namespace(self):\n pass",
"def set(namespace, name):",
"def test_replace_namespaced_build(self):\n pass",
"def test_replace_namespaced_stateful_set(self):\n pass",
"def set_current_namespace(self, namespace: N) -> None:\n pass",
"def test_patch_namespaced_bu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convenience function, wrap any node belonging to this setup in the namespace retrieved when initialized | def _wrap_ns(self, node):
return "{}{}".format(self.techanim_ns, node) | [
"def wrap_namespace(self, node):\n self._push_splicer(\"class\")\n for cls in node.classes:\n if not cls.options.wrap_lua:\n continue\n name = cls.name\n self.reset_file()\n self._push_splicer(name)\n self.wrap_class(cls)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set config on this setup. Decide if it will merge with stored, or follow env variable one. TODO | def set_config(self):
str_config = cmds.getAttr("{}.{}".format(self.root_node,
CONFIG["config_attr"]))
try:
# THIS NEEDS TO BE REVISTED. I am adding shit from file
stored_config = ast.literal_eval(str_config)
self.setup... | [
"def setup_config(self, config):\n if config['TRACKER_NAME'] is None or \\\n config['APP_ID'] is None:\n return\n\n keys = [\n 'COLLECTOR_HOST',\n 'PROTOCOL',\n 'EMIT_METHOD',\n 'BUFFER_SIZE',\n 'DEBUG_MODE',\n 'EN... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
refresh the info dict on setup with all new information | def refresh_info(self):
if not self.is_setup_connected() and not self.target_namespace:
return
self.get_association_info()
self.create_techanim_connections() | [
"def update(self, info):\n self.name = info.name\n for k in info.info:\n self.info[k] = info.info[k]",
"def _init(self):\n\n self._info.update({\n 'name': self._tool.__class__.__name__,\n 'creator': self._tool.creator(),\n 'module': self._tool.__cla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Nuclei, get them shits. Belonging to this setup. | def get_nuclei(self):
sim_layer = self._wrap_ns(self.setup_config["sim_layer"])
return cmds.listRelatives(sim_layer, ad=True, type="nucleus") or [] | [
"def _get_species(self):\n self._get_popn_split()\n self._parse_taxo_info()",
"def get_little_three_dragons(sit):\n poss = []\n sets = get_only_sets(sit['sets'])\n poss = find_combinations(sets, 3, is_only_dragon_eye_and_dragon_pungs)\n return ('Little Three Dragons', poss)",
"def GetH... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays the desired nodes and any parent nodes that may be hidden | def show_nodes(self, nodes, select_second=None, isolate=False, select=False):
cmds.hide(cmds.listRelatives(self.root_node,
ad=True,
type="transform"))
cmds.showHidden(nodes, a=True)
if select or isolate:
cmds.... | [
"def treeView(self):\n if self.list:\n self.list.Hide()\n self.tree.Show()\n self.initTree()",
"def display_nodes(self) -> None:\n\n def display_decision_node(node):\n txt = []\n txt.append(\" Type: \" + node.get(\"type\"))\n txt[-1] +... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
delete input layer on any nodes | def delete_input_layer_cache(self):
# deleteGeometryCache;
# performDeleteGeometryCache 0;
# deleteCacheFile 3 { "delete", "", "geometry" };
input_nodes = self.get_layer_nodes_info([self.input_layer])
cached_nodes = self.is_node_cached(input_nodes.values()[0])
if cached_n... | [
"def deleteLayer(self, layer='0'):\n \n pass",
"def delete_layer(LayerId=None):\n pass",
"def _clearLayer(self, layer=0):\n for i in self._existingLayerItems(layer):\n self._plt.removeItem(i)",
"def destroy_nodes(\n self,\n name,\n ):\n pass",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
does the input layer have any nodes with caches on them | def is_input_layer_cached(self):
input_nodes = self.get_layer_nodes_info([self.input_layer])
return self.is_node_cached(input_nodes.values()[0]) | [
"def has_cache(self, node):\n return node in self.model.cache",
"def is_sim_layer_cached(self):\n layers = [self._wrap_ns(self.setup_config[\"sim_layer\"])]\n input_nodes = self.get_layer_nodes_info(layers)\n return self.is_node_cached(input_nodes.values()[0])",
"def is_layered(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
are there any nodes in the sim layer that have cache nodes on them | def is_sim_layer_cached(self):
layers = [self._wrap_ns(self.setup_config["sim_layer"])]
input_nodes = self.get_layer_nodes_info(layers)
return self.is_node_cached(input_nodes.values()[0]) | [
"def is_node_cached(self, nodes):\n nodes_with_cache = []\n for node in nodes:\n for shape in cmds.listRelatives(node, shapes=True) or []:\n if cmds.listConnections(shape, type=\"historySwitch\"):\n nodes_with_cache.extend([node, shape])\n el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
are the specific nodes supplied cached in anyway | def is_node_cached(self, nodes):
nodes_with_cache = []
for node in nodes:
for shape in cmds.listRelatives(node, shapes=True) or []:
if cmds.listConnections(shape, type="historySwitch"):
nodes_with_cache.extend([node, shape])
elif cmds.listC... | [
"def has_cache(self, node):\n return node in self.model.cache",
"def cache_lookup(self, node, content):\n if node in self.model.cache:\n return self.model.cache[node].has(content)",
"def local_cache_lookup(self, node, content):\n if node in self.model.local_cache:\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Función que separa cada palabra de la lista en sublistas de caracteres para poder realizar las permutaciones y manipularlas más fácilmente. Recibe lista con las palabras leídas y devuelve la nueva lista con sublistas de las palabras seaparadas por caracteres | def separa_por_caracteres(lista):
lista_resultado = [ [ letras for letras in palabra ] for palabra in lista ]
return lista_resultado | [
"def mayus_letra_por_palabra(lista):\n alterada = []\n for palabra in lista:\n cadena = ''\n i = 0\n while i < len(palabra):\n palabra[i] = palabra[i].swapcase()\n alterada.append(cadena.join(palabra))\n palabra[i] = palabra[i].swapcase()\n i +=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Función que cambia las letras (keys) de la palabra por algún número (values), serán modificadas en la lista que recibe como parámetro | def cambia_letra_por_numero(lista):
for palabra in lista:
i = 0
while i < len(palabra):
if palabra[i] in dicc_numeros.keys():
pal = palabra[i]
palabra[i] = dicc_numeros[palabra[i]]
i += 1 | [
"def normalize_keys(*values: Union[int, str]) -> Set[int]:\n ids, slugs = set(), set()\n for x in values:\n try:\n rel_id = int(x)\n except ValueError:\n # it was a string, not an int. Add value to slugs\n slugs.add(x)\n els... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Función que cambia a mayúscula o minúscula una letra de la palabra, recorre las palabras de la lista y va haciendo el cambio De letra a letra de la palabra para regresar una lista con las palabras originales con n veces una letra mayúscula/minúscula Devuelve lista con las nuevas palabras donde cada una tiene una letra ... | def mayus_letra_por_palabra(lista):
alterada = []
for palabra in lista:
cadena = ''
i = 0
while i < len(palabra):
palabra[i] = palabra[i].swapcase()
alterada.append(cadena.join(palabra))
palabra[i] = palabra[i].swapcase()
i += 1
return ... | [
"def permuta_palabras(lista):\n cad = ''\n final,mezclas, resultado = [], [], []\n for palabra in lista:\n if len(palabra) <= 7:\n mezclas += permutations(palabra)\n if len(palabra) > 7 and len(palabra) < 15:\n mezclas+= permutations(palabra[:7])\n mezclas+= p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Función que realiza las permutaciones de las palabras contenidas en la lista, las permutaciones se realizan con la función permutations() del módulo itertools. Cuando la palabra es mayor a 7 caracteres se particionan las permutaciones porque solamente llega a 7!. Se agregan a las conraseñas generadas desde las palabras... | def permuta_palabras(lista):
cad = ''
final,mezclas, resultado = [], [], []
for palabra in lista:
if len(palabra) <= 7:
mezclas += permutations(palabra)
if len(palabra) > 7 and len(palabra) < 15:
mezclas+= permutations(palabra[:7])
mezclas+= permutations(p... | [
"def generar_palabras():\n letras = 'abcdefghijklmnopqrstuvwxyz'\n\n for largo in range(3, 7):\n conjuntos = [letras, ] * largo\n for letras_elegidas in product(*conjuntos):\n palabra = ''.join(letras_elegidas)\n yield palabra",
"def anagram_solver(lst):\n for i in ran... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Función que escribe las contraseñas generadas en el archivo de salida. | def escribe_contrasenias(lista, archivo_salida):
cad = ''
with open(archivo_salida,'w') as passwords:
for cadaPassword in lista:
passwords.write(cad.join(cadaPassword)+'\n') | [
"def generate_password_file(source_fn, dest_fn, rules=lambda word:true):\n filteredWords = filter_words_from_file(source_fn, rules);\n combos = combinations(filteredWords);\n writer = open(dest_fn, \"w\");\n for i in range(len(combos)):\n writer.write(combos[i][0] + \":\" + combos[i][1] + \"\\n\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Función para realizar la combinación aleatoria de las palabras contenidas en lista. Se establece límite de < 100 para lal nueva lista generada. Es una forma manual de realizar la mezcla de las palabras que después serán permutadas. Recibe lista con las palabras y devuelve la lista con sublistas de las palabras mezclada... | def mezclar_todas_palabras(lista):
cadenas = []
otra = []
while len(otra) < 100:
for palabra in lista:
for palabra in lista:
posInicial = randint(0,len(palabra)-1)
posFinal = randint(0,len(palabra)-1)
agrega = palabra[posInicial:posFinal+1]... | [
"def permuta_palabras(lista):\n cad = ''\n final,mezclas, resultado = [], [], []\n for palabra in lista:\n if len(palabra) <= 7:\n mezclas += permutations(palabra)\n if len(palabra) > 7 and len(palabra) < 15:\n mezclas+= permutations(palabra[:7])\n mezclas+= p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cons = con_ceq(x,project) Equality Constraint Functions SU2 Project interface to scipy.fmin_slsqp | def con_ceq(x,project):
cons = project.con_ceq(x)
if cons: cons = array(cons)
else: cons = zeros([0])
return cons | [
"def con_cieq(x,project):\n \n cons = project.con_cieq(x)\n \n if cons: cons = array(cons)\n else: cons = zeros([0])\n \n return -cons",
"def con_dcieq(x,project):\n \n dcons = project.con_dcieq(x)\n \n dim = project.n_dv\n if dcons: dcons = array(dcons)\n else: dcons... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dcons = con_dceq(x,project) Equality Constraint Gradients SU2 Project interface to scipy.fmin_slsqp | def con_dceq(x,project):
dcons = project.con_dceq(x)
dim = project.n_dv
if dcons: dcons = array(dcons)
else: dcons = zeros([0,dim])
return dcons | [
"def con_dcieq(x,project):\n \n dcons = project.con_dcieq(x)\n \n dim = project.n_dv\n if dcons: dcons = array(dcons)\n else: dcons = zeros([0,dim])\n \n return -dcons",
"def con_cieq(x,project):\n \n cons = project.con_cieq(x)\n \n if cons: cons = array(cons)\n else: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cons = con_cieq(x,project) Inequality Constraints SU2 Project interface to scipy.fmin_slsqp | def con_cieq(x,project):
cons = project.con_cieq(x)
if cons: cons = array(cons)
else: cons = zeros([0])
return -cons | [
"def con_dcieq(x,project):\n \n dcons = project.con_dcieq(x)\n \n dim = project.n_dv\n if dcons: dcons = array(dcons)\n else: dcons = zeros([0,dim])\n \n return -dcons",
"def con_ceq(x,project):\n \n cons = project.con_ceq(x)\n \n if cons: cons = array(cons)\n else: c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dcons = con_dcieq(x,project) Inequality Constraint Gradients SU2 Project interface to scipy.fmin_slsqp | def con_dcieq(x,project):
dcons = project.con_dcieq(x)
dim = project.n_dv
if dcons: dcons = array(dcons)
else: dcons = zeros([0,dim])
return -dcons | [
"def con_dceq(x,project):\n \n dcons = project.con_dceq(x)\n\n dim = project.n_dv\n if dcons: dcons = array(dcons)\n else: dcons = zeros([0,dim])\n \n return dcons",
"def con_cieq(x,project):\n \n cons = project.con_cieq(x)\n \n if cons: cons = array(cons)\n else: cons =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert dictionary into data frame and tokenize inputs given queries. | def prepare_inputs(data, queries, tokenizer):
# Prepare inputs
table = pd.DataFrame.from_dict(data)
inputs = tokenizer(table=table, queries=queries,truncation=True, padding=True,return_tensors="pt").to(device)
# Return things
return table, inputs | [
"def query2df(query):\n df = pd.DataFrame(data = list(itertools.product([0, 1], repeat=len(query.variables))), columns=query.variables)\n df['p'] = query.values.flatten()\n return df",
"def parse_df(self, kb_name, df, answer_col, query_col='', context_col='context_string'):\n df = df.assign(contex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate predictions for some tokenized input. | def generate_predictions(inputs, model, tokenizer):
# Generate model results
outputs = model(**inputs)
# Convert logit outputs into predictions for table cells and aggregation operators
predicted_table_cell_coords, predicted_aggregation_operators = tokenizer.convert_logits_to_predictions(
input... | [
"def predict_tokens(self, tokens):\n return",
"def predict_tokens(self:Learner, inp, **kargs):\n pred_lbls, pred_lbl_ids, probs = self.predict(inp)\n\n # grab the huggingface tokenizer from the learner's dls.tfms\n learn_hf_tokenizer = self.dls.tfms[0].tokenizer.filter(lambda tok: isinstance(tok, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert the filename to lon and lat | def fn2lonlat(filename):
tokens = filename.split("/")[-1].rsplit(".", 1)[0].split("x")
return [0 - float(tokens[0]), float(tokens[1])] | [
"def parseFilename(self, filename):\r\n match = self.filename_regex.match(filename)\r\n if match is None:\r\n # TODO?: Raise exception?\r\n '''print \"Filename\", filename, \"unrecognized!\"'''\r\n return None\r\n lat = int(match.group(2))\r\n lon = int(m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1、判断f是否为一个有效的路径 是,则执行第二步 否,则返回一个无效文件的错误信息 2、获取f路径下面的所有文件,判断文件的类型 包含文件,则输出文件夹路径列表 不包含文件,则输出Not dir | def get_dir(f):
if os.path.exists(f):
fileList=os.listdir(f)
# print(fileList)
result=[]
for file in fileList:
if os.path.isdir(f+os.sep+file):
result.append(f+os.sep+file)
if result==[]:
return 'Not dir'
return result
else:... | [
"def get_file_list(types=None,osdir='./'):\n\tflist=os.listdir(osdir)\n\tprint flist, \"\\n\\n\"\n\toutlist=[]\n\tfor f in flist:\n\t\tif tocheckexist(f,types) is not None:\n\t\t\toutlist=outlist+[f]\n\treturn outlist",
"def _validate_path(self, path: _TPath) -> _TPathList:\n self._print('DataGenerator: _v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if a function is a stub. | def is_stub(node: AnyFunctionDef) -> bool:
function_has_docstring = (
isinstance(node.body[0], Expr) and
isinstance(node.body[0].value, Str)
)
if function_has_docstring:
return _is_stub_with_docstring(node)
return _is_stub_without_docstring(node) | [
"def testStub(self):\n\n self.assertNotEqual(None, self.stub)",
"def checkfuncname(b, frame):\n if not b.funcname:\n # Breakpoint was set via line number.\n if b.line != frame.f_lineno:\n # Breakpoint was set at a line with a def statement and the function\n # defined... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the Player's Turn | def runPlayerTurn(self, player):
self.runController(PlayerTurnController(player, self.game)) | [
"def get_turn(self, player):\n clear_screen()\n input(\"It is {}'s turn!\\n{}, \"\n \"press Enter when you are ready to start you turn.\"\n .format(player, player))\n clear_screen()\n opponent_player = self.get_opponent_in_game(player)\n player.perform_tu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load readings from local filesysystem. There's no need to refactor this function. The json library reads until EOF and then loads into memory. Returns a dictionary. | def get_readings(readings_file):
with open(readings_file, 'r') as f:
readings = json.load(f)
return readings | [
"def read_data():\r\n\r\n if os.path.isfile(os.getcwd() + \"/www/access_list.txt\") and os.stat(os.getcwd() + \"/www/access_list.txt\").st_size != 0:\r\n data = json.load(open(os.getcwd() + \"/www/access_list.txt\"))\r\n return collections.defaultdict(dict, data)\r\n else:\r\n return coll... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function prints the initialization dict to a .yml file. | def print_dict(init_dict, file_name="test"):
ordered_dict = collections.OrderedDict()
order = ["SIMULATION", "PARAMS", "DIST"]
for key_ in order:
ordered_dict[key_] = init_dict[key_]
with open("{}.boupy.yml".format(file_name), "w") as outfile:
yaml.dump(ordered_dict, outfile, explicit_s... | [
"def print_dict(init_dict, file_name=\"test\"):\n ordered_dict = collections.OrderedDict()\n order = [\n \"GENERAL\",\n \"CONSTANTS\",\n \"INITIAL_CONDITIONS\",\n \"SIMULATION\",\n \"SOLUTION\",\n \"PARAMETERS\",\n ]\n for key_ in order:\n ordered_dict[ke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of Panchayats based on the furnished parameters. If names of state, district or block are given, they are used as filters. Accepts any part of the name of any parameter. | def getPanchayats(request):
if request.method == 'GET':
inName=request.GET.get('panchayat', '')
ptid=request.GET.get('ptid', '')
blockName=request.GET.get('block', '')
bid = request.GET.get('bid', '')
districtName = request.GET.get('district', '')
stateName = request.... | [
"def filter_params(self, parameters: List[Dict]):\n pgs_filterd = []\n\n for group in parameters:\n if group[\"params\"] == []:\n pass\n else:\n pgs_filterd += [group]\n return pgs_filterd",
"def categorize_parameters(\n self, paramet... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function gets the active jobcards in the Panchayat by getting jobcards from the workdetail table. I could have taken them from the jobcard register, but it leads to a lot of inactive jobcards with no data, which could be frustrating on the ground. If the feedback is that it is frustrating to not find other jobcard... | def getJobcards(request):
if request.method == 'GET':
jcEnd=request.GET.get('jobend', '')
jcContains=request.GET.get('vcode', '')
ptid=request.GET.get('ptid', '')
limit=request.GET.get('limit', '')
if limit == '':
limit=50
else:
limit=int(limit)
... | [
"def getJobcardsAll(request):\n #GOLITODO add the extra field in models for the village and use it here for filtring\n if request.method == 'GET':\n jcEnd=request.GET.get('jobend', '')\n jcContains=request.GET.get('vcode', '')\n ptid=request.GET.get('ptid', '')\n limit=request.GET.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function gets all the jobcards and does not look at whether the jobcard is active or not. From api.ai, I might get two numbers for the jobcard intent. One will correspond to the last numbers of a jobcard and the other is likely to be a village code. There are challenges in putting them together. Right now, I am go... | def getJobcardsAll(request):
#GOLITODO add the extra field in models for the village and use it here for filtring
if request.method == 'GET':
jcEnd=request.GET.get('jobend', '')
jcContains=request.GET.get('vcode', '')
ptid=request.GET.get('ptid', '')
limit=request.GET.get('limit'... | [
"def getJobcards(request):\n if request.method == 'GET':\n jcEnd=request.GET.get('jobend', '')\n jcContains=request.GET.get('vcode', '')\n ptid=request.GET.get('ptid', '')\n limit=request.GET.get('limit', '')\n if limit == '':\n limit=50\n else:\n limit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This returns the number of jobcard holders that are there in a Panchayat. | def getNumberJobcards(request):
if request.method == 'GET':
ptid=request.GET.get('ptid', '')
noJobcards=Jobcard.objects.filter(panchayat__id=ptid).count()
return JsonResponse(noJobcards, safe=False) | [
"def supplyCount(card):\n return g.supplyCount[card]",
"def get_total_shareholders() -> int:\n return len(balance_of)",
"def holders(self):\n if not self.reentrant:\n if self._get_locker():\n return 1\n return 0\n r = self.client.range(self.holders_key).k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Details about each Jobcard | def jobcardInfo(request):
if request.method=='GET':
jobcard = request.GET.get('jobcard', '')
status = request.GET.get('status','')
if status == '':
wds=WorkDetail.objects.filter(worker__jobcard__jobcard=jobcard).order_by("-muster__dateTo")
else:
wds=WorkDetail.objects.filter(worker__jobcard__jobca... | [
"def get_job_detail():\n\n return JobDetail.query.all()",
"def _details(self) -> Mapping[str, Any]:\n return self._connection.request(\"GET\", f\"/jobs/{self.id}\").json()",
"def get_job_details():\n server = get_server_instance()\n for job_name, job_instance in server.get_jobs():\n print... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gives Method to get FTOs | def getFTO(request):
if request.method=='GET':
ftoNo = request.GET.get('ftoNo', '')
myftos=FTO.objects.filter(ftoNo=ftoNo)
serializer = FTOSerializer(myftos,many=True)
return JsonResponse(serializer.data, safe=False) | [
"def getF2s(self):\n return self.getter(lambda x: x.getF2())",
"def writeForcings(self, method, options):\n log = logging.getLogger(__name__)\n if method.lower() == \"esp\":\n self._ESP(options)\n elif method.lower() == \"bcsd\":\n pass\n elif method.lower(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gives Method to retrieve Wagelists | def getWagelists(request):
if request.method=='GET':
bcode = request.GET.get('bcode', '')
limit = request.GET.get('limit', '')
if limit == '':
limit=50
else:
limit=int(limit)
if bcode == '':
wagelists=Wagelist.objects.filter(id__gt=0)[:limit]
else:
wagelists=Wagelist.objects.filter(blo... | [
"def retrieve_listing_items(self):",
"def get_list_link(self):",
"def test_lists_get(self):\n pass",
"def getListing(self) -> ghidra.program.model.listing.Listing:\n ...",
"def wfp_list(type=None):\n data = Wfp_lists.query.filter_by(type=type).all()\n return render_template(\"par... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print out all non private methods and attributes of an abject | def print_attr(obj):
for attr in dir(obj):
if attr.startswith('__'):
continue
else:
print attr
print getattr(obj, attr)
print '\n' | [
"def pprint(obj):\n for argname in sorted([x for x in dir(obj) if not x.startswith('__')]):\n # Skip callables\n if hasattr(getattr(obj, argname), '__call__'):\n continue\n print(\"{} : {}\".format(argname, getattr(obj, argname)))",
"def _debug( self, unoobj,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a file containing gnuplot data for the profile. | def write_plot(self):
with open(self._graph_data_path, "w+") as f:
run_time = self.start_time
f.write("Time, Temperature\n")
temperature = 0
for step in self.profile["steps"]:
keys = list(step)
if len(keys) > 0:
... | [
"def writeProfile(fname,prof):\n t = np.linspace(0,1,prof.shape[0],endpoint=False)\n fh = open(fname,'w')\n for x in range(prof.shape[0]):\n fh.write('%.7e %.7e\\n' % (t[x],prof[x]))\n fh.close()",
"def gnuplot(title, data, filename, ylabel=None, xlabel=None, using=None,\n styles=[\"poin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of objects describing all the profiles in the profiles_folder. | def get_list(profiles_folder, logger):
profile_list = []
with scandir(profiles_folder) as it:
for entry in it:
if entry.is_file():
filepath = profiles_folder + entry.name
profile = json_from_file(filepath, logger)
if... | [
"def list(self):\n # List is to be extended (directories should not have a trailing slash)\n paths_to_ignore = ['.DS_Store']\n\n profiles = []\n cache = ClientCache(self._conan_api.cache_folder)\n profiles_path = cache.profiles_path\n if os.path.exists(profiles_path):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Este es un documento. La primera linea termina en punto(.) Despues un espacio Y el resto del documento Llamarla con la extencion __doc__ y agregar un pass como se muestra a continuacion | def documento():
pass | [
"def printdoc():",
"def make_doc(self, doc):\n # TODO do\n self.__doc__ = doc",
"def show_doc(self):\n pass",
"def docs():",
"def getDoc(self):\r\n return self.__doc__",
"def getdoc(object):\r\n try:\r\n doc = object.__doc__\r\n except AttributeError:\r\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method takes the land use data and multiplies various columns of the land use data by coefficients from the spec table in order to yield a size term (a linear combination of land use variables). | def size_term(land_use, destination_choice_coeffs):
coeffs = destination_choice_coeffs
# first check for missing column in the land_use table
missing = coeffs[~coeffs.index.isin(land_use.columns)]
if len(missing) > 0:
logger.warn("%s missing columns in land use" % len(missing.index))
... | [
"def dataCellSpecificLibrarySizeFactors(dataFrame):\n librarySize = dataFrame.sum(axis=0)\n meanLibrarySize = librarySize.mean()\n sizeFactors = librarySize / meanLibrarySize\n cellSpecificNormalizedDataFrame = dataFrame / sizeFactors\n return cellSpecificNormalizedDataFrame, sizeFactors",
"def _co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Operator for performing a keyadd keyadd is additive so you will end up with more entries in the resulting dictionary This will append a the version specied by the primary_key migrator field. Additionally all dependencies specified by zip_keys will be updated with additional entries from v2. If an ordering reorders the ... | def op_variant_key_add(v1: dict, v2: dict):
primary_key = v2["__migrator"]["primary_key"]
ordering = v2["__migrator"].get("ordering", {})
if primary_key not in v2:
return v1
if primary_key not in v1:
raise RuntimeError("unhandled")
result = v1.copy()
for pkey_ind, pkey_val in en... | [
"def test_multiple_key_add_migration():\n base = parse_variant(\n dedent(\n \"\"\"\n python:\n - 3.6.* *_cpython # [not (osx and arm64)]\n - 3.7.* *_cpython # [not (osx and arm64)]\n - 3.8.* *_cpython\n python_impl:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inverse of op_variant_key_add Will remove a given value from the field identified by primary_key and associated zip_keys | def op_variant_key_remove(v1: dict, v2: dict):
primary_key = v2["__migrator"]["primary_key"]
ordering = v2["__migrator"].get("ordering", {})
if primary_key not in v2:
return v1
assert len(v2[primary_key]) == 1
result = v1.copy()
if primary_key not in v1:
return v1
if v2[prima... | [
"def remove(key):",
"def remove_key(self, tablename, key):\n raise NotImplementedError",
"def _DeleteValue(self, key):\n pass",
"def decrease_key(self, old_item, new_item):",
"def removeKey(self, time, attributeIndex, view) -> None:\n ...",
"def remove(self, key, column_path, timestam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the two variants together. Present this assumes mostly flat dictionaries. | def variant_add(v1: dict, v2: dict) -> Dict[str, Any]:
left = set(v1.keys()).difference(v2.keys())
right = set(v2.keys()).difference(v1.keys())
joint = set(v1.keys()) & set(v2.keys())
# deal with __migrator: ordering
if "__migrator" in v2:
ordering = v2["__migrator"].get("ordering", {})
... | [
"def __iadd__(self, other):\n if not isinstance(other, dict):\n msg = 'Can not concatenate Dict and {}'.format(type(other))\n raise TypeError(msg)\n for key, val in other.items():\n if key in self:\n self._append_key(key, val)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the top 10 hot posts of a subreddit | def top_ten(subreddit):
req = get(
"https://www.reddit.com/r/{}/hot.json".format(subreddit),
headers={
"User-Agent": "alx_app"},
params={
"limit": 10},
allow_redirects=False)
if req.status_code != 200:
print(None)
else:
posts = req.json... | [
"def top_ten(subreddit):\n # Set the Default URL strings\n base_url = 'https://www.reddit.com'\n api_uri = '{base}/r/{subreddit}/hot.json'.format(base=base_url,\n subreddit=subreddit)\n\n # Set an User-Agent\n user_agent = {'User-Agent': 'Python/req... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
copies memory region to target | def transfer_mem_to_target(ava, addr, length):
memory = ava.get_emulator().read_untyped_memory(addr, length)
# is this file needed ?
f = open("/tmp/ava_memory", "wb")
f.write(memory)
f.close()
ava.get_target().write_untyped_memory(addr, memory) | [
"def copyToMemory(self):\n self.chip8.execute(0xA200)\n self.chip8.execute(0xF355)\n \n memory = self.chip8.get_memory()\n \n self.assertEquals(0x64, memory[0x200])\n self.assertEquals(0x27, memory[0x201])\n self.assertEquals(0x12, memory[0x202])\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalise `data` with `method`. | def normalise(data, method='robust'):
if method == 'none':
return data
X_train, y_train = data['train']
X_test, y_test = data['test']
if method == 'l2':
trans = Normalizer('l2')
elif method == 'l1':
trans = Normalizer('l1')
elif method == 'max':
trans = Normaliz... | [
"def normalize(method, df):\n columns = df.columns\n if method == \"range\":\n return pd.DataFrame(data=MinMaxScaler().fit(df).transform(df),\n columns=columns)\n elif method == \"z\":\n return stats.zscore(df)\n elif method == \"maxabs\":\n return pd.Data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add item to antecedent. The item is referred by its integer index in the Dataset's class item_map. | def add_item(self, item: int) -> None:
self._antecedent.add(item)
self._is_updated = False | [
"def add_item(self, assessment_id, item_id):\n pass",
"def add_item(self, item: _T) -> None:\n if item not in self.item_to_index:\n self.item_to_index[item] = len(self.index_to_item)\n self.index_to_item.append(item)",
"def insert(self, item, index):\n raise NotImpleme... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the rule cover. A rule's cover is defined as the set of tx where each tx contain, at least, every item of the antecedent. | def set_cover(self) -> None:
self._cover = self.Dataset.get_tx(self.antecedent)
self._is_updated = True | [
"def cover(self):\n self._obj.apply(MunkresElement.cover)\n self.covered = True",
"def add_cover(self):\n self.has_cover = True",
"def set_incumbent_coverage(self, coverage):\n\n if not self.edges:\n print(\"Edge objects must be built before setting the incumbent\"\\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return size of a Rule's cover. | def get_cover_size(self) -> int:
if self._is_updated:
return len(self._cover)
else:
self.set_cover()
return len(self._cover) | [
"def calculate_size_of_face(face):\n face_rectangle = face['faceRectangle']\n return face_rectangle['height'] * face_rectangle['width']",
"def get_image_size(self):",
"def __calc_pixels_per_image(self) -> int:\n cwidth, cheight = self.__cropped_image_size()\n return cwidth * cheight",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate rule's quality based on population comparison. | def __population_quality(self) -> float:
population_identifier = np.zeros(shape=self.Dataset.size)
subgroup_identifier = np.ones(shape=len(self.get_cover()))
group = np.concatenate((population_identifier,
subgroup_identifier))
subgroup_times = self.Datase... | [
"def quality_p(self, qual):\n mode0 = Config(self.mlvl, self.mf, self.rank, 0)\n mode1 = Config(self.mlvl, self.mf, self.rank, 1)\n if 0 <= qual <= 5:\n if self.mf:\n return mode1.quality(qual)+mode0.quality(qual)*mode1.fail()\n else:\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return m unique elements from seq. This differs from random.sample which can return repeated elements if seq holds repeated elements. | def _random_subset(seq,m):
targets=set()
while len(targets)<m:
x=random.choice(seq)
targets.add(x)
return targets | [
"def _random_subset(seq, m, rng):\n targets = set()\n while len(targets) < m:\n x = rng.choice(seq)\n targets.add(x)\n\n return targets",
"def _random_subset(seq, m, seed):\n targets = set()\n random.seed(seed)\n\n while len(targets) < m:\n x = random.choice(seq)\n ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return random graph using BarabásiAlbert preferential attachment model. A graph of n nodes is grown by attaching new nodes each with m edges that are preferentially attached to existing nodes with high degree. | def barabasi_albert_graph(n, m, seed=None):
if m < 1 or m >= n:
raise nx.NetworkXError(\
"Barabási-Albert network must have m>=1 and m<n, m=%d,n=%d" % (m, n))
if seed is not None:
random.seed(seed)
# Add m initial nodes (m0 in barabasi-speak)
G = complete_graph(m)
# ... | [
"def ba(self, n=20, m=2):\n\n BA = nx.random_graphs.barabasi_albert_graph(n, m)\n\n return BA",
"def barabasiAlbert(num_vertices):\n\n graph = nx.Graph()\n for x in range(num_vertices):\n graph.add_node(\"(\" + str(x) + \")\")\n\n while not nx.is_connected(graph):\n probabilit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a PA_Graph on total_nodes where each vertex is iteratively connected to a number of existing nodes equal to out_degree | def make_PA_Graph(total_nodes, out_degree):
# initialize graph by creating complete graph and trial object
pa_graph = make_complete_graph(out_degree)
trial = PATrial(out_degree)
# total_nodes - out_degree new nodes
for vertex in range(out_degree, total_nodes):
# add edges from vertex to nei... | [
"def make_PA_Graph(total_nodes, out_degree):\n #initialize graph by creating complete graph and trial object\n PA_graph = make_complete_graph(out_degree)\n trial = PATrial(out_degree)\n \n for vertex in range(out_degree, total_nodes):\n neighbours = trial.run_trial(out_degree)\n\n for x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a json list of Temperature Observations (tobs) for the previous year | def prior_year_temp():
tobs_data = session.query(Measurements.tobs).all()
return jsonify (tobs_data) | [
"def temperature():\n #Query for the dates and temperature observations from a year from the last data point.\n\n last_temp= session.query(Measurement.date).order_by(Measurement.date.desc()).first()\n year_ago = last_temp - dt.timedelta(days=365)\n dates_and_temps = session.query(Measurement.date, Measu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The address prefix for the subnet. | def address_prefix(self) -> Optional[str]:
return pulumi.get(self, "address_prefix") | [
"def ip_address_prefix(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"ip_address_prefix\")",
"def prefix(self):\n return int(self.network.split('/')[1])",
"def NoOfAddressPrefix(self):\n return self._get_attribute('noOfAddressPrefix')",
"def address_prefixes(self) -> Se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of address prefixes for the subnet. | def address_prefixes(self) -> Optional[Sequence[str]]:
return pulumi.get(self, "address_prefixes") | [
"def address_prefixes(self) -> Sequence[str]:\n return pulumi.get(self, \"address_prefixes\")",
"def getAvailableSubnetPrefixes(self):\n usedSubnetPrefixes = set([\n \".\".join(networkInfos.ipAddress.split(\".\")[:2])\n for networkInfos in self.getNetworkInfos()\n ])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Application gateway IP configurations of virtual network resource. | def application_gateway_ip_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayIPConfigurationResponse']]:
return pulumi.get(self, "application_gateway_ip_configurations") | [
"def ip_configuration(self) -> pulumi.Input['BastionHostIpConfigurationArgs']:\n return pulumi.get(self, \"ip_configuration\")",
"def config_networking(\n self, network_obj, ip, netmask, gateway, domain, dns, guest_hostname\n ):\n\n global_ip = vim.vm.customization.GlobalIPSettings()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An array of references to the delegations on the subnet. | def delegations(self) -> Optional[Sequence['outputs.DelegationResponse']]:
return pulumi.get(self, "delegations") | [
"def getSubscribedAddresses():",
"def get_delegators(address: str = None) -> Tuple:\n _assert_is_shareholder(address)\n return tuple(addr for addr in delegations if delegations[addr] == address)",
"def delegations(self) -> Optional[Sequence['outputs.AssessmentDelegation']]:\n return pulumi.get(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Array of IpAllocation which reference this subnet. | def ip_allocations(self) -> Optional[Sequence['outputs.SubResourceResponse']]:
return pulumi.get(self, "ip_allocations") | [
"def get_network_allocations_number(self):\n return self.IP_ALLOCATIONS",
"def ip_addresses(self):\n return self._ip_addresses",
"def get_allocated_networks(self):\n allocated_networks = []\n for nwk in self.conn.listAllNetworks():\n et = ET.fromstring(nwk.XMLDesc())\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Array of IP configuration profiles which reference this subnet. | def ip_configuration_profiles(self) -> Sequence['outputs.IPConfigurationProfileResponse']:
return pulumi.get(self, "ip_configuration_profiles") | [
"def list_profiles(cls, base_directory):\n pc = config_file(os.path.join(base_directory, 'profiles', 'profile.config'))\n return pc[:]",
"def available_profiles(cls) -> List[str]:\n return list(cfg.get(\"profiles\"))",
"def profiles(self):\n return self._profiles",
"def profiles(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Nat gateway associated with this subnet. | def nat_gateway(self) -> Optional['outputs.SubResourceResponse']:
return pulumi.get(self, "nat_gateway") | [
"def add_nat_gateway(self, name, subnet):\n eip_name = \"{}ElasticIP\".format(name)\n\n self.template.add_resource(EIP(\n eip_name,\n Domain=\"vpc\"\n ))\n\n self.template.add_resource(NatGateway(\n name,\n AllocationId=GetAtt(eip_name, 'Alloca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The reference to the NetworkSecurityGroup resource. | def network_security_group(self) -> Optional['outputs.NetworkSecurityGroupResponse']:
return pulumi.get(self, "network_security_group") | [
"def node_security_group(self) -> 'pulumi_aws.ec2.SecurityGroup':\n return pulumi.get(self, \"node_security_group\")",
"def network_security_group_id(self) -> str:\n return pulumi.get(self, \"network_security_group_id\")",
"def node_security_group(self) -> Optional['pulumi_aws.ec2.SecurityGroup']:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An array of references to private endpoints. | def private_endpoints(self) -> Sequence['outputs.PrivateEndpointResponse']:
return pulumi.get(self, "private_endpoints") | [
"def endpoints(self):\n return self[\"endpoints\"]",
"def private_endpoint_connections(self) -> Sequence['outputs.PrivateEndpointConnectionResponse']:\n return pulumi.get(self, \"private_endpoint_connections\")",
"def get_endpoints(self):\n return self.endpoints",
"def private_endpoint_co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The reference to the RouteTable resource. | def route_table(self) -> Optional['outputs.RouteTableResponse']:
return pulumi.get(self, "route_table") | [
"def get_routing_table(self):\n return self.routing_table",
"def route_table_id(self):\n return self._route_table_id",
"def route_table_id(self) -> str:\n return pulumi.get(self, \"route_table_id\")",
"def table_ref(self):\n return self._table_ref",
"def table(self):\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An array of service endpoint policies. | def service_endpoint_policies(self) -> Optional[Sequence['outputs.ServiceEndpointPolicyResponse']]:
return pulumi.get(self, "service_endpoint_policies") | [
"def get_policies():\r\n policy = policies.values()\r\n return policy",
"def policies(self):\n return self._policies",
"def list_policies() -> List:\n return [\n policies_v0.__name__,\n policies_v1.__name__,\n policies_v2.__name__,\n policies_v3.__name__,\n ]",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the specified subnet by virtual network and resource group. | def get_subnet(expand: Optional[str] = None,
resource_group_name: Optional[str] = None,
subnet_name: Optional[str] = None,
virtual_network_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSubnetResult:
__args__ = dict... | [
"def _get_cspf_group_subnet(self):\n return self.__cspf_group_subnet",
"def get_subnet(self, name_or_id, filters=None):\n if not filters:\n filters = {}\n return self.network.find_subnet(\n name_or_id=name_or_id, ignore_missing=True, **filters\n )",
"def subnet(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detuning envelope for e>f DRAG. | def detuning_envelope_ef(t, args):
anharms = args['anharms']
couplings = args['couplings']
e = args['e']
g = args['g']
couplings = [c/g for c in couplings]
coeff = (couplings[e-1]**2 \
- (anharms[e+2]**2/anharms[e-1]**2) \
* couplings[e+1]) / (4*anharms[e+2])
... | [
"def elevator(self, value):\n if value < -1.0:\n value = -1.0\n elif value > 1.0:\n value = 1.0\n\n self.fdmexec.GetFCS().SetDeCmd(value)",
"def vert_extrude(self, u, d='up', Q='self'):\n s = \"::: extruding function %s :::\" % d\n print_text(s, cls=self)\n if t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a user from the admins. | def admins_remove(request):
if len(models.User.admins()) > 1:
username = request.params['remove']
user = models.User.get_by_username(username)
user.admin = False
return httpexceptions.HTTPSeeOther(
location=request.route_url('admin_admins')) | [
"def delete_user(self):\n User.users_list.remove(self)",
"def removeadmin_user(uid):\n pass",
"def delete_user(self):\n\n \tUser.user_list.remove(self)",
"def delete_user(self):\n User.Users_list.remove(self)",
"def delete_user(self):\n\n User.user_list.remove(self)",
"def delet... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes a user with all their group memberships and annotations. Raises UserDeletionError when deletion fails with the appropriate error message. | def delete_user(request, user):
if models.Group.created_by(user).count() > 0:
raise UserDeletionError('Cannot delete user who is a group creator.')
user.groups = []
query = _all_user_annotations_query(request, user)
annotations = es_helpers.scan(client=request.es.conn, query={'query': query})... | [
"def delete_user(request, user):\n\n if models.Group.created_by(request.db, user).count() > 0:\n raise UserDeletionError('Cannot delete user who is a group creator.')\n\n user.groups = []\n\n query = _all_user_annotations_query(request, user)\n annotations = es_helpers.scan(client=request.es.conn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query matching all annotations (shared and private) owned by user. | def _all_user_annotations_query(request, user):
userid = util.user.userid_from_username(user.username, request)
return {
'filtered': {
'filter': {'term': {'user': userid.lower()}},
'query': {'match_all': {}}
}
} | [
"def query_for_users_annotations(userid):\n return {\n \"query\": {\n \"filtered\": {\n \"filter\": {\n \"bool\": {\n \"must\": [{\"term\": {\"user\": userid.lower()}}]\n }\n }\n }\n }\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Precision at n measure is the number of instances where the any crowd's answer occur within ranker's firs n choices | def arrau_precision_n(test_scores, num_true, all_candidates, punctuation_ids, ns):
precisions = []
for i in range(ns):
precision = 0
for k, item in enumerate(test_scores):
ranks = len(item) - rankdata(item, method='ordinal').astype(int)
#precision += min(1, len(set(ranks[... | [
"def precision_n(test_scores, num_true, n):\n precisions = []\n for i in range(n):\n precision = 0\n for k, item in enumerate(test_scores):\n ranks = len(item) - rankdata(item, method='ordinal').astype(int)\n precision += min(1, len(set(ranks[:i+1]) & set(range(num_true[k])... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Precision at n measure is the number of instances where the any crowd's answer occur within ranker's firs n choices | def precision_n(test_scores, num_true, n):
precisions = []
for i in range(n):
precision = 0
for k, item in enumerate(test_scores):
ranks = len(item) - rankdata(item, method='ordinal').astype(int)
precision += min(1, len(set(ranks[:i+1]) & set(range(num_true[k]))))
... | [
"def arrau_precision_n(test_scores, num_true, all_candidates, punctuation_ids, ns):\n precisions = []\n for i in range(ns):\n precision = 0\n for k, item in enumerate(test_scores):\n ranks = len(item) - rankdata(item, method='ordinal').astype(int)\n #precision += min(1, len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method copies an existing Excel file and creates a duplicate to preserve the quality of the original. | def make_wb_copy():
shutil.copy(full_target_file_name, path_name + copied_file_name) # copy the file
| [
"def backup_imported_questionnaire():\n import_folder=\"./Import\"\n if (not os.path.exists(import_folder)):\n os.makedirs(import_folder)\n shutil.copy(self.excel_file,\"./Import/RM_{}_{}_{}.xlsx\".format(self.country_name,self.emco_year,datetime.datetime.now().strfti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method removes empty rows from the Excel file in order to help cohesively merge the different sheets. | def parse_rows(wb, merged_ws):
number_of_sheets = len(wb.worksheets) - 9 # Number of sheets
for sheet_number in range(1, 1 + number_of_sheets): # parse through each sheet
sheet = wb["%s%s" % (sheet_number, "월")] #... | [
"def remowe_first_sheet(self):\r\n self.output_file.remove_sheet(self.output_file.get_sheet_by_name('Sheet'))\r\n self.output_sheets = self.output_file.get_sheet_names()",
"def strip_trailing_rows(self):\n\n rows = list()\n strip_mode = True\n for rownum, row in enumerate(revers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |