query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
True ZODB was connected. | def is_connected(self) -> bool:
return hasattr(_app_ctx_stack.top, "zodb_connection") | [
"def connected(self) -> bool:\n with self.engine.connect() as conn:\n result = conn.execute(\"SELECT 1 AS is_alive\")\n return bool(result.fetchone()[0] > 0)",
"def is_connected(self):\n if self.connected and self.connack_rec:\n return 1\n return 0",
"def is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the current transfer counts for the current connection | def transfers(self):
return _app_ctx_stack.top.zodb_connection.getTransferCounts() | [
"def getTotalCount(self):\n return self.__total_connections",
"def get_counts(self):\n count = self.aio.read()\n return count",
"def connection_count(self):\n connlist = qnetwork.connections(self.connection, self.credentials)\n per_node = {}\n for node_data in connlist.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads input log file, parses for x,y pose data and calls a plot function. | def logplot(in_dir, fname, xlim, ylim, title):
with open(in_dir + fname,'r') as logfile:
lf_lines = logfile.readlines()
traj_x = []
traj_y = []
for row in lf_lines:
if row[:4] == 'pose':
#print(float(row[10:-2]))
tup = row[7:]
sep_pos = tup.find(' ,... | [
"def plot(self, log_dir):\n if not os.path.isfile(log_dir):\n raise Exception('Please ensure that you enter log file path using \\'-l\\'')\n\n df = pd.read_csv(log_dir)\n headers = list(df)[1:]\n x_axis = list(df)[0]\n df.plot(x=x_axis, y=headers, grid=True, style='-')\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a key hexed from random bytes at the given length for crypto. | def GenerateRandomHexKey(length=_RANDOM_BYTE_LENGTH):
# After encoded in hex, the length doubles.
return os.urandom(length).encode('hex') | [
"def get_random_key(key_len: int = 16) -> bytes:\n return bytes(random.randint(0, 255) for _ in range(key_len))",
"def gen_random_key(length=16):\n alphabet = ('abcdefghijklmnopqrstuvwxyz'\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n '0123456789+/')\n return ''.join([alp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a secret key for the user and creates it on demand. | def GetSecretKey(cls, user_id):
uid = hashlib.sha256(str(user_id)).hexdigest()
entity = ndb.Key(cls, uid).get()
if not entity:
entity = cls(id=uid, secret_key=GenerateRandomHexKey())
entity.put()
return entity.secret_key | [
"def CreateUserSecret(user):\r\n secret = base64.b32encode(os.urandom(_SECRET_BYTES))\r\n secrets.PutSecret(_SecretName(user), secret)\r\n DisplayUserSecret(user)",
"def create(self):\n id_access_secretkey = uuid.uuid4()\n id_webuser = Base.logged_id_webuser or None\n keys = Token().genera... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode the tree representation into a list representation. | def to_list(self):
root = self.label
if len(self.children) > 0:
children = [c.to_list() for c in self.children]
else:
children = []
return [root, [children]] | [
"def aslist(self):\n return [tree.copy() for tree in self.trees()]",
"def tree_to_list(self: object) -> list:\n visit_order: list = []\n root: BinaryTreeNode = self.get_root()\n \n def traverse_tree(node: BinaryTreeNode) -> Union['traverse_tree', None]:\n if node:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the set of labels in the tree. | def labels_set(self):
if len(self.children) == 0:
return {self.label}
else:
children_labels = set()
for c in self.children:
children_labels = children_labels | c.labels_set()
return set([self.label]) | children_labels | [
"def labels(self):\n return set([n.taxon.label for n in self._tree.leaf_nodes()])",
"def tree_get_labels_contains(self):\n ret = {*[]}\n for node in PostOrderIter(self):\n ret.add(node.node_label)\n return ret;",
"def node_labels(self):\n return frozenset(record[0] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test empty metadata as produced by TaskWrapper. | def test_empty_metadata(self):
self.include_metadata = True
self.include_work_dir_outputs = False
self.job_wrapper.metadata_line = ' '
# Empty metadata command do not touch command line.
expected_command = _surround_command("%s; return_code=$?; cd '%s'" % (MOCK_COMMAND_LINE, self... | [
"def test_empty_metadata(self):\n self.include_metadata = True\n self.include_work_dir_outputs = False\n self.job_wrapper.metadata_line = \" \"\n # Empty metadata command do not touch command line.\n expected_command = self._surround_command(MOCK_COMMAND_LINE, f\"; cd '{self.job_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Should mark the import as error, and write an error for the missing columns | def test_missing_columns(self):
file = SimpleUploadedFile(
"test.csv",
b"msisdn,messaging consent,edd year,edd month,baby dob year,"
b"baby dob month,baby dob day\n",
)
form = MomConnectImportForm(
data={"source": "MomConnect Import"}, files={"file... | [
"def test_missing_column_raises(self, csv_missing_fields_in_header):\n missing_df = pd.read_csv(csv_missing_fields_in_header)\n with pytest.raises(pandera.errors.SchemaError):\n crowsetta.formats.seq.generic.GenericSeqSchema.validate(missing_df)",
"def testTooFewColumnNames(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
research_consent should have a valid value | def test_invalid_research_consent(self):
file = SimpleUploadedFile(
"test.csv",
b"msisdn,facility code,id type,id number,messaging consent,"
b"research_consent,edd year,edd month,edd day,baby dob year,"
b"baby dob month,baby dob day\n"
b"+27820001001,1... | [
"def test_research_consent_default(self):\n file = SimpleUploadedFile(\n \"test.csv\",\n b\"msisdn,facility code,id type,id number,messaging consent,\"\n b\"research_consent,edd year,edd month,edd day,baby dob year,\"\n b\"baby dob month,baby dob day\\n\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
research_consent should default to False | def test_research_consent_default(self):
file = SimpleUploadedFile(
"test.csv",
b"msisdn,facility code,id type,id number,messaging consent,"
b"research_consent,edd year,edd month,edd day,baby dob year,"
b"baby dob month,baby dob day\n"
b"+27820001001,1... | [
"def consent(self):\n self._consent = None\n if ClinicConsent.objects.filter(subject_identifier=self.subject_identifier):\n self._consent = ClinicConsent.objects.get(subject_identifier=self.subject_identifier)\n return self._consent",
"def can_search_assessments_offered(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
previous_optout should have a valid value | def test_invalid_previous_optout(self):
file = SimpleUploadedFile(
"test.csv",
b"msisdn,facility code,id type,id number,messaging consent,"
b"previous_optout,edd year,edd month,edd day,baby dob year,"
b"baby dob month,baby dob day\n"
b"+27820001001,123... | [
"def testoptdone(self):\r\n assert self.data.optdone\r\n target_e, target_g, target_s = self.data.geotargets\r\n value_e, value_g, value_s = self.data.geovalues[-1]\r\n converged = (value_e < target_e and value_g < target_g) or (value_g < target_g and value_s < target_s)\r\n asser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dob is required for none id type | def test_idtype_dob(self):
file = SimpleUploadedFile(
"test.csv",
b"msisdn,facility code,id type,messaging consent,edd year,edd month,"
b"edd day,baby dob year,baby dob month,baby dob day\n"
b"+27820001001,123456,none,true,2021,2,3,,,\n",
)
form = ... | [
"def validate_dob(self):\n try:\n form = \"%Y-%m-%d\"\n t = datetime.strptime(self.dob, form)\n except ValueError:\n self.reason += \"Invalid date of birth format\"",
"def test_dob_field(self):\n dob_field = self.record.find('field[@name=\\'dob\\']')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dob should be a valid date | def test_invalid_dob(self):
file = SimpleUploadedFile(
"test.csv",
b"msisdn,facility code,id type,messaging consent,edd year,edd month,"
b"edd day,dob year,dob month,dob day,baby dob year,baby dob month,"
b"baby dob day\n"
b"+27820001001,123456,none,tr... | [
"def validate_dob(self):\n try:\n form = \"%Y-%m-%d\"\n t = datetime.strptime(self.dob, form)\n except ValueError:\n self.reason += \"Invalid date of birth format\"",
"def test_dob_field(self):\n dob_field = self.record.find('field[@name=\\'dob\\']')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ping all running nodes | def rosnode_ping_all(verbose=False):
master = rosnode.rosgraph.Master(rosnode.ID)
try:
state = master.getSystemState()
except rosnode.socket.error:
raise rosnode.ROSNodeIOException("Unable to communicate with master!")
nodes = []
for s in state:
for t, l in s:
no... | [
"def pingAll(self):\n self.net.pingAll()",
"def wait_for_all_nodes_online(self):\n nodes = self._clusterutil.list_nodes()\n funcs_list = list()\n args_list = list()\n for node in nodes:\n funcs_list.append(self.wait_for_node_online)\n args_list.append([node... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a semihidden routine for cleaning up stale node registration information on the ROS Master. The intent is to remove this method once Master TTLs are properly implemented. | def rosnode_cleanup():
pinged, unpinged = rosnode_ping_all()
if unpinged:
master = rosnode.rosgraph.Master(rosnode.ID)
rosnode.cleanup_master_blacklist(master, unpinged)
return pinged, unpinged | [
"def clear_registered_nodes(self):\n self.__nodes.clear()\n self.__names.clear()\n self.__aliases.clear()",
"def cleanup_cluster(self, cluster):\n self.log.info(\"removing xdcr/nodes settings\")\n rest = RestConnection(cluster.get_master_node())\n rest.remove_all_replicat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read randomaccess file on positions given as unicode string | def ra_unicode_read(fh, start, end):
tmp_pos = fh.tell()
fh.seek(0)
buf = u""
iter_fh = (line.decode('utf-8') for line in fh)
for line in iter_fh:
line_len = len(line)
# .. recalibrate start/end ...
if line_len < start:
start = start - line_len
if en... | [
"def testReadlineUTF16(self):\n test_path = self._GetTestFilePath(['another_file.utf16'])\n self._SkipIfPathNotExists(test_path)\n\n test_os_path_spec = path_spec_factory.Factory.NewPathSpec(\n definitions.TYPE_INDICATOR_OS, location=test_path)\n file_object = resolver.Resolver.OpenFileObject(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens a second and waits till a client connects. Then sends the map updates till the client disconnects. Start over. | def run(self):
while not self.setup() and self.running:
pass
while self.running:
# Create a byte array to receive the computed maps
mapb = bytearray(self.MAP_SIZE_PIXELS * self.MAP_SIZE_PIXELS)
# Get final map
self.slam.getmap(mapb)
... | [
"def run(self):\r\n self.client.connect()\r\n self.client.run()",
"def start_online():\n Client(580, 580, ip='116.203.85.179', port=5081).start()",
"def __auto_mode(self):\n while True:\n # establish connection\n while True:\n if self.android_api.is_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
installs packages using aptdcon (waits for apt to be free) | def aptdcon_install(packages: Iterable, delete_debs=True):
packages = sorted(set(packages))
print(f"Installing {' '.join(packages)}")
packages_in_quotes = (f'"{p}"' for p in packages)
command = ('aptdcon', '--hide-terminal', '--install', *packages_in_quotes)
# https://askubuntu.com/questions/132059/how-... | [
"def apt_install(pkgs):\n return run([\"apt-get\", \"install\", \"-y\"] + list(pkgs))",
"def apt(packages):\n return sudo(\"apt-get install -y -q \" + packages)",
"def apt_install(*pkgs):\n run('sudo apt-get install -q %s' % ' '.join(pkgs))",
"def apt_get(*packages):\n sudo('apt-get -y -f install %s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check for common worthless features that preclude the need for any further processing. If UA string is not worthless, process against normalizing regexes. Some client User Agent strings such as Antivirus services add file version information that is of no use outside the application itself. Remove such information to p... | def normalize(self):
normalized = self.all_details.get('normalized', '')
if normalized:
return normalized
if self.is_digit():
self.all_details['normalized'] = 'Numeric'
elif self.is_uuid():
self.all_details['normalized'] = 'UUID'
elif self.is_... | [
"def _deduplicate_user_agent(user_agent: str) -> str:\n # Split around \";\" > Strip whitespaces > Store as dict keys (ensure unicity) > format back as string\n # Order is implicitly preserved by dictionary structure (see https://stackoverflow.com/a/53657523).\n return \"; \".join({key.strip(): None for ke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add data to secondary_client details | def supplement_secondary_client_data(self, app_idx):
data = {
'name': app_idx.pretty_name(),
'version': app_idx.version(),
'type': 'generic',
}
self.client.secondary_client.update(data)
try:
self.all_details['client']['secondary_client'].up... | [
"def client_details(self, value):\n self._client_details = value",
"def __set_client_detail(self):\r\n ClientDetail = self.client.factory.create('ClientDetail')\r\n ClientDetail.AccountNumber = self.config_obj.account_number\r\n ClientDetail.MeterNumber = self.config_obj.meter_number\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the UA for client information using the Client parsers | def parse_client(self) -> None:
if self.client:
return
app_idx = ApplicationIDExtractor(self.user_agent)
app_id = app_idx.extract().get('app_id', '')
for Parser in self.CLIENT_PARSERS:
parser = Parser(
self.user_agent,
self.ua_has... | [
"def parse_ua(self, user_agent, max_length=800):\n if len(user_agent) > max_length:\n raise RuntimeError(\"User Agent string length ({}) longer \"\n \"than the allowed {} chars\"\n .format(len(user_agent), max_length))\n formatted_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the UA for Device information using the Device or Bot parsers | def parse_device(self) -> None:
if self.device or self.skip_device_detection:
return
for Parser in self.DEVICE_PARSERS:
parser = Parser(
self.user_agent,
self.ua_hash,
self.ua_spaceless,
self.VERSION_TRUNCATION,
... | [
"def parse_device_info(self, info_string):\n device = {}\n block_list = [\"[\\x1b[0;\", \"removed\"]\n if not any(keyword in info_string for keyword in block_list):\n try:\n device_position = info_string.index(\"Device\")\n except ValueError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the UA for bot information using the Bot parser | def parse_bot(self) -> None:
if not self.skip_bot_detection and not self.bot:
self.bot = Bot(
self.user_agent,
self.ua_hash,
self.ua_spaceless,
self.VERSION_TRUNCATION,
).parse()
self.all_details['bot'] = self.bo... | [
"def get_ua():\n url_ua = 'http://www.useragentstring.com/pages/useragentstring.php?name=All'\n print('get ua list from web...')\n opener = spider_origin()\n body = opener.open(url_ua).read()\n soup = BeautifulSoup(body, 'html.parser')\n tag_lis = soup.find_all('li')\n uas = []\n for tag in tag_lis:\n ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the UA for Operating System information using the OS parser | def parse_os(self) -> None:
if not self.os:
self.os = OS(
self.user_agent,
self.ua_hash,
self.ua_spaceless,
self.VERSION_TRUNCATION,
).parse()
self.all_details['os'] = self.os.ua_data | [
"def ua_details(self):\n user_agent = self.user_agent\n os = ''\n os_version = ''\n browser = ''\n platform = ''\n vendor = ''\n if user_agent:\n if 'iPad' in user_agent:\n os = 'iOS'\n platform = 'iPad'\n vendo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
All detected feature phones running Android are more likely a smartphone | def android_feature_phone(self) -> bool:
try:
return self.device.dtype() == 'feature phone' and self.os.family() == 'Android'
except AttributeError:
pass
return False | [
"def detectSmartphone(self):\r\n return self.__isIphone \\\r\n or self.__isAndroidPhone \\\r\n or self.__isTierIphone \\\r\n or self.detectS60OssBrowser() \\\r\n or self.detectSymbianOS() \\\r\n or self.detectWindowsMobile() \\\r\n or self.det... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devices running Kylo or Espital TV Browsers are assumed to be a TV | def is_television(self) -> bool:
if self.client_name() in ('Kylo', 'Espial TV Browser'):
return True
return TV_FRAGMENT.search(self.user_agent) is not None | [
"def detectGoogleTV(self):\r\n return UAgentInfo.deviceGoogleTV in self.__userAgent",
"def device_class(self):\n return DEVICE_CLASS_TV",
"def ua_details(self):\n user_agent = self.user_agent\n os = ''\n os_version = ''\n browser = ''\n platform = ''\n ven... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load default storage factory. | def storage_factory(self):
return load_or_import_from_config(
'SIPSTORE_FILE_STORAGE_FACTORY', app=self.app
) | [
"def initialize_storage():\n pass",
"def _storage_init(self):\n if not self._storage.initialized:\n self._storage.init(self._module._py3_wrapper)",
"def default_storage(request):\n return import_by_path(settings.MESSAGE_STORAGE)(request)",
"def create_storage(uri: Optional[str] = None)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the archive location URI. | def archive_location(self):
name = self.app.config['SIPSTORE_ARCHIVER_LOCATION_NAME']
return Location.query.filter_by(name=name).one().uri | [
"def get_archive_path(self):\r\n pass",
"def build_absolute_uri(self, location=None):\n if not location:\n location = self.get_full_path()\n if not absolute_http_url_re.match(location):\n current_uri = '%s://%s%s' % (self.is_secure() and 'https' or 'http',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the message token/channel, then call the bas class constructor. | def _construct_message(self):
self.message = {"token": self._auth, "channel": self.channel}
super()._construct_message() | [
"def __init__(self, message):\n\n self.message = message",
"def __init__(self, buf=None, *args, **kwargs):\n super(Message, self).__init__(buf, *args, **kwargs)\n self.__initialized = True",
"def __init__(self, token):\n self.token = token\n self.bot = telegram.Bot(token)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a binary tree with the given elements | def build_tree(elements):
print("Building tree with these elements:",elements)
root = BinarySearchTreeNode(elements[0])
for i in range(1, len(elements)):
root.add_child(elements[i])
return root | [
"def make_tree(arr):\n\n for i in range(len(arr)):\n arr, val = mid(arr)\n\n if i == 0: \n binary = BinaryNode(val)\n\n else:\n binary.insert(val)\n\n return binary",
"def build_from_list(cls, inlist=[]):\n\n tree = BinaryTree()\n for x in inlist:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Eğer prop_value ayarlanan değerlerde değilse, o değerlere dönüştürülür | def on_prop_value2(self, *args):
prop_value = self.prop_value
# Eğer prop_value ayarlanan tipte değilse, o tipe dönüştür
if not (type(prop_value) is self.prop_type):
try:
# Eğer gelen değer "5.8" şeklindeyse ve int'e dönüştürülmek isteniyorsa,
# önce... | [
"def prepare_value(self, prop, value):\n return value",
"def get_property_value(self, property, db):\n if property == 'resultTime':\n return self.get_time()\n elif property == 'wallTime':\n return self.wallTime\n elif proper... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to extract all gateways from data file. Takes data from file "cells_abcd.csv". Returns | def get_all_gateways():
gateways: List[Gateway] = []
with open("/home/agora/Documents/Popular_paths/Data/saint_foy/saint_foy/cells_abcd.csv", "r") as f:
csv_reader = csv.reader(f, delimiter = ';')
for line in csv_reader:
if line[0] == 'ci': # Title line
pass
... | [
"def cost_to_all_cells(filename, src_waypoint, output_filename):\r\n \r\n # Load and display the level.\r\n level = load_level(filename)\r\n #show_level(level)\r\n\r\n # Retrieve the source coordinates from the level.\r\n src = level['waypoints'][src_waypoint]\r\n \r\n # Calculate the cost t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Host to which the HTTP server should bind. | def host(self):
return '127.0.0.1' | [
"def server_bind(self):\n SocketServer.TCPServer.server_bind(self)\n host, port = self.socket.getsockname()[:2]\n self.server_name = socket.getfqdn(host)\n self.server_port = port",
"def host(self):\r\n return \":\".join([self.hostname, str(self.port)])",
"def get_host(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a "list" file of one string per line. | def read_list(fname):
with open(fname) as handle:
items = [line.strip() for line in handle]
return items | [
"def list_parse(name_list):\n\n if name_list and name_list[0] == '@':\n value = name_list[1:]\n if not os.path.exists(value):\n log.warning('The file %s does not exist' % value)\n return\n try:\n return [v.strip() for v in open(value, 'r').readlines()]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate genelevel mutational statistics from a table of mutations. | def make_lof_table(data_table, my_genes, my_samples, summary_func):
table_header = ["Gene"] + my_samples + [
"Missense:Benign", "Missense:Possibly", "Missense:Probably",
"MissenseNA", "Indel", "Nonsense", "Frameshift", "Splice-site",
"Synonymous"]
table_records = []
gs_lookup = grou... | [
"def lof_sig_scores(table, samples, verbose=True):\n mut_probdam = 'Missense:Probably'\n mut_syn = 'Synonymous'\n mut_trunc = ['Nonsense', 'Frameshift', 'Splice-site']\n mut_other = ['Missense:Benign', 'Missense:Possibly', 'MissenseNA', 'Indel']\n mut_all = [mut_probdam, mut_syn] + mut_trunc + mut_ot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Group relevant fields in a data table by gene and sample. | def group_data_by_gs(data_table):
gene_data = collections.defaultdict(lambda: collections.defaultdict(list))
for _idx, row in data_table.iterrows():
samp = row['sample']
gene = row['gene']
gene_data[gene][samp].append({
'muttype': row['type'].strip(),
'normalized'... | [
"def test_group_by_fields(self):\r\n t = [\r\n ['#sample', 'loc', 'age', 'mal'],\r\n ['a', 'US', '5', 'n'],\r\n ['b', 'US', '10', 'n'],\r\n ['c', 'Mal', '5', 'y'],\r\n ['d', 'Mal', '10', 'n'],\r\n ['e', 'Mal', '5', 'y'],\r\n ]\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate LOF mutation burden scores for genes in the processed table. | def lof_sig_scores(table, samples, verbose=True):
mut_probdam = 'Missense:Probably'
mut_syn = 'Synonymous'
mut_trunc = ['Nonsense', 'Frameshift', 'Splice-site']
mut_other = ['Missense:Benign', 'Missense:Possibly', 'MissenseNA', 'Indel']
mut_all = [mut_probdam, mut_syn] + mut_trunc + mut_other
#... | [
"def mutate_all(self):\n for indiv in self.individuals[self.elite_count:]:\n self.update_mutation_factor()\n new_genotype = indiv.genotype\n for j in range(self.num_vars):\n if random.random() < self.mut_rate:\n offset = (2*(random.random()-0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Permute a mutation data table's gene, sample and NMAF columns. | def permute_table(dtable):
shuffle_field(dtable, 'gene')
shuffle_field(dtable, 'sample')
shuffle_field(dtable, 'Normalized')
if 'Filler' in dtable:
del dtable['Filler'] | [
"def shuffle_columns(gene):\n import numpy as np\n return np.random.permutation(gene.tolist())",
"def new_mutation_data_from_genemap(self, genes_mutatedPatient):\n\t\tpatientID_mutatedGenes = dict([(ty, dict()) for ty in self.tumor_tys])\n\t\tpatients = set()\n\t\tfor t in self.tumor_tys:\n\t\t\tfor g, vari... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shuffle a column of a pandas DataFrame inplace. | def shuffle_field(dframe, field):
column = list(dframe[field])
random.shuffle(column)
dframe[field] = column | [
"def randomize(df):\n df=df.iloc[np.random.permutation(df.index)].reset_index(drop=True)\n return df",
"def shuffle_columns(gene):\n import numpy as np\n return np.random.permutation(gene.tolist())",
"def shuffle_data(df, arrays, random_state=None):\n df = df.sample(frac=1, replace=False, random_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check working and education age, as well as agebased death rates | def age_check(self):
# check working status
if 15 <= float(self.age) < 59:
if self.work_status == 0:
self.work_status = 1
num_labor_list[self.hh_id] += 1
labor_list.append(self.unique_id)
if self.work_status == 1 and self.uni... | [
"def test_age_with_death(self):\n peep = Person(\"@I01@\")\n peep.set_date(\"7 AUG 1988\", \"birth\")\n peep.set_date(\"7 SEP 1990\", \"death\")\n\n self.assertEqual(2, peep.get_age())",
"def test_age_no_death(self):\n peep = Person(\"@I01@\")\n birth_date = datetime.strp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Small chance of giving birth every step if female, married, and under 55 | def birth_check(self):
if random.random() < 0.00017: # 0.0121, or 1.21%, is the yearly birth rate.
birth_flag_list.append(1)
# This makes the birth rate for every 5 days (73 'checks' a year) 0.00017%,
# because 1 - 0.0121 = 0.9879; 98.79% is the chance of not giving birt... | [
"def gopher_births(population):\n birth_rate = random.randint(BIRTH_RATE_MIN, BIRTH_RATE_MAX) # Birth rate between min and max\n return int(population * birth_rate / 100) # Calculate and return births",
"def test_check_birth(self):\n herb = Fa.Herbivore(weight=60, age=20)\n herb2 = Fa.Herbivor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Describes remigration process and probability following outmigration | def re_migration_check(self):
if self.hh_id == 'Migrated':
self.mig_years += 1/73
prob = math.exp(-1.2 + 0.06 * float(self.age) - 0.08 * self.mig_years)
re_mig_prob = prob / (prob + 1)
if random.random() < re_mig_prob: # re-migration occurs
... | [
"def test_stat_probability_of_migration(self, initial_statistic_cell):\n number_of_runs = len(self.herbivores)\n prob_migration = self.stat_cell.herbi_list[0].probability_of_migration()\n # The probability is the same for all animals, because they does not\n # age, nor get hungry.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves human agent to assigned point according to frequency | def move_to_point(self, destination, frequency):
# index 0 represents x, index 1 represents y
if frequency > 1:
x_towards = int(round((destination[0] - current_position[0]) / frequency))
if x_towards > 1:
x_towards -= 1
y_towards = int(round((des... | [
"def __move(self):\n\n # Make sure that the freq is set correctly\n self.__pwm.set_freq(50)\n\n self.__pwm.turn_on()\n\n # Allow time for transistion\n time.sleep(0.5)\n\n # Turn the servo off to reduce current and noise\n self.__pwm.turn_off()",
"def first_trackin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that updates the db's tables (SpreadsheetsWorksheetsFeed) | def refresh_tables(self):
if self.key is None:
raise AttributeError('Can not refresh tables on uninitialised db')
self.tables = self.client.ssclient.GetWorksheetsFeed(self.key) | [
"def update_updated_data_sqlite_db(self, table_name: str):\n # go through indicators and get updated data in dataframe\n print('start downloading queries')\n df = self.__get_updated_data(table_name)\n print('api download completed')\n\n # get list of sql queries to insert to sqlit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new spreadsheetdatabase identified by name, containing data from file ob/string | def create(self, name, data=',,,'):
if not name or not isinstance(name, basestring):
raise ValueError('Require textual, non-zero-length name')
if not isinstance(data, file):
from cStringIO import StringIO
data = StringIO(data)
clen = len(data.read())
... | [
"def add_xlsx_database(dbname, infile, size):\n tmp = tempfile.NamedTemporaryFile(suffix=\".xlsx\")\n tmp.write(infile.read())\n tmp.seek(0)\n try:\n wb = openpyxl.load_workbook(tmp.name)\n check_quota(size=size)\n with DbSaver() as saver:\n dbname = saver.set_name(dbname... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the product identifier for the given review Returns null if there is no review with the given identifier | def getProductId(self, reviewId):
res = self.get_metadata_item_by_review_id(reviewId, self.prod_index)
if res is None:
return -1
return res | [
"def get_review(review_id):\n\n reviewID = storage.get('Review', review_id)\n\n if reviewID is None:\n abort(404)\n return jsonify(reviewID.to_dict())",
"def review_restaurant_name(review):\n return review[0]",
"def review_by_id(review_id):\n obj = storage.get(\"Review\", review_id)\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the score for a given review Returns 1 if there is no review with the given identifier | def getReviewScore(self, reviewId):
res = self.get_metadata_item_by_review_id(reviewId, self.score_index)
if res is None:
return -1
return res | [
"def review_rating(review):\n return review[1]",
"def get_review(reviews, userId, BusinessId):\n reviews = reviews[(reviews['business_id'] == BusinessId) & (reviews['user_id'] == userId)]\n\n if reviews.empty:\n return np.nan\n elif len(reviews) > 1:\n return float(reviews['stars'].max()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the numerator for the helpfulness of a given review Returns 1 if there is no review with the given identifier | def getReviewHelpfulnessNumerator(self, reviewId):
res = self.get_metadata_item_by_review_id(reviewId, self.helpfulness_index)
if res is None:
return -1
return res.split('/')[0] | [
"def review_rating(review):\n return review[1]",
"def getReviewHelpfulnessDenominator(self, reviewId):\n res = self.get_metadata_item_by_review_id(reviewId, self.helpfulness_index)\n if res is None:\n return -1\n return res.split('/')[1]",
"def _getRating(self):\n try:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the denominator for the helpfulness of a given review Returns 1 if there is no review with the given identifier | def getReviewHelpfulnessDenominator(self, reviewId):
res = self.get_metadata_item_by_review_id(reviewId, self.helpfulness_index)
if res is None:
return -1
return res.split('/')[1] | [
"def getReviewHelpfulnessNumerator(self, reviewId):\n res = self.get_metadata_item_by_review_id(reviewId, self.helpfulness_index)\n if res is None:\n return -1\n return res.split('/')[0]",
"def review_rating(review):\n return review[1]",
"def get_review(reviews, userId, Busine... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a series of integers of the form id1, freq1, id2, freq2, ... such that idn is the nth review containing the given token and freqn is the number of times that the token appears in review idn Note that the integers should be sorted by id Returns an empty Tuple if there are no reviews containing this token | def getReviewsWithToken(self, token):
wordid = self.find_word_in_dictionary(token)
# word is not in the dictionary
if wordid == -1:
print("Token is not in the dictionary")
return 0
with open(self.doc_to_words_path, 'rb') as bin:
tup = []
... | [
"def find_n_reviews(x, n, review_books_df):\n asin_1 = x['asin_1']\n asin_2 = x['asin_2']\n\n overall_reviews_1 = review_books_df.query('asin == @asin_1').sort_values(\n 'unixReviewTime').iloc[0:(n+1)].overall.tolist()\n overall_reviews_2 = review_books_df.query('asin == @asin_2').sort_values(\n '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the ids of the reviews for a given product identifier Note that the integers returned should be sorted by id Returns an empty Tuple if there are no reviews for this product | def getProductReviews(self, productId):
res = self.get_metadata_item_by_product_id(productId, self.review_id_index)
if res is None:
return ()
return tuple(sorted(res)) | [
"def __extract_review_ids(self, soup):\n try:\n id_tags = soup.find_all('div', attrs={'class':'review', 'itemprop':'reviews'})\n review_ids = [int(re.sub('review_', '', tag.get('id'))) for tag in id_tags]\n return review_ids\n except:\n raise",
"def review... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try encoding a value that was not present during fitting | def test_labelencoder_unseen():
df = cudf.Series(np.random.choice(10, (10,)))
le = LabelEncoder().fit(df)
assert le._fitted
with pytest.raises(KeyError):
le.transform(cudf.Series([-1])) | [
"def test_fitting_error_col_None():\n fs = OneHotEncoder()\n with pytest.raises(AttributeError):\n fs.transform(data)",
"def test_encode_missing(self):\n df = pd.DataFrame({'x2':['a','a',np.NaN]})\n df_transformed_correct = pd.DataFrame({'x2_OHE_a':[1,1,0],'x2_OHE_nan':[0,0,1]})\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the set of instructions to install the runtime specific components from a build in a previous stage. Examples ```python o = openmpi(...) Stage0 += o Stage1 += o.runtime() ``` | def runtime(self, _from='0'):
instructions = []
instructions.append(comment('OpenMPI'))
instructions.append(packages(ospackages=self.__runtime_ospackages))
instructions.append(copy(_from=_from, src=self.prefix,
dest=self.prefix))
if self.ldconfig:... | [
"def runtime(self, _from='0'):\n self.rt += comment('UCX')\n self.rt += packages(ospackages=self.__runtime_ospackages)\n self.rt += self.__bb.runtime(_from=_from)\n return str(self.rt)",
"def create_runtime(self, runtime):\n logger.info(\"Extracting preinstalled Python modules f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remplis la liste dans l'ordre d'un parcours en largeur. | def parcour_largeur(self, liste=[]):
if self not in liste:
liste.append(self)
for successeur in self.tache.successeur:
liste = successeur.sommet.parcour_largeur(liste)
return liste | [
"def affichage_boucle(Liste): \n for elmt in Liste : #pour chaque ÈlÈment dans la liste\n print elmt #afficher la liste",
"def affichage_boucle_liste_dans_list(Liste): \n cpt_l=0 #compteur de sous-listes\n for sousliste in Liste : #pour chaque sous liste dans la liste principale :\n cpt_l+=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create input parameter matrix (nrows,npars) for nrows simulations and npars parameters with bounds bl and bu Input nrows of simulations bl (npars) lower bounds of parameters bu (npars) upper bounds of parameters Optional Input distname initial sampling ditribution (not implemented yet, takes uniform distribution) Outpu... | def _SampleInputMatrix(nrows, bl, bu, distname='randomUniform'):
npars = len(bl)
x = np.zeros((nrows,npars))
bound = bu-bl
for i in range(nrows):
# x[i,:]= bl + DistSelector([0.0,1.0,npars],distname='randomUniform')*bound # only used in full Vhoeys-framework
x[i,:]= bl + np.random.rand(1... | [
"def setparams (w=None, delay=None, tau=None, low=None, high=None):\n global firststep\n for n in nclist: \n if w is not None: n.weight[0] = w if useHHCell else -w # neg wts are needed for ArtCell (neg driving force for HHCell)\n if delay is not None: n.delay=delay\n if firststep or (low and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a new point in a simplex Input func function to minimize s 2Darray, the sorted simplex in order of increasing function values sf 1Darray, function values in increasing order bl (npars) lower bounds of parameters bu (npars) upper bounds of parameters mask (npars) mask to include (1) or exclude (0) parameter fro... | def _cce(func, s, sf, bl, bu, mask, icall, maxn, alpha, beta, maxit, printit):
"""
List of local variables
sb(.) = the best point of the simplex
sw(.) = the worst point of the simplex
w2(.) = the second worst point of the simplex
fw = function value of the worst point
ce(.) = the ... | [
"def simplex_step(A,b,c,B,N):\n\n c_B = array([c[i] for i in B])\n c_N = array([c[i] for i in N])\n\n A_N = transpose( array([A[:,i] for i in N]) )\n A_B = transpose( array([A[:,i] for i in B]) )\n\n A_B_inv = inv(A_B)\n lambda_ = dot(transpose(c_B), A_B_inv)\n \n r_N = transpose( dot(lambda... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ShuffledComplexEvolution algorithm for function minimization | def sce(func, x0, bl, bu,
mask=None,
maxn=1000, kstop=10, pcento=0.0001,
ngs=2, npg=None, nps=None, nspl=None, mings=None,
peps=0.001, seed=None, iniflg=True,
alpha=0.8, beta=0.45, maxit=False, printit=2,
outf=False, outhist=False, outcall=False,
restart=False, re... | [
"def run_qae_optimization(training_states, n_repetitions, exact=no_noise, noisy=gate_error):\n result_list = []\n def proxy(params, training_states, n_repetitions, exact=no_noise, noisy=gate_error):\n \"\"\"Embedded function version\n \"\"\"\n input_list = fix_list(params, all_param_array... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a revocation registry instance from a definition. | def from_definition(
cls, revoc_reg_def: dict, public_def: bool
) -> "RevocationRegistry":
rev_reg = None
reg_id = revoc_reg_def["id"]
tails_location = revoc_reg_def["value"]["tailsLocation"]
issuer_did_match = re.match(r"^.*?([^:]*):3:CL:.*", revoc_reg_def["credDefId"])
... | [
"async def create_and_store_revocation_registry(\n self,\n origin_did: str,\n cred_def_id: str,\n revoc_def_type: str,\n tag: str,\n max_cred_num: int,\n tails_base_path: str,\n ) -> Tuple[str, str, str]:",
"async def create_and_store_revocation_registry(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accessor for the credential definition ID. | def cred_def_id(self) -> str:
return self._cred_def_id | [
"def credential_id(self):\n return self._credential_id",
"async def get_cred_def_id(controller, credential_def):\n\n # TODO Determine what is funky here?!\n cred_def_id = credential_def[\"credential_definition_id\"]\n if not cred_def_id:\n raise HTTPException(\n status_code=404,\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accessor for the issuer DID. | def issuer_did(self) -> str:
return self._issuer_did | [
"def issuer(self) -> str:\n return self._issuer",
"def certificate_issuer_id(self):\n return self._certificate_issuer_id",
"def did(self):\n return DID(self._id)",
"def issuer(self):\r\n return str(self.connection.get_peer_certificate().get_issuer())",
"def issuer_name(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accessor for the maximum number of issued credentials. | def max_creds(self) -> int:
return self._max_creds | [
"def get_max_attempts(self):\n\t\treturn self._max_attempts",
"def maxloginattempts(self) :\n\t\ttry :\n\t\t\treturn self._maxloginattempts\n\t\texcept Exception as e:\n\t\t\traise e",
"def max_attempts(self):\n return 1",
"def credentialsCount(self):\n return self._credentials_count",
"def ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accessor for the revocation registry ID. | def registry_id(self) -> str:
return self._registry_id | [
"def _rId(self):\n return self.__rId",
"async def get_revocation_registry(self, rev_reg_id: str):\n\n return await self.admin_GET(f\"{self.base_url}/registry/{rev_reg_id}\")",
"def get_id(self, refobj):\n return cmds.getAttr(\"%s.identifier\" % refobj)",
"def get_id(self) -> str:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accessor for the tails file hash. | def tails_hash(self) -> str:
return self._tails_hash | [
"def getHash(self):\n f = StringIO()\n self.saveBinary(f)\n m = md5.new()\n m.update(f.getvalue())\n return m.hexdigest()",
"def hash(self):\n return self.dotpath and stringhash(self.dotpath) or None",
"def get_contents_hash(self):\n md5 = hashlib.md5()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accessor for the tails file local path. | def tails_local_path(self) -> str:
return self._tails_local_path | [
"def local_path(self) -> str:\n if self.spec.local_path[-1] == '/':\n return self.spec.local_path\n else:\n return self.spec.local_path + '/'",
"def getpath(self):\r\n return LocalPath(self._path)",
"async def get_or_fetch_local_tails_path(self):\n tails_file_path = self.get_receiv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setter for the tails file local path. | def tails_local_path(self, new_path: str):
self._tails_local_path = new_path | [
"def tails_local_path(self) -> str:\n return self._tails_local_path",
"def local_file(self, value):\n self._local_file = value",
"def __set_full_path_of_file(self, value):\n self.full_path_of_file = value",
"def local_storage_path(self, val):\n self._local_storage_path = val",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accessor for the tails file public URI. | def tails_public_uri(self) -> str:
return self._tails_public_uri | [
"def file_url(self):\n return self._file_url",
"def get_uri(self):\r\n return self.uri",
"def url(self):\n return self.storage.url_for(self.filedata)",
"def uri(self):\n return self._uri",
"def public_url(self):\n return self._public_url",
"def file_address(self) -> str:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setter for the tails file public URI. | def tails_public_uri(self, new_uri: str):
self._tails_public_uri = new_uri | [
"def tails_public_uri(self) -> str:\n return self._tails_public_uri",
"def set_uri(self, uri):\r\n self.uri = uri",
"def set_uri(self, uri):\n self.__uri = uri",
"def file_address(self) -> str:\n return f\"http://{self._address}:{self._port}/{self.path.name}\"",
"def uri(self, ur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if the tails file exists locally. | def has_local_tails_file(self) -> bool:
tails_file_path = Path(self.get_receiving_tails_local_path())
return tails_file_path.is_file() | [
"def is_file_exists(self):\n pass",
"def file_exist() -> bool:\n pass",
"def check_file_existence(self, filename):\n try:\n for sample in TimeoutingSampler(\n config.GAHOOKS_TIMEOUT, 1, self.machine.fs.exists,\n \"/tmp/%s\" % filename\n ):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch the tails file from the public URI. | async def retrieve_tails(self):
if not self._tails_public_uri:
raise RevocationError("Tails file public URI is empty")
LOGGER.info(
"Downloading the tails file for the revocation registry: %s",
self.registry_id,
)
tails_file_path = Path(self.get_rece... | [
"def _download_file(url):\n return requests.get(url, stream=True)",
"async def get_or_fetch_local_tails_path(self):\n tails_file_path = self.get_receiving_tails_local_path()\n if Path(tails_file_path).is_file():\n return tails_file_path\n return await self.retrieve_tails()",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the local tails path, retrieving from the remote if necessary. | async def get_or_fetch_local_tails_path(self):
tails_file_path = self.get_receiving_tails_local_path()
if Path(tails_file_path).is_file():
return tails_file_path
return await self.retrieve_tails() | [
"def tails_local_path(self) -> str:\n return self._tails_local_path",
"def _remote_path(self):\n return self._remote_dir",
"def remote_path(self) -> str:\n if self.spec.remote_path[-1] == '/':\n return self.spec.remote_path\n else:\n return self.spec.remote_path + '/'",
"def remo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot a histogram of the envelope delays for all stations combined. | def plot_hist(delays):
fig = plt.figure()
ax = fig.add_subplot(111)
alldelays = []
for _s in delays.keys():
alldelays += delays[_s]
if len(alldelays) > 0:
n, bins, patches = ax.hist(alldelays, bins=np.arange(0, 30, 0.5),
color='green', histtype='bar... | [
"def plot_spectrums_overlapping(\n self, energies_dict: dict, title:str,\n figsize: tuple = (16,12)\n ) -> None:\n \n plt.figure(figsize=figsize)\n plt.title(title)\n for key in energies_dict.keys():\n spectre, bins = np.histogram(energies_dict[key],range = (0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the playlist when user open new playlist. Clear container stored old playlist. | def init_container(self):
self.current_playlist = [] | [
"def new_playlist_command(self):\n self.parent.song_object_list.clear()\n self.display_data(self.parent.song_object_list)\n self.playlist_select.set(\"Working Playlist\")",
"def clear_playlists():\n global kk_slider_queue\n global aircheck_queue\n global aircheck_playlist_created\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The playlist is preprocessed, the song is converted to a specified ID, and if the id does not exist, the dictionary is updated. | def playlist_processing(self, playlist):
with open(self.vocab2id_file, 'rb') as f:
vocab = cPickle.load(f)
vocabulary_size = len(vocab)
self.stable_size = 14130
word2id = dict(zip(vocab.keys(), vocab.values()))
for i in playlist:
self.current_playlist.app... | [
"def _update_songs(self):\n\n songs = self._api.get_all_songs()\n self._library = {}\n self._songs = {}\n\n for song in songs:\n self._songs[song['id']] = song \n if song['artist'] == \"\":\n song['artist'] = \"unknown\"\n if song['album... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reshape a batch by using current sequence of playlist. The elements of playlist much be lager than (self.task_size+2) | def fetch_batch(self, playlist):
y_output = []
y_out = []
x_out = []
x_array = np.arange(self.seq_length, dtype=float).reshape(1, self.seq_length)
data = self.playlist_processing(playlist)
playlist = self.standardization(data)
# manage a batch table for next step... | [
"def rearrange_batch(batch):\n return list(zip(*batch))",
"def prepare_batches(data, batch_size):\n shuffle(data)\n batches = []\n\n for k in range(0, len(data), batch_size):\n batch = data[k:k + batch_size]\n inputs, item_ids, labels = zip(*batch)\n\n inputs = pad_sequence(inputs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the stationary distribution Returns | def compute_stationary_distribution(self):
return self.mc.stationary_distributions | [
"def stationary_distribution(self):\n P = self.markov_transition()\n N = len(P)\n I = np.identity(N)\n A = P.T - I # get right-kernel\n pi = null_space(A)\n pi = pi / sum(pi)\n pi = [float(item) for item in pi]\n return pi",
"def stationary_distribution(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
method which blocks execution until the lens completes its move | def wait_focus_move(self):
import time
T0 = time.time()
finished = False
aborted = False
while not finished:
T1 = time.time()
the_status = self.status
if not the_status['F_move'] or the_status['FD_endStop']:
finished = True... | [
"def wait_for_move(self):\n while not self.move_done():\n #Empirical testing suggests that we can't poll more often than 1ms\n time.sleep(0.001)",
"def __wait_for_move(self, verbose=False):\r\n res = self.__wait_for([(2, 1), (2, 2), (2, 3)], verbose=verbose)\r\n if res[1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
try to connect over the serial port to the device at self.addr. If this is None it will try to guess the address | def connect(self):
import serial
if self.addr == None:
self.addr = self.get_EFu_addr()
self.ser = serial.Serial(self.addr, 115200, timeout=1)
if self.ser.isOpen():
print('Opened port: {}'.format(self.addr))
else:
raise RuntimeError('Failed t... | [
"def connect(self):\n # open serial port\n try:\n #device = self.get_device_name(self.serial_number)\n device = \"/dev/ttyAMA0\"\n self.serial.port = device\n # Set RTS line to low logic level\n self.serial.rts = False\n self.serial.ope... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
go to the lens' min focus distance | def go_minFD(self):
response = self.send_lens_cmd(['06', '00', '00', '00'], fast_mode=True)
self.wait_focus_move() | [
"def set_focus_distance(self,distance):\n\t\tself.outbox.add(\"focusdist\",distance)\n\t\tself.focus_distance = distance",
"def refocus(opt_model):\n osp = opt_model['optical_spec']\n\n fld = osp['fov'].fields[0] # assumed to be the axial field\n wvl = osp['wvls'].central_wvl\n\n df_ray, ray_op, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize an instance of the class 'UpperClass'. 'UpperClass' then creates instances of all nested functions, including all controls, data, limits, and time states. For more details, see structure of 'UpperClass' within pyign.functions.classes. | def _init_upper_class(*args):
upper_class = ucl()
return upper_class | [
"def setup_class(self):\n class SubCosmology(Cosmology):\n\n H0 = Parameter(unit=u.km / u.s / u.Mpc)\n Tcmb0 = Parameter(unit=u.K)\n\n def __init__(self, H0, Tcmb0=0*u.K, name=None, meta=None):\n super().__init__(name=name, meta=meta)\n self._H0 ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Access protected class data and edit the element lengths of time_delay. | def __set_time_elements(*args):
args[0].TimeState.delay_elements = args[1]
args[0].TimeState.set_delay_elements() | [
"def update_stay_time(self):\n # It would not be better to simply self.stay_time = self.get_length() ??\n self.stay_time = self.get_length()",
"def delays(self):\n return self.__delays",
"def __init__(self, delay=0):\n self.delay = delay",
"def setDelays(self, d):\n raise NotImp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Access protected class data of the system Abort State. This approach is a secure method to access saved system state values. If an abort is tripped, the test stand control system will automatically enter 'Safe' mode and valve configuration Arguments | def getAbortState(*args):
return args[0].Controls.AbortState.abort_state | [
"def check_abort(*args):\n if getAbortState(args[0]) == 1:\n args[0].Controls.ValveState.valve_state = [0] * args[0].Controls.valve_number\n args[0].Controls.IgnitorState.ignitor_state = 0\n return args[0].Controls.ValveState.valve_state, args[0].Controls.IgnitorState.ignitor_state",
"def _rec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Access protected class data to evaluate the delays in an automated firing sequence. The returned value representation is an array ranging containing real time delays. This approach is a secure method to access saved system state values. Arguments | def getTimeDelay(*args):
return args[0].TimeState.TimeDelay.time_delay | [
"def delays(self):\n return self.__delays",
"def getDelay(self, *args):\n return _libsbml.Event_getDelay(self, *args)",
"def net_delay_data(self):\n return self._net_delay_data",
"def _dt(self) -> List[float]:\n assert self._state == HitObject.STATE.PASSED\n # TODO\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if any sensor is out of limit range, if out of bounds is detected, abort is tripped and system enters 'Safe' mode. Arguments | def check_limits(*args):
if getNanny(args[0]) == 1:
if np.sum(pt_index(args[0])) != 0:
setAbortState(args[0], 1)
elif np.sum(tc_index(args[0])) != 0:
setAbortState(args[0], 1)
elif np.sum(lc_index(args[0])) != 0:
setAbortState(args[0], 1)
return args[0... | [
"def check_limits(self):\n\n #Find the relative position of each leg vs. its \"zero\" position\n relpos = self.fixed_plate - self.fixed_plate_zero\n\n for leg in range(3):\n #Check that the leg is within allowable \"safe zone\"\n #Use the position of the leg (relative to 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check Abort State, if abort has been tripped, all valves and the ignitor are set to 'Safe' state until system is restarted. Arguments | def check_abort(*args):
if getAbortState(args[0]) == 1:
args[0].Controls.ValveState.valve_state = [0] * args[0].Controls.valve_number
args[0].Controls.IgnitorState.ignitor_state = 0
return args[0].Controls.ValveState.valve_state, args[0].Controls.IgnitorState.ignitor_state | [
"def raise_if_aborted():\n if abort_all.is_set():\n raise AbortAllException(\"abort_all event has been set\")",
"def set_abort_flag(self):\r\n self.abort_flag = True",
"def getAbortState(*args):\n return args[0].Controls.AbortState.abort_state",
"def check_limits(*args):\n if getNanny(a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check GO State. If all three panels are NOT a 'GO', ignitor state is set to 'Safe' mode. Arguments | def check_go(*args):
if np.sum(getGOState(args[0]))!= 3:
args[0].Controls.IgnitorState.ignitor_state = 0
return args[0].Controls.IgnitorState.ignitor_state | [
"def check_stage(self):\n\n #Initalize target and goal_stage to stage1 values\n target = 3\n goal_stage = 2\n\n # Set target and goal_stage if current stage is not 1\n if self.current_stage == 2:\n target = 7\n goal_stage = 3\n elif self.current_stage == 3:\n ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the manual switch circuit is active to determine Time Regime. If the switch panel is active, this sets the Time Regime to a '0' or 'Initialize Regime'. Arguments | def check_manual_circuit(*args):
if args[0] == 0:
setTimeRegime(1)
elif args[0] == 1:
setTimeRegime(0) | [
"def set_autoswitch_hysteresis_timer(self, time):\n\n raise NotImplementedError",
"def set_system_time(self):\n self.switch_to_GPS()\n # if self.is_fix():\n # settime = Popen(\"sudo date -u\", shell=True).wait()\n # return True\n return False",
"def timeboard_se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load a renderer by name. First look by name among builtin renderers, then among renderers provided by plugins, and then try interpreting rname as a path. | def load_renderer(rname: str, config: ConfigManager) -> Renderer:
try:
return getattr(importlib.import_module('plasTeX.Renderers.'+rname), 'Renderer')()
except ImportError:
pass
for plugin in config['general']['plugins'] or []:
try:
return getattr(importlib.import_module... | [
"def importRenderer(rdrname):\n\n try:\n return importlib.import_module(\"renderers.\" + rdrname)\n except ImportError:\n errmsg = translate(\"Render\",\"Error importing renderer '{}'\\n\").format(rdrname)\n FreeCAD.Console.PrintError(errmsg)\n return None",
"def get(self, render... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Irá parsear um arquivo .sql com as queries necessárias e irá retornar um dicionário contendo o nome da query no arquivo, como chave e a query especificamente como valor. | def parse_queries(file_name):
pattern = r"--[ ]?name:[ ]?([a-z\-_]*)\n([a-zA-Z _.,0-9\()\n'-:@=\"?>=<\[\]\$%]*);"
queries = {}
with open(file_name, 'r') as f:
file_queries = f.read()
matches = findall(pattern, file_queries, M | I)
for query in matches:
query_name, sql = ... | [
"def __load_query(self, name):\n try:\n with open(QUERIES_DIR + name + '.sql') as query:\n query_string = query.read()\n return query_string\n except IOError as e:\n if e.errno == errno.ENOENT:\n return name\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The Register of Surveys | def surveys():
# lists the views and mimetypes available for a Survey Register (a generic Register)
views_mimetypes = model_classes_functions.get_classes_views_mimetypes() \
.get('http://purl.org/linked-data/registry#Register')
try:
view, mime_format = LDAPI.get_valid_view_and_mimetype(
... | [
"def initialize_survey(self, **kwargs):",
"def start_survey():\n title=satisfaction_survey.title\n instructions = satisfaction_survey.instructions\n # session['responses'] =[]\n return render_template(\"instructions.html\", survey_title=title, instructions=instructions)",
"def _publish_survey(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Will return a list of sequences and structures with the most common structure first in the list. (rest or list unordered!) Don't care which of the sequences for the "winning" sequence that is reported since the are not ranked amongst them self. | def common(structs):
frequency = {}
v = 0
indx = 0
result = []
tmp_list = [] #lookup the seq for the structures,dont care which winner seq
key = []
for block in structs:
tmp_list.extend(block)
p = tuple(block[-1])
if frequency.__contains__(p): #everytime struct ... | [
"def get_most_common(self, lst):\n data = Counter(lst)\n mc = data.most_common(2) \n #if len(mc) == 1 or (mc[0][1] != (mc[1][1])):\n # return mc[0][0]\n #return \"AMB\"\n return data.most_common(1)[0][0]",
"def _calculate_secondary_structure(seq, window):\n # STRUCTS = {0: \"Helix\", 1: \"Tu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a structure block into a block containing the sequens and structures lines. | def structParser(lines):
blc = 0 #blank line counter
bc = 0 #block counter
struct = []
record = False
for line in lines:
if len(line) == 1:
blc +=1
record = False
if blc == 2:
blc = 0
bc +=1
record = True
if record ... | [
"def parseBlock():\n global SCOPE\n SCOPE.push(\"BLOCK\")",
"def _parse_block(self):\n self.parse_state = 'block'\n # only variable declarations are currently implemented so this works.\n if self._current_tk_type() == 'TK_VAR':\n self._parse_declarations()\n self._pars... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
__age_categorize converts integer age to categorical label [14] | def __age_categorize(self, age):
# Baby age category - most at risk, highest categorical denomination
if age <= 4:
self.__age = 4
# Youth age category - second most at risk
elif 5 <= age <= 14:
self.__age = 3
# Adult age category - least at risk
... | [
"def age_categories(x):\n if x == 0:\n cat = 0\n elif x <= 18:\n cat = 1\n elif x <= 60:\n cat = 2\n else:\n cat = 3\n return cat",
"def get_age_label(age):\n # return 0 if int(age) < 30 else 1 if int(age) < 60 else 2\n return 0 if int(age) < 30 else 1 if int(age) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This functions requires RNAplot from the Vienna RNA Package It takes the input sequence and bracketed sequence to genenrate the graph in svg format. | def graphRep(input_seq, bracket_str):
proc = subprocess.Popen(['RNAplot', '-o', 'svg'], stdin=subprocess.PIPE,)
input_str = input_seq + '\n' + bracket_str;
proc.communicate(input_str)
file = open('rna.svg', 'r')
graph_svg = markdown(file.read())
return graph_svg | [
"def create_svg( output_file_path, min_speed, max_speed, power=100):\n import svgwrite\n document_width = 100\n document_height = 150\n document_start = (10, 10)\n document_unit = \"mm\"\n \n laser_line_width = 0.001\n laser_line_width_unit = \"mm\"\n \n laser_line = str(laser_line_wid... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Concept = Run of particle time | def run(self):
self.tick = self.tick + 1
print 'Particle tick=:', self.tick | [
"def method_compute_timestep(self):",
"def evaluate(self, time) -> float:\n ...",
"def timestep(self):\n #Determine the time to simulate by calling a function to return the lowest half time\n timeToSimulate = self.findLowestRemaining()\n #Add the simulated time to a total time variab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
used to test an array of requirements | def meetsreqs(request, requirements):
for requirement in requirements:
if requirement(request) == False:
return False
return True | [
"def types_matching_data_requirements(given_types, required_types):\n matches = True\n i = 0\n\n for item in given_types:\n #print (\"item: %r req: %r\" % (item, required_types[i]))\n\n if item not in required_types[i]:\n matches = False\n i += 1\n return matches",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a filter for requests by domain name | def filter_domain(name):
def wrapped(request):
""" Function used to filter request
"""
if request.environ.get('HTTP_HOST'):
url = request.environ['HTTP_HOST']
else:
url = request.environ['SERVER_NAME']
if url.lower() == name.lower():
return... | [
"def filter_by_domain( data, domains = [] ):\n\n domains = set( map( lambda d: d.replace('www.', ''), domains))\n\n if domains:\n data = filter( lambda d: '{uri.netloc}'.format( uri= urlparse( d['url'] ) ).replace('www.', '') in domains, data )\n else:\n print 'No domains given for filtering... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
NOOP function. Does nothing! | def noop(*args, **kwargs):
pass | [
"def _dummy(self):\n pass",
"def noop_decorator(func):\n return func",
"def empty_callback(*args):\n pass",
"def f_noarg(self) :\n pass",
"def noop(author: str, arg: str, svc: Any) -> str:\n return 'Nothing to be done.'",
"def dummy_func(*args, **kwargs):\r\n pass",
"def nu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
specify the error handler | def error(self, func):
self.error_handler = func
return func | [
"def error(self, handler):\n pass",
"def _set_error_handler(self):\n if self.on_error:\n error_step = self.context.root.path_to_step(self.on_error)\n self._on_error_handler = error_step.run",
"def handle_err(self):\r\n pass",
"def handle_err(self):\n pass",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
decorate the function and bind the route to it | def wrapped(func):
self.routes.append((path, {
'regex': re.compile('^' + re.sub(self._part_matcher,'(.*?)',path) + '$'),
'function':func,
'reqs':req,
'kwargs':kwargs,
'parts':parts_info,
'generate':generate
... | [
"def route(self, path, **params):\n\n def decorate(func):\n \"\"\"\n A function returned as a object in load time,\n which set route to given url along with decorated function.\n \"\"\"\n from aha.dispatch.router import get_router\n r = get_ro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |