query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Get text templates for sms | def get_templates(self, template_name, **kwargs):
text = render_template("{template}.txt".format(template=template_name), **kwargs)
return text | [
"def generate_text(contents, template, is_sms = True):\n \n max_chars = 160 - len(SMS_SALUTATION)\n \n contents = replace_dollar_signs(contents)\n sms = template.substitute(contents)\n \n if is_sms:\n if len(sms) > max_chars:\n template_length = len(sms)-get_content_length(con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new IR Learned Code from a IRCode and a IRCodeInfo. | def __init__(self, code, codeInfo):
self.Code = code #IRCode
self.CodeInfo = codeInfo #IRCodeInfo
| [
"def make_il(self, il_code, symbol_table, c):\n raise NotImplementedError",
"def PyCode_New(space, argcount, nlocals, stacksize, flags,\n w_code, w_consts, w_names, w_varnames, w_freevars, w_cellvars,\n w_filename, w_funcname, firstlineno, w_lnotab):\n return PyCode(space,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transmits a repeat of a previously transmitted code. his must be called within the gap period after transmitting the original code. This is required for codes that use seperate sequences for the code and the repeat identifier. | def transmitRepeat(self):
try:
result = PhidgetLibrary.getDll().CPhidgetIR_TransmitRepeat(self.handle)
except RuntimeError:
raise
if result > 0:
raise PhidgetException(result) | [
"def send_next_packet():\n #\"global\" required here to be able to read and write to SEQUENCE \n global SEQUENCE\n data = sys.stdin.buffer.read(DATA_SIZE)\n if (len(data) > 0):\n rtt_start = time.time()\n msg_obj = {\"sequence\": SEQUENCE, \"data\": b64encode(data).decode(), \"ack\": True, \"eof\": False}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads raw IR data. | def readRaw(self):
count = 2048 #this is as big as the library buffer, so the user doesn't have to poll as often
buf = [] #buffer that will hold the read raw data and be returned to the user
dataPtr = (c_int * count)()
length = c_int()
length.value = count;
... | [
"def readFile(self):\n self.__rawFileInst = ThermoRawReaderUtility( self.__filePath)\n self.__maxSpecNumber = self.__rawFileInst.call_GetNumSpectra()\n self.__transitionData = self.__getTransitionDataFromInstrumentMethod()\n self.__uniqParentIonsTuple = self.__makeUniqParentIonsTuple()\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the last code that was recieved. | def getLastCode(self):
codePtr = (c_ubyte * IR_MAX_CODE_DATA_LENGTH)(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
dataLength = c_int(IR_MAX_CODE_DATA_LENGTH)
bitCount = c_int()
try:
result = PhidgetLibrary.getDll().CPhidgetIR_getLastCode(self.handle, codePtr, byref(dataLen... | [
"def get_latest_code(self):\n return self.code.latest()",
"def get_last_event(self):\n return self.last_event_code",
"def __last_code(self) -> Optional[VMCode]:\n if len(self.__vm_codes) > 0:\n return self.__vm_codes[-1]\n else:\n return None",
"def getLastLea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the last code the was learned. | def getLastLearnedCode(self):
codePtr = (c_ubyte * IR_MAX_CODE_DATA_LENGTH)()
dataLength = c_int(IR_MAX_CODE_DATA_LENGTH)
codeInfo = CPhidgetIR_CodeInfo()
try:
result = PhidgetLibrary.getDll().CPhidgetIR_getLastLearnedCode(self.handle, codePtr, byref(dataLength... | [
"def get_latest_code(self):\n return self.code.latest()",
"def getLastCode(self):\r\n codePtr = (c_ubyte * IR_MAX_CODE_DATA_LENGTH)(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)\r\n dataLength = c_int(IR_MAX_CODE_DATA_LENGTH)\r\n bitCount = c_int()\r\n \r\n try:\r\n result ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create new nodes from files only (no CSV), and add media. These objects will have a title (derived from filename), and a configdefined Islandora model, content type, and status. Media use is derived from config as well. | def create_from_files():
logging.info('"Create from files" task started using config file %s', args.config)
file_dir_path = config['input_dir']
files = os.listdir(file_dir_path)
for file_name in files:
filename_without_extension = os.path.splitext(file_name)[0]
if len(filename_without_e... | [
"def create_node(file_class=None, url=None, title=None, license=None, copyright_holder=None,\n description=\"\", as_file=False, author=None, source_id=None):\n\n assert url, \"URL not provided to create_node\"\n if not source_id:\n source_id=url\n mime = examine_file(url) # TEMP_FILE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function that places a hyperlink within a paragraph object. | def add_hyperlink(paragraph, url, text, color, underline):
# This gets access to the document.xml.rels file and gets a new relation id value
part = paragraph.part
r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)
# Create the w:hyperlink tag and add nee... | [
"def add_hyperlink(paragraph, url, text):\r\n\r\n # This gets access to the document.xml.rels file and gets a new relation id value\r\n part = paragraph.part\r\n r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)\r\n\r\n # Create the w:hyperlink tag and add need... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the video info from the list file | def _parse_list(self):
frame_path = [x.strip().split(' ') for x in open(self._image_set)]
self.video_list = [VideoRecord(item) for item in frame_path]
print('Sequence number/ video number:%d' % (len(self.video_list))) | [
"def parse():\n all_players = list(FACE_IMAGE_LOCATIONS.keys())\n face_encodings = VideoParser.__load_faces_encodings(all_players)\n player_occurrences = VideoParser.__get_player_occurrences(all_players, face_encodings)\n VideoParser.__save_parsed_video(player_occurrences)",
"def parse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count device properties in tango database | def _count_device_properties(self):
db_info = self.db_instance.get_info()
db_info_list = db_info.split("\n")
num_properties = 0
for line in db_info_list:
if "Device properties defined" in line:
num_properties = line.split("=")[-1]
... | [
"def get_number_of_devices(self):\n return self.num_of_devices",
"def get_number_of_devices(self):\n return self.drt_manager.get_number_of_devices()",
"def get_count():\n _check_init()\n return _pypm.CountDevices()",
"def test_properties_count_get(self):\n pass",
"def test_initial_device_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test initial device properties added to the tangoDB | def test_initial_device_properties(self):
expected_count = 1 # model_key property already present in db
self.assertEquals(expected_count, self._count_device_properties()) | [
"def test_store_property_after_reconnecting_to_the_device():",
"def test_write_device_properties_to_db(self):\n initial_count = self._count_device_properties()\n tango_sim_generator.write_device_properties_to_db(\n self.sim_device.name(), self.expected_model, self.db_instance\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing whether the device properties in the model are added to the tangoDB | def test_write_device_properties_to_db(self):
initial_count = self._count_device_properties()
tango_sim_generator.write_device_properties_to_db(
self.sim_device.name(), self.expected_model, self.db_instance
)
num_expected_properties = len(self.expected_mod... | [
"def test_initial_device_properties(self):\n expected_count = 1 # model_key property already present in db\n self.assertEquals(expected_count, self._count_device_properties())",
"def test_model_class_db_usermodel_has_core_propertes(self):\n properties =['public_id', 'password', 'last... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing whether the attributes quantities in the model are added to the TANGO sim device controller | def test_sim_control_attribute_list(self):
implemented_attr = helper_module.SIM_CONTROL_ADDITIONAL_IMPLEMENTED_ATTR
control_attributes = test_sim_test_interface.control_attributes(
self.expected_model
)
attributes = set(self.sim_control_device.get_attribut... | [
"def test_attributes(self):\n a = self.model()\n for attr in self.attributes:\n self.assertTrue(hasattr(a, attr), 'Has attribute %s' % attr)",
"def test_device_attribute_list(self):\n # test that the attributes from the running simulated device match the attributes\n # from ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setting the desired attribute value for the device's attribute from the simulator controller device | def test_sim_control_device_attribute_change(self):
desired_attribute_name = "temperature"
input_value = 100.0
self.sim_control_device.attribute_name = self.attr_name_enum_labels.index(
desired_attribute_name
)
self.sim_control_device.pause_act... | [
"def set_device(self, device):",
"def setdevice(device):\n\tcurrent.device = device",
"def set_attribute(self, attr, value):\n logger.debug(\"SET ATTRIBUTE {} to {}\".format(attr, value))",
"def __setattr__(self,name,value):\n try:\n TreeNode(self.part_dict[name]+self.head,self.tree).... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing whether the attributes specified in the POGO generated XMI file are added to the TANGO device. | def test_device_attribute_list(self):
# First testing that the attribute with data format "IMAGE" is in the device.
attribute_name = "image1"
device_attributes = set(self.sim_device.get_attribute_list())
self.assertIn(
attribute_name,
device_attributes,
... | [
"def test_device_attribute_list(self):\n # test that the attributes from the running simulated device match the attributes\n # from in the simdd json file\n device_attributes = set(self.sim_device.get_attribute_list())\n default_attributes = helper_module.DEFAULT_TANGO_DEVICE_ATTRIBUTES\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing whether the attributes specified in the fandango generated fgo file are added to the TANGO device. | def test_device_attribute_list(self):
# test that the attributes from the running simulated device match the attributes
# from in the fandango generated file
device_attributes = set(self.sim_device.get_attribute_list())
extra_attr_from_device = set(["NumAttributesNotAdded", "AttributesNo... | [
"def test_device_attribute_list(self):\n # test that the attributes from the running simulated device match the attributes\n # from in the simdd json file\n device_attributes = set(self.sim_device.get_attribute_list())\n default_attributes = helper_module.DEFAULT_TANGO_DEVICE_ATTRIBUTES\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing whether commands from running simulated device match commands from fandango file | def test_device_command_list(self):
actual_device_cmds = self.sim_device.get_command_list()
expected_cmd_list = self.sim_file_parser.get_device_command_metadata().keys()
self.assertEquals(
set(actual_device_cmds),
set(expected_cmd_list),
"The commands specifie... | [
"def _verifyCommand(self):\n for i in range(3):\n rc = self.subdevice.command_test() # Verify command is correct\n if rc is None:\n break",
"def test_device_command_list(self):\n default_cmds = helper_module.DEFAULT_TANGO_DEVICE_COMMANDS\n actual_device_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing whether the attributes specified in the simdd json are added to the TANGO device. | def test_device_attribute_list(self):
# test that the attributes from the running simulated device match the attributes
# from in the simdd json file
device_attributes = set(self.sim_device.get_attribute_list())
default_attributes = helper_module.DEFAULT_TANGO_DEVICE_ATTRIBUTES
r... | [
"def test_device_attribute_list(self):\n # test that the attributes from the running simulated device match the attributes\n # from in the fandango generated file\n device_attributes = set(self.sim_device.get_attribute_list())\n extra_attr_from_device = set([\"NumAttributesNotAdded\", \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing whether commands from running simulated device match commands from simmdd json file | def test_device_command_list(self):
default_cmds = helper_module.DEFAULT_TANGO_DEVICE_COMMANDS
actual_device_cmds = set(self.sim_device.get_command_list()) - default_cmds
expected_cmd_list = self.sim_file_parser.get_device_command_metadata().keys()
self.assertEquals(
actual_d... | [
"def test_device_command_list(self):\n actual_device_cmds = self.sim_device.get_command_list()\n expected_cmd_list = self.sim_file_parser.get_device_command_metadata().keys()\n self.assertEquals(\n set(actual_device_cmds),\n set(expected_cmd_list),\n \"The comma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the TANGO device Init command works correctly. | def test_device_init_command(self):
default_val = 0
self.assertEqual(self.sim_device.integer1, default_val)
# Write to the attribute integer1
self.sim_device.integer1 = 45
self.assertEqual(self.sim_device.integer1, 45)
# Reset the values of the device attributes to defaul... | [
"def test_create_device(self):\n pass",
"def test_create_device1(self):\n pass",
"def setUp(self):\n self.device = FakeReadDevice(\"test\")",
"def test_init(self):\n self.assertEqual(self.device_key, self.factory.device_key)",
"def test_get_device(self):\n pass",
"def te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that you can have multiple sim control devices running. | def test_multiple_sim_control_devices(self):
self.assertGreater(self.sim_control_device1.ping(), 0)
self.assertGreater(self.sim_control_device2.ping(), 0)
self.assertGreater(self.sim_control_device3.ping(), 0) | [
"def test_controller_switches(self):\n for name in self.our_controllers:\n self.start_controller(name)\n self.assertTrue(self.check_state(name, 'running'), \"{} is starting correctly\".format(name))\n time.sleep(1) # process some update() cycles\n self.stop_control... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asynchronously create the TokenInstance | async def create_async(
self,
grant_type: str,
client_sid: str,
client_secret: Union[str, object] = values.unset,
code: Union[str, object] = values.unset,
code_verifier: Union[str, object] = values.unset,
device_code: Union[str, object] = values.unset,
ref... | [
"def create_token(self):\n self._token_id, self.files_endpoint, self.queues_endpoint = \\\n self.token_func()",
"async def _create_auth_async(self) -> Union[uamqp_authentication.JWTTokenAsync, JWTTokenAuthAsync]:\n try:\n # ignore mypy's warning because token_type is Optional\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a description to grammar. Each line is a rule for a | def grammar(description, whitespace=r'\s*'):
G={' ':whitespace}
description = description.replace('\t',' ') # handle tabs in description
for line in split(description,"\n"):
lhs, rhs = split(line,"=>")
alternatives = split(rhs, ' | ')
G[lhs]=tuple(map(split, alternatives))
retur... | [
"def grammar(description, whitespace=r'\\s*'):\n G = {' ': whitespace}\n description = description.replace('\\t', ' ') # no tabs\n for line in split(description, '\\n'):\n lhs, rhs = split(line, ' => ', 1)\n alternatives = split(rhs, ' | ')\n G[lhs] = tuple(map(split, alternatives))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the value of a variable. The variable will be defined in the runtime context of the preprocessor minilanguage. The value is either the result of safely evaluating the value token with `ast.literal_eval`, or the token itself if it cannot be evaluated. | def set(self, identifier, value_token, *, preprocessor=None):
try:
value = ast.literal_eval(value_token)
except (SyntaxError, ValueError):
value = value_token
setattr(self, identifier, value) | [
"def set_value(self, var_value):\n pass",
"def set_variable(self, request, context):\n response = SetVariableResponse()\n value = decode(request.value)\n self._delegator.set_variable(request.component, request.variable, value)\n return response",
"def assign_variable(self, nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Interpret additional tokens if a condition is true. Note This keyword can be written as ``if`` (instead of ``if_``) in the preprocessor directives. | def if_(self, condition_token, keyword_token, *tokens, preprocessor=None):
condition = self._get_token_value(condition_token)
if not isinstance(condition, bool):
raise DoxhooksTypeError(condition, condition_token, "bool")
if condition:
self.interpret(keyword_token, *token... | [
"def test_conditional_instruction(self):\n LEXER.input('if x:')\n self.checks_tokens(['IF', 'ID', 'COL'])\n LEXER.input('else:')\n self.checks_tokens(['ELSE', 'COL'])",
"def __compile_if(self, xml_tree):\n tk = self.__tokenizer\n # 'if'\n SubElement(xml_tree, tk.ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify a context to allow lowercase boolean representations. | def lowercase_booleans(context_class):
context_class._convert_bool_to_str = _convert_to_lowercase_str
return context_class | [
"def startcase_booleans(context_class):\n context_class._convert_bool_to_str = _convert_to_str\n return context_class",
"def _bool_encode(self, d):\n for k, v in d.items():\n if isinstance(v, bool):\n d[k] = str(v).lower()\n \n return d",
"def _normalize(val)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify a context to allow startcase boolean representations. | def startcase_booleans(context_class):
context_class._convert_bool_to_str = _convert_to_str
return context_class | [
"def lowercase_booleans(context_class):\n context_class._convert_bool_to_str = _convert_to_lowercase_str\n return context_class",
"def _enabled_with_ctx(flag: Dict, context: Dict[str, str]) -> bool:\n if not context:\n return False\n\n constraints = flag['constraints']\n\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets kid value to be used in token header for this handler. it must be unique for each handler. | def get_kid(self):
return 'f825ccd5-9b4a-476f-ae12-c1c1ea99e6b2' | [
"def get_kid_from_jwe_header(token: str) -> Optional[str]:\n import base64\n import json\n\n header = token.split(\".\")[0]\n deserialized_header = base64.urlsafe_b64decode(header + \"===\")\n jose_header = json.loads(deserialized_header)\n\n return jose_header.get(\"kid\")",
"def _get_kid(messa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute RHS of modelA at time t | def RHS(y,t):
return np.multiply(A.dot(y),ones-y)-beta*y | [
"def RHS(y,t):\n\n dy = 0 #modify\n return dy",
"def RHSnetFomp(y,t,a,b0,b1,g,k,w):\n dy = fn.rhs_omp(P,y,t,a,b0,b1,g,k,w,2)\n return dy",
"def _model(self, t, theta, period, tmpid):\n template = self.templates[tmpid]\n phase = (t / period - theta[2]) % 1\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Analyze transport processes (model A, model B, linear diffusion) on BarabasiAlbert graphs. Modify input and output as needed. | def transport(input=(None)):
n=100
m=5
G=nx.barabasi_albert_graph(n, m, seed=5)
maxdeg=0
degree_dist=[]
for i in range(0,n):
degree_dist.append(G.degree[i])
if G.degree[i]>maxdeg:
maxdeg=G.degree[i]
j=i
tf,tfa,tfb=10,20,1000
Nt=10000
iarray=Li... | [
"def predict_taskAB(model, samples: List[Dict], tokenizer=None, step_size: int=32, label_tags: Dict=POLARITY_INV, verbose=False):\n print(\"[preds]: predicting on task A+B ...\")\n #model.freeze()\n predicted = [] # List[Dict] for output\n if verbose: \n print(\"sample_size:\", len(samples))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
used to count frequency of results in a list, returning dictionaary | def CountFrequency(my_list):
# Creating an empty dictionary
freq = {}
for item in my_list:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
return freq | [
"def list_frequencies(list_of_items):\n itemfreq = [list_of_items.count(p) for p in list_of_items] \n return dict(zip(list_of_items,itemfreq))",
"def count_list_freq(l):\n freq = {}\n for items in l:\n freq[items] = l.count(items)\n return freq",
"def list_count(l):\n return dict((l.cou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the latest trades that have occured for a specific market. | def public_market_history(self, market_symbol):
return self.get(f'markets/{market_symbol}/trades') | [
"def get_recent_market_data(self, markets: list):\n args = {\n 'symbols': ','.join(markets)\n }\n return self.request('tickers', args=args)",
"def binance_get_trades(market):\r\n market_str = market.split('-')\r\n market = market_str[1] + market_str[0]\r\n trades = api_bin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the balance from your account for a specific currency. | def account_balance(self, currency_symbol):
return self.get(f'balances/{currency_symbol}', auth=True) | [
"def get_balance(self, currency=None):\n if currency:\n return self.__call__('balance', 'getbalance',\n {'currencyname': currency})\n return self.__call__('balance', 'getbalances')",
"def get_balance(self, ticker):\n return self.trading_client.accoun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a query string of name/value pairs. | def _create_query_str(data):
params = []
for name, value in data.items():
params.append(name + '=' + str(value))
return '?' + '&'.join(params) | [
"def _generate_query_string(self):\n \n query_items = {}\n \n for key, val in self.__dict__.iteritems():\n if not key.startswith('_'):\n query_items[key] = val.encode('utf-8')\n \n return urllib.urlencode(query_items)",
"def get_query_params():\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns signed request using the HMAC SHA512 algorithm. | def _sign_request(secret, method, url, timestamp, content_hash=None):
message = f'{timestamp}{url}{method}{content_hash}'
return hmac.new(secret.encode('utf-8'), message.encode('utf-8'), hashlib.sha512).hexdigest() | [
"def _sign_request(api_secret: str, timestamp: int, method: str, path: str,\n body: Union[Dict, str] = \"\", subaccount_id: str = \"\") -> str:\n body = body if body else \"\"\n payload = f\"{timestamp}{method.upper()}{path}{body}{subaccount_id}\"\n message = bytearray(payload, 'utf-8')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort any lists in an IAM JSON policy so that comparison of two policies with identical values but different orders will return true | def sort_json_policy_dict(policy_dict):
... | [
"def test_list_ikepolicy_sort(self):\r\n resources = \"ikepolicies\"\r\n cmd = ikepolicy.ListIKEPolicy(test_cli20.MyApp(sys.stdout), None)\r\n self._test_list_resources(resources, cmd,\r\n sort_key=[\"name\", \"id\"],\r\n sort_di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rainbow movie theater light style chaser animation. | def theaterChaseRainbow(strip, wait_ms=30):
for j in range(256):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i+q, wheel((i+j) % 255))
strip.show()
time.sleep(wait_ms/1000.0)
for i in range(0, strip.numPixels(... | [
"def theaterChaseRainbow(strip, wait_ms=50):\n for j in range(256):\n for q in range(3):\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, wheel((i+j) % 255))\n strip.show()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List png frame files for a video. | def list_pngs(video_title: str) -> list:
path_to_pngs = os.path.join('frames', video_title)
files = os.listdir(path_to_pngs)
png_files = [f for f in files if os.path.splitext(f)[1] == '.png']
png_files = sorted(png_files, key=lambda s: int(s[5:-4]))
return png_files | [
"def videoFrames(filename, framerate=1):\n vid_file = os.path.join(os.path.dirname(os.getcwd()), \"Database\", \"Video\", filename)\n print(vid_file)\n assert os.path.isfile(vid_file), \"Given path is not a valid file\"\n tmpdir = os.path.join(os.getcwd(), \"tmp\")\n subprocess.run(\n [\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that update_blocks creates 10 blocks | def test_update_blocks(path_last_block, path_get_blocks_iterator, mocked_logger):
# Method to test
created_id = BlockchainEthService.update_blocks()
assert Block.objects.count() == 10
assert len(created_id) == 10
mocked_logger.info.assert_called_once_with("10 new blocks created.") | [
"def test_get_n_latest_blocks(self):\n\n latest = 5\n number_of_blocks = 15\n wait_for_block(self.network, 5)\n for validator_id in range(self.network.validators_count()):\n height_counter = latest\n host, public_port, private_port = self.network.api_address(validat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
bind all controls with facade | def bind_controls(self):
self.add_comment_button.Bind(wx.EVT_BUTTON, self.add_comment)
self.del_comment_button.Bind(wx.EVT_BUTTON, self.remove_comment)
self.upload_button.Bind(wx.EVT_BUTTON, self.upload_change)
self.Bind(wx.EVT_CLOSE, self.on_close) | [
"def bind_controls(self):\n self.always_display_check.Bind(wx.EVT_CHECKBOX, self.on_check_display)\n self.ok_button.Bind(wx.EVT_BUTTON, self.on_close)",
"def bindAll(self, *args):\r\n return self._wrap(self.obj)",
"def bind(self):\n super(QtBaseWidgetComponent, self).bind()",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluate the population with respect to input data X and expected output. | def _evaluate(self, X, Y):
# evaluate all networks
#
# evaluations = torch.zeros(self.population_size, device=self.device)
evaluations = torch.zeros(self.population_size, device=self.device)
for i in range(self.population_size):
selected_pheno = self.population[i].cp... | [
"def evaluate_population(self):\n self._ea.evaluation(self.population)",
"def evaluate(self, x, gp, experiment):\n pass",
"def evaluate(self, dataset):\n return self.model.evaluate(dataset.X_val, dataset.y_val)",
"def evaluate(population, context=None):\n for individual in population:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a list of evaluation scores, selects best_rate percentage of individuals by applying one of selection methods passed as parameter | def _selection(self, evaluations, selection, method="truncated", best_rate=0.2):
if selection:
end_range_for_parents = max(1, int(self.population_size * best_rate))
evaluations_sorted = torch.sort(evaluations)
population_sorted = self.population[evaluations_sorted[1]]
... | [
"def best_percentile_selector(train_features, test_features, train_similarity_target, test_similarity_target, regressor):\n\tpercentile_score = 0\n\tpercentiles = [25, 35, 45, 50, 55, 65, 75]\n\t# percentiles = [45]\n\tpercentile_selector = None\n\tpercentile_train_features_selected = None\n\tpercentile_test_featur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given best population applies crossover with given probability, method and parents number | def _crossover(self, best_population, crossover, n_parents=2, method="uniform_swap"):
if crossover:
# randomly select parents
parents_indexes = torch.randint(0, len(best_population), (self.population_size, n_parents),
device=self.device)
... | [
"def crossover(parents, img_shape, n_individuals=8):\r\n new_population = numpy.empty(shape=(n_individuals, \r\n functools.reduce(operator.mul, img_shape)),\r\n dtype=numpy.uint8)\r\n \r\n \"\"\"\r\n Selecting the best previou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dict of reasonable random parameters that can be used to do parameter search. | def random_parameters():
res = dict()
res["population_size"] = random.randrange(2, 21)
res["mutation_prob"] = random.choice([0.02, 0.05, 0.10, 0.20, 0.30, 0.40, 0.50])
res["crossover"] = random.choice([True, False])
res["selection"] = random.choice([True, False])
res["sig... | [
"def get_random_parameters():\n\n # change this dictionary to change the random distribution\n dists = dict(\n embed_size=[100],\n EMBED_HIDDEN_SIZE=[10, 20, 50, 100, 150, 200, 300, 400, 500],\n ACTIVATION=['relu', 'tanh', 'sigmoid'],\n L2 = [0, .01, .001, .0001,0.00001,0.000001,0.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function takes two equal sized sets and returns a set of tupples. Each tuple is made out of the one element of each two starting sets. >>> male={'mgerbil1','mgerbil2','mgerbil3','mgerbil4','mgerbil5'} >>> female={'fgerbil1','fgerbil2','fgerbil3','fgerbil4','fgerbil5'} >>> mating_pairs(male, female) {('mgerbil2', '... | def mating_pairs(male: set, female: set) -> Compoundset:
set_of_pairs=set()
found =True
while found:
if len(male)>0 and len(female)>0:
malegerbil=male.pop()
femalegerbil=female.pop()
pairs=(malegerbil,femalegerbil)
set_of_pairs.add(pairs)
else... | [
"def generate_pairs():\n\td1 = [1,2,3,4,5,6]\n\td2 = [1,2,3,4,5,6]\n\tpairs = []\n\tfor i in d1:\n\t\tfor j in d2:\n\t\t\tpairs.append([i,j])\n\treturn pairs",
"def friend_pairs_and_other_friends(friend_tuple): \n x=friend_tuple[0]\n y=friend_tuple[1]\n def auxfun(w):\n return (frozenset({x,w}),y)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method will update attributes of the model passed by kwargs. | def update(self, **kwargs):
print("Updating model")
print(kwargs)
for key in kwargs:
setattr(self, key, kwargs[key]) | [
"def update_model(self, model_update, **kwargs):\n raise NotImplementedError",
"def _update(self, kwargs):\n\n for attr in kwargs:\n self.ptr[attr] = kwargs[attr]",
"def update(self, model, changedAttributes):\n pass",
"def updateModel(self):\n pass",
"def update(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts features from chunk, concatenates feature_train (onpower_train, offpower_train and duration_train) with new features and retrains feature models. Updates stats attribute. | def train_on_chunk(self, chunk, meter):
# EXTRACT FEATURES:
# find units:
self.__setattr__('units', chunk.columns[0])
# Loading treshold for getting events:
thDelta = getattr(self, 'thDelta')
chunk.index.name = 'date_time'
# To prevent learning many samples at the... | [
"def train_chunk_wise(self, clf, d, current_epoch):\n \n for dataset in d[\"datasets\"]:\n # Loading the dataset\n print(\"Loading data for \",dataset, \" dataset\") \n for building in d[\"datasets\"][dataset]['buildings']:\n # Loading the b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Passes each chunk from mains generator to disaggregate_chunk() and passes the output to _write_disaggregated_chunk_to_datastore() Will have a default implementation in super class. Can be overridden for more simple inmemory disaggregation, or more complex outofcore disaggregation. | def disaggregate(self, mains, output_datastore):
building_path = '/building{}'.format(mains.building())
# only writes one appliance and meter per building
meter_instance = 2
mains_data_location = '{}/elec/meter1'.format(building_path)
#dis_main = pd.DataFrame()
... | [
"def disaggregate_chunk(self, test_mains):\n raise NotImplementedError()",
"def in_memory_rechunk(\n inputs: List[Tuple[core.ChunkKey, xarray.Dataset]],\n target_chunks: Mapping[str, int],\n) -> Iterator[Tuple[core.ChunkKey, xarray.Dataset]]:\n key, dataset = consolidate_chunks(inputs)\n yield from... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks units. Disaggregates "chunk" with MaximumLikelihood algorithm. | def disaggregate_chunk(self, chunk):
# An resistive element has active power equal to apparent power.
# Checking power units.
units = self.__physical_quantity(chunk)
# EVENTS OUT OF THE CHUNK:
# Delta values:
column_name = 'diff_' + units[1]
chunk[column_name] =... | [
"def _determine_units(self, program):\n pass",
"def consume_units(self, units):\n pass",
"def quantizedInheritance():\r\n \r\n #first let's check that we need to remove samples\r\n arg = engine.buildArgument(conclusions.Conclusion(\"no process\"))\r\n name = \"removal of groups of olde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Crops feature_train(onpower_train, offpower_train and duration_train) to get same samples from different appliances(same modelappliance) and avoids overfittings to a many samples appliance. Updates stats attribute. Does the retraining. | def no_overfitting(self):
# Instance with minimun length should be the maximum length
train_len = []
[train_len.append(st['Nevents']) for st in self.stats]
train_len = np.array(train_len)
max_len = train_len[train_len != 0].min()
# CROPS FEATURE SAMPLES
onpower_... | [
"def retrain(self):\n self.training = True\n self.updating = False\n self.enable_gradients(False)\n self.update_noise_distributions()",
"def train():\r\n print('Loading and compiling models...')\r\n model_systole = get_model()\r\n model_diastole = get_model()\r\n\r\n # load... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cheks integrity of feature model distributions. CDF has to be bounded by one. | def check_cdfIntegrity(self, step):
# Selecting bins automatically:
x_max = self.onpower_train.max().values[0]
x_min = 0
step = 1
x_onpower = np.arange(x_min, x_max, step).reshape(-1, 1)
x_max = 0
x_min = self.offpower_train.min().values[0]
step = 1
... | [
"def check_distribution(self):\n pass",
"def full_modeling(target, pre_clust_df, model_path, id_column):\n targets = [x for x in pre_clust_df.columns if x[:8] == 'default_']\n # folders for result saving\n folder_auc = model_path + '/pictures/roc_auc'\n folder_column_pics = model_path + '/pictu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Request File Path from user input import data to employees.csv | def emp_import():
while True:
try:
file_path = input("Enter the path of your file or enter 'quit' to go back to menu.\n File Path: ")
except FileNotFoundError:
print("File Not Found Error.")
continue
if file_path == "quit":
return
elif not os.path.exists(file_path) and not os.path.isfile(file_path)... | [
"def get_input_file():\n\n filename = input('Input the file name to save data to: ') + '.csv'\n return filename",
"def add_csv():\n employer_email = request.form['user']\n file = request.files['uploads[]'].stream.read().decode(\"utf-8\", \"strict\")\n error_list = parse_new_csv(file, employer_emai... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Request File Path from user input and Removes listed data from employees.csv | def path_delete_emp():
while True:
try:
file_path = input("Enter the path of your file or enter 'quit' to go back to menu.\n File Path: ")
except FileNotFoundError:
print("File Not Found Error.")
continue
if file_path == "quit":
return
elif not os.path.exists(file_path) and not os.path.isfile(file_... | [
"def delete_employee_from_file():\n try:\n path = input(\"Enter employees file path to delete:\")\n with open('/Users/sapir/Documents/python/final project- employee attandance log/emplist.csv', 'r') as inp, \\\n open('/Users/sapir/Documents/python/final project- employee attandance l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Separate out positive and negative attributes in the dataframe with attributes. Outputs two separated dataframes | def separate_pos_neg(attribution):
attribution_pos_val = attribution*(attribution >= 0)
attribution_neg_val = attribution*~(attribution >= 0)
return attribution_pos_val, attribution_neg_val | [
"def fix_negative_values(X_train: pd.DataFrame, X_test: pd.DataFrame) -> tuple:\r\n X_train.loc[X_train[\"CLCT\"] < 0, \"CLCT\"] = 0.0\r\n X_test.loc[X_test[\"CLCT\"] < 0, \"CLCT\"] = 0.0\r\n\r\n return X_train, X_test",
"def make_and_append_negative_data(self):\n negative_df = self.get_negative_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a url for download. This will call safe_url_string and then strip the fragment, if one exists. The path will be normalised. If the path is outside the document root, it will be changed to be within the document root. | def safe_download_url(url, encoding='utf8', path_encoding='utf8'):
safe_url = safe_url_string(url, encoding, path_encoding)
scheme, netloc, path, query, _ = urlsplit(safe_url)
if path:
path = _parent_dirs.sub('', posixpath.normpath(path))
if safe_url.endswith('/') and not path.endswith('/'):... | [
"def safe_download_url(url):\n safe_url = safe_url_string(url)\n scheme, netloc, path, query, _ = urlparse.urlsplit(safe_url)\n if path:\n path = _parent_dirs.sub('', normpath(path))\n if url.split('?')[0].endswith('/') and not path.endswith('/'):\n path += '/'\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean URL arguments leaving only those passed in the parameterlist keeping order >>> import w3lib.url >>> w3lib.url.url_query_cleaner("product.html?id=200&foo=bar&name=wired", ('id',)) 'product.html?id=200' >>> w3lib.url.url_query_cleaner("product.html?id=200&foo=bar&name=wired", ['id', 'name']) 'product.html?id=200&na... | def url_query_cleaner(url, parameterlist=(), sep='&', kvsep='=', remove=False, unique=True, keep_fragments=False):
if isinstance(parameterlist, (six.text_type, bytes)):
parameterlist = [parameterlist]
url, fragment = urldefrag(url)
base, _, query = url.partition('?')
seen = set()
querylist ... | [
"def strip_args(url):\n FLAGS = ['on.nytimes.com/public/overview', 'query.nytimes.com']\n\n if not any(flag in url.lower() for flag in FLAGS):\n for i in range(len(url)):\n if url[i] == \"?\" or url[i] == \"#\":\n url_str = url[:i]\n if url_str.endswith('/all/')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add or remove a parameter to a given url >>> import w3lib.url | def add_or_replace_parameter(url, name, new_value):
return _add_or_replace_parameters(url, {name: new_value}) | [
"def _add_query_parameter(url, name, value):\n if value is None:\n return url\n else:\n return update_query_params(url, {name: value})",
"def url_add_parameters(url, params):\r\n if params:\r\n fragments = list(urlparse.urlparse(url))\r\n fragments[4] = urllib.urlencode(parse_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add or remove a parameters to a given url >>> import w3lib.url | def add_or_replace_parameters(url, new_parameters):
return _add_or_replace_parameters(url, new_parameters) | [
"def url_add_parameters(url, params):\r\n if params:\r\n fragments = list(urlparse.urlparse(url))\r\n fragments[4] = urllib.urlencode(parse_qsl(fragments[4]) +\r\n params.items())\r\n url = urlparse.urlunparse(fragments)\r\n return url",
"def add_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If given a path name, return its File URI, otherwise return it unmodified | def any_to_uri(uri_or_path):
if os.path.splitdrive(uri_or_path)[0]:
return path_to_file_uri(uri_or_path)
u = urlparse(uri_or_path)
return uri_or_path if u.scheme else path_to_file_uri(uri_or_path) | [
"def file_uri(fname):\n if os.name == 'nt':\n # Local file\n if re.search(r'^[a-zA-Z]:', fname):\n return 'file:///' + fname\n # UNC based path\n else:\n return 'file://' + fname\n else:\n return 'file://' + fname",
"def path_to_local_file_uri(path):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks value is a positive integer, returns True if so, else raise error. | def check_positive(value):
try:
ivalue = int(value)
if ivalue <= 0:
# is int but non-positive
raise argparse.ArgumentTypeError(
'{} is an invalid positive integer value'.format(value))
return ivalue
except ValueError:
# not int
rais... | [
"def is_positive_int(val):\n return val and isinstance(val, int) and val > 0",
"def validate_value_is_int_convertible_and_positive(value: int) -> None:\n if not isinstance(value, int):\n validate_value_is_int_convertible(value)\n validate_positive_integer_value(int(value))",
"def check_positive(va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Counts how many kmers exists in a given file | def count_kmers(file_name, k, verbose=False):
if verbose:
start = time.time()
print('Counting kmers in {}'.format(file_name))
total_kmers = 0
with open(file_name, 'r') as f:
line_num = 0
for line in f:
if line_num % 4 == 1: # dna sequence
total_km... | [
"def count_kmers(sequence_file, kmer_mhash, mhash_kmer, kmer_canonical, k=5, txt=False):\n counts = Counter()\n n = 0\n for seq in file_handle(sequence_file, txt=txt):\n n += 1\n for kmer in sequence_kmers(seq, kmer_canonical, k):\n mhash = kmer_mhash[kmer]\n if mhash_km... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementation of DSK, kmer counting with very low memory algorithm Hashes each kmer and puts them into different files according to their hash values. By using target disk and memory spaces, determines how many distinct files should be used and in how many iterations the program needs to perform. | def dsk(file_name, k, n, capacity, error_rate, iters, parts, verbose=False):
if verbose:
start = time.time()
# Assign functions to local variables for performance improvement
hash_function = mmh3.hash
heap_pushpop = heapq.heappushpop
CHUNK_LIMIT = math.floor(capacity / 10) # write approxi... | [
"def count_kmers(sequence_file, kmer_mhash, mhash_kmer, kmer_canonical, k=5, txt=False):\n counts = Counter()\n n = 0\n for seq in file_handle(sequence_file, txt=txt):\n n += 1\n for kmer in sequence_kmers(seq, kmer_canonical, k):\n mhash = kmer_mhash[kmer]\n if mhash_km... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementation of Bloom Filter kmer Counting algorithm Creates a Bloom Filter and check the kmer is previously encountered or not. Only previously encountered kmers are added to the Hash Table, which drastically reduced the size of the Hash Table. | def bf_counter(file_name, k, n, capacity, error_rate, verbose=False):
if verbose:
start = time.time()
print('BFCounter started.')
heap = []
for i in range(n):
heap.append((0, ''))
bf = BloomFilter(capacity, error_rate, 'kmer_bf')
kmer_counter = defaultdict(lambda: 1)
... | [
"def counts(kmer):\n if kmer_length == 6:\n counts_dict = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}\n elif kmer_length == 8:\n counts_dict = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}\n\n kmer_hd = kmer_hd_dict(kmer)\n for list_of_kmers in all_sequences_kmerred:\n # fir... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the DefaultDialogues class. | def test_default_dialogues(self):
_, dialogue = self.default_dialogues.create(
counterparty=COUNTERPARTY_AGENT_ADDRESS,
performative=DefaultMessage.Performative.BYTES,
content=b"some_content",
)
assert dialogue.role == DefaultDialogue.Role.AGENT
assert... | [
"def test_default_dialogues(self):\n _, dialogue = self.default_dialogues.create(\n counterparty=COUNTERPARTY_AGENT_ADDRESS,\n performative=DefaultMessage.Performative.BYTES,\n content=self.content_bytes,\n )\n assert dialogue.role == DefaultDialogue.Role.AGENT\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the OefSearchDialogues class. | def test_oef_search_dialogues(self):
_, dialogue = self.oef_search_dialogues.create(
counterparty=COUNTERPARTY_AGENT_ADDRESS,
performative=OefSearchMessage.Performative.SEARCH_SERVICES,
query="some_query",
)
assert dialogue.role == OefSearchDialogue.Role.AGENT... | [
"def test_search(self):\n pass",
"def test_search_interface(self):\n pass",
"def test_search_entry(self):\n pass",
"def test_search_message_action(self):\n pass",
"def test_search_message(self):\n pass",
"def test_search_event(self):\n pass",
"def test_search_ca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the TacDialogues class. | def test_tac_dialogues(self):
_, dialogue = self.tac_dialogues.create(
counterparty=COUNTERPARTY_AGENT_ADDRESS,
performative=TacMessage.Performative.REGISTER,
agent_name="some_agent_name",
)
assert dialogue.role == TacDialogue.Role.CONTROLLER
assert di... | [
"def test_play_game(self):\r\n\r\n \r\n a_players = [RandomPlayer(1), RandomPlayer(2)]\r\n a_x_dist = 3\r\n a_y_dist = 3\r\n a_num_to_win = 1\r\n a_game = Game(a_players, a_x_dist, a_y_dist, a_num_to_win)\r\n\r\n #Game is played to competion\r\n a_game.play_game()\r\n\r\n a_history = a_ga... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if a is valid point. Points are tuples with two elements wich are integer coordinates | def is_point(a):
return isinstance(a, tuple) and isinstance(a[0], int) and isinstance(a[1], int) | [
"def valid_points(points, **kw):\n\n return is_integer(points)",
"def validate_points(*points):\n try:\n # Convert to float array\n points = numpy.array(points)\n points = points.astype(float)\n # Ensure it has the form (X,2)\n if len(points.shape) != 2 or points.shape[1] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return distance betwen a and b. | def distance(a, b):
ax, ay = a
bx, by = b
dx = bx - ax
dy = by - ay
return (abs(dx) + abs(dy) + abs(dx - dy)) / 2 | [
"def distance(self, a, b):\n raise NotImplementedError()",
"def distance(self, a, b):\n if not (a in self and b in self):\n raise RuntimeError(\n \"Can only compute distance for values within \"\n \"the space, not {} and {}.\".format(a, b)\n )\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if a and b are in given distance d | def in_distance(a, b, d):
return distance(a, b) <= d | [
"def distance(self, a, b):\n if not (a in self and b in self):\n raise RuntimeError(\n \"Can only compute distance for values within \"\n \"the space, not {} and {}.\".format(a, b)\n )\n return 1 if a != b else 0",
"def dist(self, one, two):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates how many points lies in circle in d distance | def num_points_in_circle(d):
return 6 * d if d > 0 else 1 | [
"def num_points_in_distance(d):\n return 1 + 3 * d * (d + 1)",
"def numInCircle(r,points): \r\n count = 0\r\n for point in points:\r\n if inCircle(r,point):\r\n count += 1\r\n return count",
"def dcircle(p, xc, yc, r):\n return np.sqrt(((p - np.array([xc, yc])) ** 2).sum(-1))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates how many points lies in given distance | def num_points_in_distance(d):
return 1 + 3 * d * (d + 1) | [
"def count_points_within(points: List[Point], total_distance: int) -> int:\n min_x, min_y, max_x, max_y = minmax_from_points(points)\n \n count = 0\n for x in range(min_x, max_x + 1):\n print(min_x, x, max_x)\n for y in range(min_y, max_y + 1):\n if Point(x, y).total_manhattan_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a modelled PSF for the given model | def model_psf(self):
return self.model()(self._XGrid, self._YGrid) | [
"def get_PSF_model(psf_models, n_psf, current_idx):\n return psf_models[current_idx%n_psf]",
"def get_FSF(self):\n try:\n white = self.images['MUSE_WHITE']\n pixstep = white.wcs.get_step(unit=u.arcsec)[0]\n except Exception:\n pixstep = None\n\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract the FWHM from the model of the star. The FWHM needs to be calculated for each model. For the Moffat, the FWHM is a function of the gamma and alpha parameters (in other words, the scaling factor and the exponent of the expression), while for a Gaussian FWHM = 2.3548 sigma. Unfortunately, our case is a 2D Gaussia... | def fwhm(self):
model_dict = dict(zip(self.model().param_names, self.model().parameters))
if self.model_type == self._MOFFAT2D:
gamma, alpha = [model_dict[ii] for ii in ("gamma_0", "alpha_0")]
FWHM = 2.0 * gamma * np.sqrt(2 ** (1 / alpha) - 1)
FWHM_x, FWHM_y = None, N... | [
"def calc_psf_fwhm_inpix_gaussian(arr):\n\tmodel = fit_gaussian(arr)\n\n\tsigma = max(model.y_stddev, model.x_stddev)\n\tfwhm = 2.355 * sigma\n\n\treturn fwhm",
"def calc_psf_fwhm_inpix_moffat(arr):\n\tmodel = fit_moffat(arr)\n\n\tfwhm = 2.* model.gamma * np.sqrt( 2.**(1./model.alpha) - 1. )\n\n\treturn fwhm",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a model with first guesses for the parameters. The user can select between several astropy models, e.g., 'Gaussian2D', 'Moffat2D'. We will use the data to get the first estimates of the parameters of each model. Finally, a Constant2D model is added to account for the background or sky level around the star. | def _initialize_model(self):
max_value = self.data.max()
if self.model_type == self._GAUSSIAN2D:
model = models.Gaussian2D(
x_mean=self.x, y_mean=self.y, x_stddev=1, y_stddev=1
)
model.amplitude = max_value
# Establish reasonable bounds f... | [
"def init_model(self):\n # n_dims == n_hparams\n n_dims = len(self.searchspace.keys())\n\n if self.interim_results:\n n_dims += 1 # add one dim for augumented budget\n\n cov_amplitude = ConstantKernel(1.0, (0.01, 1000.0))\n\n other_kernel = Matern(\n length_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fit the sky using a Ring2D model in which all parameters but the amplitude are fixed. | def fit_sky(self):
min_value = self.data.min()
ring_model = models.Ring2D(
min_value, self.x, self.y, self._box * 0.4, width=self._box * 0.4
)
ring_model.r_in.fixed = True
ring_model.width.fixed = True
ring_model.x_0.fixed = True
ring_model.y_0.fixed =... | [
"def test_linear_fit_2d_model_set_fixed_parameters(self):\n init_model = models.Polynomial2D(\n degree=2,\n c1_0=[1, 2],\n c0_1=[-0.5, 1],\n n_models=2,\n fixed={\"c1_0\": True, \"c0_1\": True},\n )\n\n x, y = np.mgrid[0:5, 0:5]\n zz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a dynamic environment given a json_path to an environment file, using property_name as the initial node to start reading, validating against a json schema file if given any | def set_env_from_json_file(json_path, property_name=None, schema_path=None):
if schema_path: # if schema_path is provided
with open(schema_path, 'r') as schema_file:
json_schema = json.load(schema_file)
else:
json_schema = None
with open(json_path, 'r') as data:
if pro... | [
"def set_env_from_json(json_object, json_schema=None):\n if json_schema:\n validate(json_object, json_schema)\n\n environment = json_object\n\n # Prepend the command \"source\" to each one of the commands defined in the\n # command_prefixes property of the json file.\n prefixes = environment.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a dynamic environment based on the contents of the given json_object and validates againts a json_schema object if given any. If 'command_prefixes' is available it adds it to the environment prepending 'source' to the given paths. fabfile.py from fabric.api import task from fabutils.env import set_env_from_json | def set_env_from_json(json_object, json_schema=None):
if json_schema:
validate(json_object, json_schema)
environment = json_object
# Prepend the command "source" to each one of the commands defined in the
# command_prefixes property of the json file.
prefixes = environment.pop('command_pre... | [
"def set_env_from_json_file(json_path, property_name=None, schema_path=None):\n if schema_path: # if schema_path is provided\n with open(schema_path, 'r') as schema_file:\n json_schema = json.load(schema_file)\n else:\n json_schema = None\n\n with open(json_path, 'r') as data:\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The POST on `/institution` should create an institution | def test_create(self, mock_decorator):
response = self.client.post(
'/api/bce_institutions/0802145Y',
content_type='application/json',
headers={'Authorization': 'Bearer token'},
data=json.dumps({
'is_institution': True
}))
self.... | [
"def institutions_post(user_inst): # pylint:disable=unused-argument\n name = request.headers.get('name')\n webpage = request.headers.get('webpage')\n address = request.headers.get('address')\n username = request.headers.get('username')\n\n if not user_inst.group == \"support\":\n return jsoni... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The PUT on `/institution` should update an institution's status if it is updated from False to True | def test_update_true(self, mock_decorator):
BceInstitutionRepository.create(
uai='0802145Z', is_institution=False)
response = self.client.put(
'/api/bce_institutions/0802145Z',
content_type='application/json',
headers={'Authorization': 'Bearer token'},
... | [
"def institutions_patch(user_inst):\n institution_id = request.headers.get('id')\n name = request.headers.get('name')\n webpage = request.headers.get('webpage')\n address = request.headers.get('address')\n\n if institution_id is None:\n return jsonify({'error': 'Missing parameter'}), 400\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrite the network's weights with a specified list of tensors or change weights along directions with a step size. | def set_weights(net, weights, directions=None, step=None):
if directions is None:
# You cannot specify a step length without a direction.
for (p, w) in zip(net.parameters(), weights):
p.data.copy_(w.type(type(p.data)))
else:
assert step is not None, 'If a direction is specifi... | [
"def update_weights(self, batch_size, eta):\n for l in self.layers:\n l.update_weights(batch_size, eta)",
"def network_weights(self, weights: typing.List[np.ndarray]) -> None:\n logging.debug(\"Assigning new network weights: %s\" % str(weights))\n for parameter, sample in zip(self.model.para... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrite the network's state_dict or change it along directions with a step size. | def set_states(net, states, directions=None, step=None):
if directions is None:
net.load_state_dict(states)
else:
assert step is not None, 'If direction is provided then the step must be specified as well'
if len(directions) == 2:
dx = directions[0]
dy = direction... | [
"def updateSimState(self):\n self.sim_state = {k: v for k,v in self.state.iteritems()}",
"def set_state(self, new_state):\n for x, y in doublerange(self.size):\n self.change_cell(x, y, new_state[x][y])",
"def simStepSize(self, stepsize):\n self.simulation.stepSize = stepsize",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produce a direction from 'weights' to 'weights2'. | def get_diff_weights(weights, weights2):
return [w2 - w for (w, w2) in zip(weights, weights2)] | [
"def get_weight_dist(w1, w2, p=2):\n return torch.norm(w1 - w2, p=p)",
"def connect_both(node1, node2, weight):\n connect_one_way(node1, node2, weight)\n connect_one_way(node2, node1, weight)",
"def reverse_edge(self, node1, node2, weight=None):\n\n if not weight:\n weight = self._gra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rescale the direction so that it has similar norm as their corresponding model in different levels. | def normalize_direction(direction, weights, norm='filter'):
if norm == 'filter':
# Rescale the filters (weights in group) in 'direction' so that each
# filter has the same norm as its corresponding filter in 'weights'.
for d, w in zip(direction, weights):
d.mul_(w.norm()/(d.norm(... | [
"def normalize(self):\n d = 1.0 / self.magnitude()\n self.r *= d\n self.g *= d\n self.b *= d\n self.a *= d",
"def normalize(self):\n mag = self.distance(Point())\n if mag > 0:\n self.scale(1. / mag)",
"def normalize(self):\n\ttry:\n\t self.as_matrix... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup the h5 file to store the directions. | def setup_direction(args, dir_file, net):
print('-------------------------------------------------------------------')
print('setup_direction')
print('-------------------------------------------------------------------')
# Setup env for preventing lock on h5py file for newer h5py versions
os.en... | [
"def insert(self, h5file, description):\n return",
"def openh5(self):\n if not self.h5.isopen:\n self.h5 = tbl.openFile(self.h5_path, 'a')",
"def h5_output(self):\n\n if len(self.h5_datasets) == 0:\n self.init_h5_datasets()\n filename = \"working.hdf5\"\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name the direction file that stores the random directions. | def name_direction_file(args):
if args.dir_file:
assert exists(args.dir_file), "%s does not exist!" % args.dir_file
return args.dir_file
dir_file = ""
file1, file2, file3 = args.model_file, args.model_file2, args.model_file3
# name for xdirection
if file2:
# 1D linear int... | [
"def get_file_name(self):\n return Utils.get_random_string(10)",
"def generate_name(number, direction):\n number_to_ordinal = {\n 1: '1st', 2: '2nd', 3: '3rd', 21: '21st', 22: '22nd', 23: '23rd',\n 31: '31st', 32: '32nd', 33: '33rd', 41: '41st', 42: '42nd', 43: '43rd',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load direction(s) from the direction file. | def load_directions(dir_file):
f = h5py.File(dir_file, 'r')
if 'ydirection' in f.keys(): # If this is a 2D plot
xdirection = h5_util.read_list(f, 'xdirection')
ydirection = h5_util.read_list(f, 'ydirection')
directions = [xdirection, ydirection]
else:
directions = [h5_util.... | [
"def load_directions(dir_file):\n\n xdirection = h5_util.read_list(f, 'xdirection')\n ydirection = h5_util.read_list(f, 'ydirection')\n directions = [xdirection, ydirection]\n\n return directions",
"def _load_stops_mapping(self):\n # update the mapping file from the server\n online_updat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Appel la verif_prop de l' Entry proposition si proposition est un seule lettre ou si le mot complet est proposé supprime la proposition si elle ne rentre dans aucun des cas cités | def get_prop(self):
prop = self.proposition.get().upper()
if (len(prop) == 1 or len(prop) == self.jeu.len_mot()) and prop.isalpha():
self.proposition.delete(0, "end")
return prop, self.jeu.verif_prop(prop)
else:
self.proposition.delete(0, "end")
r... | [
"def is_proved(self):\n return len(self.proofs) > 0",
"def verif_victoire(self):\n\n if self._mot_en_cours == self._mot_a_trouver :\n return True\n else :\n return False",
"def verifier_correspondance(self):\n #verification du journal\n v1=self.correspondan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cette affiche la frame de fin de partie avec possibilité de rejouer d'avoir acces au scores ou de changer d'utilisateur On sauvegarde aussi les stats du joueur sur la partie | def fin_de_partie(self, win):
self.changement_frame()
self.proposition.unbind("<Return>")
self.jeu.sauve_score()
self.frame_jeu.pack_forget()
if win:
self.label_victoire["text"] = "FÉLICITATIONS !\nLe mot était '{}'.\
\nVous marquez {} point(s) !".format(s... | [
"def high_score ():\r\n\traz ()\r\n\taller_a (-200, 200)\r\n\ttexte (\"Meilleurs scores\", \"important\")\r\n\taller_a (-200, 150)\r\n\tcolonnes(5, 50, 100, generer_score () )",
"def campeonato():\n\n global res\n\n # Número de partidas em que o usuário foi o vencedor.\n usu_ganhou = 0\n\n # Loop que ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simulates the game compute_func takes a board and a list of legal moves s and returns a move | def start(compute_func):
board = gen_board()
turn = 1
while True:
print("\nTurn:", turn)
print_board(board)
lm = legal_moves(board)
print("Legal: ", *[DIRECTIONS[i] for i in lm])
chosen_move = compute_func(board,lm)
print("Chosen: " + DIRECTIONS[chosen_move... | [
"def available_moves(cls, board: list):",
"def mm_move(board, player): \n \n if board.check_win() != None: \n return SCORES[board.check_win()], (-1, -1)\n \n possible_moves = board.get_empty_squares()\n \n result = (-1, (-1, -1))\n \n for move in possible_moves: \n # make cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set an instance attribute indicating the device's pairing status | def _get_pairing_status(self):
try:
self.is_paired = is_paired(ignore_errors=False)
except BackendDown:
LOG.error('Cannot complete device updates due to backend issues.')
self.backend_down = True
if self.is_paired:
LOG.info('Device is paired') | [
"def pairingStatus(self, QBluetoothAddress): # real signature unknown; restored from __doc__\n pass",
"def update(self) -> None:\n self._parent_device.update()\n self._attr_is_on = self._port.get_state()",
"def pair(self):\n self._prop_if.Set(DEVICE_IFACE, 'Trusted', True)\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Force a sync of the local clock with the Network Time Protocol. The NTP sync is only forced on Raspberry Pi based devices. The assumption being that these devices are only running Mycroft services. We don't want to sync the time on a Linux desktop device, for example, because it could have a negative impact on other so... | def _update_system_clock(self):
if self.platform in RASPBERRY_PI_PLATFORMS:
LOG.info('Updating the system clock via NTP...')
if self.is_paired:
# Only display time sync message when paired because the prompt
# to go to home.mycroft.ai will be displayed by ... | [
"def sync(self):\n rtc = machine.RTC()\n rtc.ntp_sync(self.ntp_pool_server, update_period=3600)\n while not rtc.synced():\n time.sleep(1)",
"def updateRTCFromNTP(strip, start = False):\r\n wifi = connectToWifi(strip, start)\r\n try:\r\n ntptime.settime()\r\n except ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Indicate to the user that skills are being loaded. | def _display_skill_loading_notification(self):
self.enclosure.eyes_color(189, 183, 107) # dark khaki
self.enclosure.mouth_text(dialog.get("message_loading.skills")) | [
"def load():\r\n sourcerpg.skills.addSkill( skillName, maxLevel, creditStart, creditIncrement )",
"def has_skill(self, skill):\n self.skill_handler.has_skill(skill)",
"def loadallskills(self):\r\n for skill in os.listdir( os.path.join( es.getAddonPath( info.basename ), \"skills\" )):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if device is paired, if not automatically start pairing. Pairing cannot be performed if there is no connection to the back end. So skip pairing if the backend is down. | def _ensure_device_is_paired(self):
if not self.is_paired and not self.backend_down:
LOG.info('Device not paired, invoking the pairing skill')
payload = dict(utterances=["pair my device"], lang="en-us")
self.bus.emit(Message("recognizer_loop:utterance", payload)) | [
"def _get_pairing_status(self):\n try:\n self.is_paired = is_paired(ignore_errors=False)\n except BackendDown:\n LOG.error('Cannot complete device updates due to backend issues.')\n self.backend_down = True\n\n if self.is_paired:\n LOG.info('Device is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start up the all intent services and connect them as needed. | def _register_intent_services(bus):
service = IntentService(bus)
# Register handler to trigger fallback system
bus.on(
'mycroft.skills.fallback',
FallbackSkill.make_intent_failure_handler(bus)
)
return service | [
"def _starting_up():\n global ws, skill_reload_thread, event_scheduler\n\n ws.on('intent_failure', FallbackSkill.make_intent_failure_handler(ws))\n\n # Create skill_manager listener and invoke the first time\n ws.on('skill_manager', skills_manager)\n ws.on('mycroft.internet.connected', install_defaul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize trainable variables randomly or from the given checkpoint. | def _initialize_variables(self, finetune: str=None, **kwargs) -> None:
if finetune is None:
super()._initialize_variables(**kwargs) # default initialization
else:
self._saver = tf.train.Saver(max_to_keep=100000000)
logging.info('Restoring variables from `%s`', finetu... | [
"def resnet_init_from_checkpoint_fn(checkpoint):\n logging.info('Initializing model weights from %s', checkpoint)\n assignment_map = {}\n resnet_scope = _get_resnet_scope()\n for var in contrib_framework.get_variables(\n scope=resnet_scope, collection=tf.GraphKeys.TRAINABLE_VARIABLES):\n if 'dense' not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write Elasticluster configuration file with user and security information. | def _write_elasticluster_config(config, out_file):
orig_file = os.path.join(sys.prefix, "share", "bcbio-vm", "elasticluster", "config")
if not os.path.exists(os.path.dirname(out_file)):
os.makedirs(os.path.dirname(out_file))
if os.path.exists(out_file):
bak_file = out_file + ".bak%s" % datet... | [
"def write_user_config():\n\n # Add all new roles to cummulative roles and also remove duplicates before\n # writing -- must be a list since sets cannot be serialized with JSON\n USER_CONFIG[\"roles_this_run\"] = list(set(USER_CONFIG[\"roles_this_run\"]))\n USER_CONFIG[\"roles_all_time\"] += USER_CONFIG... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a bcbio keypair and import to ec2. Gives us access to keypair locally and at AWS. | def create_keypair(econfig_file=None, region=None, keyname="bcbio"):
import boto
import boto.ec2
if econfig_file:
keypair_dir = os.path.dirname(econfig_file).replace("elasticluster", "aws_keypairs")
else:
keypair_dir = os.path.join(os.getcwd(), "aws_keypairs")
if not os.path.exists(k... | [
"def keypair_setup():\n\n os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION)\n\n keypair_name = u.get_keypair_name()\n keypair = u.get_keypair_dict().get(keypair_name, None)\n keypair_fn = u.get_keypair_fn()\n if keypair:\n print(\"Reusing keypair \" + keypair_name)\n # check that local pem file exists and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a bcbio IAM user account with full access permissions. | def _bcbio_iam_user(conn, args):
import boto
name = "bcbio"
access_key_name = "full_admin_access"
if args.nocreate:
need_creds = False
else:
try:
conn.get_user(name)
if args.recreate:
keys = conn.get_all_access_keys(name)
for ac... | [
"def create_user(client, iam, creator, username, policy_dir, region):\n # Create the user.\n\n response = client.create_user(\n UserName = username,\n Tags = [{ 'Key': 'Created_By', 'Value': creator }]\n )\n user = iam.User(response['User']['UserName'])\n\n access_key_pair = user.create... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an IAM instance profile with temporary S3 access to be applied to launched machines. | def bcbio_s3_instance_profile(conn, args):
import boto
if hasattr(args, "nocreate") and args.nocreate:
return {"instance_profile": ""}
base_name = args.cluster if hasattr(args, "cluster") and args.cluster else "bcbio"
name = "%s_full_s3_access" % (base_name)
try:
ip = conn.get_instan... | [
"def create(profile, name):\n client = boto3client.get(\"iam\", profile)\n params = {}\n params[\"InstanceProfileName\"] = name\n return client.create_instance_profile(**params)",
"def test_instance_profile_exists(self) -> None:\n self.assertTrue(self.validate_instance_profile('s3-access-role',... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the parsers in the given list one after another, then expect the end of the input. | def whole(parsers):
if len(parsers) == 0:
return finished >> (lambda x: [])
if len(parsers) == 1:
return parsers[0] + finished >> (lambda x: x[:-1])
return reduce(add, parsers) + skip(finished) | [
"def parse(self, input):\n errors = []\n input = chain(input, [(self.EOF,)])\n stack = []\n state = 0\n while True:\n done,_,state,lookahead = self._parse(input, stack, state)\n if done:\n break\n\n expect = [ t for s,t in self._redu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |