query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
The change handler for the 'horizontal_scrollbar_policy' attribute of the shell object. | def shell_horizontal_scrollbar_policy_changed(self, policy):
self.set_horizontal_policy(policy) | [
"def shell_vertical_scrollbar_policy_changed(self, policy):\n self.set_vertical_policy(policy)",
"def set_horizontal_policy(self, policy):\n self.widget.setHorizontalScrollBarPolicy(SCROLLBAR_POLICY_MAP[policy])",
"def addHorizontalScrollbar(self):\n self.horizontalScrollbar = Scrollbar(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The change handler for the 'vertical_scrollbar_policy' attribute of the shell object. | def shell_vertical_scrollbar_policy_changed(self, policy):
self.set_vertical_policy(policy) | [
"def set_vertical_policy(self, policy):\n self.widget.setVerticalScrollBarPolicy(SCROLLBAR_POLICY_MAP[policy])",
"def shell_horizontal_scrollbar_policy_changed(self, policy):\n self.set_horizontal_policy(policy)",
"def addVerticalScrollbar(self):\n self.verticalScrollbar = Scrollbar(self, o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the pixel thickness of the scrollbar. | def horizontal_scrollbar_thickness(self):
return self._scrollbar_thickness(QtCore.Qt.Vertical) | [
"def _scrollbar_thickness(self, orientation):\n style = self.widget.style()\n options = QtGui.QStyleOptionSlider()\n options.orientation = orientation\n return style.pixelMetric(style.PM_ScrollBarExtent, options)",
"def thickness(self) -> float:\n return self._thickness",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scrolls the area such that position is visible with a minimum of margin points surrounding position. | def scroll_to_position(self, position, margin):
widget = self.widget
pos_x, pos_y = position
margin_x, margin_y = margin
widget.ensureVisible(pos_x, pos_y, margin_x, margin_y) | [
"def scroll(self):\n x_position = self._player.get_position()[0]\n half_screen = self._master.winfo_width() / 2\n world_size = self._world.get_pixel_size()[0] - half_screen\n\n # Left side\n if x_position <= half_screen:\n self._view.set_offset((0, 0))\n\n # Betw... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the horizontal scrollbar policy of the widget. | def set_horizontal_policy(self, policy):
self.widget.setHorizontalScrollBarPolicy(SCROLLBAR_POLICY_MAP[policy]) | [
"def shell_horizontal_scrollbar_policy_changed(self, policy):\n self.set_horizontal_policy(policy)",
"def set_horizontal_size_policy(widget, policy):\n\n size_policy = widget.sizePolicy()\n size_policy.setHorizontalPolicy(policy)\n widget.setSizePolicy(size_policy)",
"def set_horizontal_policy(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the vertical scrollbar policy of the widget. | def set_vertical_policy(self, policy):
self.widget.setVerticalScrollBarPolicy(SCROLLBAR_POLICY_MAP[policy]) | [
"def shell_vertical_scrollbar_policy_changed(self, policy):\n self.set_vertical_policy(policy)",
"def set_vertical_size_policy(widget, policy):\n\n size_policy = widget.sizePolicy()\n size_policy.setVerticalPolicy(policy)\n widget.setSizePolicy(size_policy)",
"def addVerticalScrollbar(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the thickness of a scrollbar for the given orientation. | def _scrollbar_thickness(self, orientation):
style = self.widget.style()
options = QtGui.QStyleOptionSlider()
options.orientation = orientation
return style.pixelMetric(style.PM_ScrollBarExtent, options) | [
"def horizontal_scrollbar_thickness(self):\n return self._scrollbar_thickness(QtCore.Qt.Vertical)",
"def thickness(self) -> float:\n return self._thickness",
"def thickness(self):\n return self._thickness",
"def thickness(self, axis):\n self_body = _union_entities(self.bodies)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts a datetime from the response | def extract_datetime(self, response):
query = self.extract_datetime_query
extracted = response.css(query).extract()[1]
return parser.parse(extracted) | [
"def _parse_datetime(response: str) -> datetime.datetime:\n match = _DATETIME_RE.match(response)\n if not match:\n raise exceptions.InvalidResponse(response)\n\n date, time = match.groups()\n month, day, year = map(int, date.split(\"/\"))\n hour, minute, second = map(int, time.split(\":\"))\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait indefinitely until clipboard updates. | def clipboard_get_new(delay):
old_value = clipboard.paste()
while True:
time.sleep(delay)
if old_value != clipboard.paste():
return clipboard.paste() | [
"def waitForNewPaste(timeout=None):\n startTime = time.time()\n originalText = paste()\n while True:\n currentText = paste()\n if currentText != originalText:\n return currentText\n time.sleep(0.01)\n\n if timeout is not None and time.time() > startTime + timeout:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This Test function checks if created profile are stored properly | def test_creation_profile_5():
assert tuple_NT[0][4] == LIST_dict[0]['current_location'], "current_location' of profile is not getting stored properly" | [
"def test_pm_profile_create(profile_manager, name):\n profile = profile_manager.create(name)\n assert os.path.isdir(profile.path)\n if name:\n assert profile.name == name",
"def testProfileCreation(self):\n small_tree1_equality = self.checkProfileEquality(self.profiles[0], self.small_profil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This Test checks speed of tuple of Named tuple vs List dictionary for 10000 profiles and 100 runs | def test_output_named_tuple_vs_dictionary_6():
assert delta2 > delta1, "Dictionary cannot be faster than named tuple" | [
"def calculate_random_profile_info_named_tuple_tc():\n value_namedtuple = calculate_random_profile_info(no=10000)()\n assert len(value_namedtuple) == 4\n assert any([\"largest_blood_type\" in o for o in list(value_namedtuple.keys())])\n assert any([\"mean_current_location\" in o for o in list(value_name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inherit name_search method to display only open period unless order close period by sending closed=True in context | def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
if args is None:
args = []
if context is None:
context = {}
if not context.get('closed',False):
args.append(('state', '=', 'draft'))
return super(account_period... | [
"def get_closed(self):\n return self.filter(status=\"CLOSED\")",
"def check_open():\n print(\"***** Check if Business is Open/Closed *****\")\n while True:\n print()\n business_object = query_business_name()\n if business_object == \"back\":\n return\n elif busi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change record state to 'Close Extension Period'. | def action_close_extension_period(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state': 'close_ext_period'}, context=context) | [
"def setAutoClose(self, state):\r\n data = self.getData()\r\n data['auto_close'] = state\r\n self.updateData(data)",
"def close(self):\n if self.SE == 6:\n self.evr.polarity.put('VAL', 0)\n else:\n self.S_CLOSE = 1",
"def period():\n frequencyText.conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update dict. of values to set interval_number depend on company_id | def onchange_company_id(self, cr, uid, ids, company_id, context=None):
# update related fields
values =super(account_config_settings,self).onchange_company_id(cr, uid, ids, company_id, context=context).get('value',{})
if company_id:
company = self.pool.get('res.company').bro... | [
"def onchange_company_id(self, cr, uid, ids, company):\n return {'value': company == 'from' and {'from_budget_line':False} or\n {'analytic_account_id':False, 'account_id':False, \n 'period_id':self._get_period(cr, uid)}}",
"def _assign_interval(self, interval)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a class with a subclassing relation defined by condition. For example, a dataclass is a subclass of `meta(dataclasses.is_dataclass)`, and a class which name starts with "X" is a subclass of | def meta(condition):
class M(metaclass=_MetaMC):
@classmethod
def chk(cls, sub):
return condition(sub)
return M | [
"def _class(self, class_):\r\n\r\n if class_:\r\n if hasattr(class_, '__mro__'):\r\n #this is a class\r\n return class_\r\n else:\r\n #this is an instance\r\n return type(class_)",
"def _get_child_by_name(cls, class_name=str)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Represent a class from an external module without importing it. For instance, `deferred("numpy.ndarray")` matches instances of numpy.ndarray, but it does not import numpy. When tested against a class, if the first part of class's `__module__` is `numpy`, then we do get the class and perform a normal issubclass check. I... | def deferred(ref):
module, _ = ref.split(".", 1)
if module in sys.modules:
return _getcls(ref)
@meta
def check(cls):
full_cls_mod = getattr(cls, "__module__", None)
cls_module = full_cls_mod.split(".", 1)[0] if full_cls_mod else None
if cls_module == module:
... | [
"def UnavailableClass(unavailable_module):\n\n class UnavailableMeta(type):\n def __getattr__(cls, name):\n raise DeferredImportError(\n unavailable_module._moduleunavailable_message(\n f\"The class attribute '{cls.__name__}.{name}' is not available \"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a map file and get the list and address of functions that need an EBC call signature MapPath Map file absolute path a list of call names with their address and source location | def ParseMap(MapPath):
Status = 0
CallList = []
with file(MapPath, 'r') as f:
for Line in f:
Line = Line.strip()
if Status == 0:
m = LoadRegexp.match(Line)
if m != None:
LoadAddr, = m.groups(0)
... | [
"def BuildSymbolToFileAddressMapping():\n result = defaultdict(list)\n # Iterate over all the extracted_symbols_*.txt files.\n for filename in os.listdir(FLAGS.work_directory):\n print(\"Checking filename %s\" % filename)\n if fnmatch.fnmatch(filename, \"extracted_symbols_*.txt\"):\n print(\"Processin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the list of files passed as arguments, and try to locate and open the matching signature files to build a complete EBC signature list. as the signature file to ensure that the signatures we need are present. FileList A list of .sig or .lib files a list of function calls with their signature data | def BuildSignatureList(FileList):
global Options
SigList = {}
for File in FileList:
File = os.path.splitext(File)[0]+'.sig'
try:
with open(File, 'rb') as f:
SavedList = pickle.load(f)
SigList.update(SavedList)
if Options.... | [
"def InsertSignatures(EfiPath, MapList, SigList):\r\n global Options\r\n\r\n with file(EfiPath, 'r+b') as f:\r\n Width = max(len(Entry[0]) for Entry in MapList) + 3\r\n for Entry in MapList:\r\n f.seek(Entry[1] + 4)\r\n f.write(struct.pack('I', EBC_CALL_SIGNATURE + SigList[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sanity check to ensures that the signatures' data and addresses are valid. EfiPath EFI binary absolute path MapList Function calls requiring signature, with their address SigList Function calls signature dictionary True if the check passed | def CheckSignatures(EfiPath, MapList, SigList):
for Entry in MapList:
# Check for missing signatures
assert Entry[0] in SigList, Entry[0] + ": missing signature"
# Make sure the signature fits in 16 bits
assert SigList[Entry[0]] < 0x10000, Entry[0] + ": invalid signature"
... | [
"def check_sigs(self):\n #No unsigned txs (yet)\n if self.reqd_sigs == None:\n return False\n #Every input address must sign\n for i in self.inputs:\n if not i[0] in self.reqd_sigs:\n return False\n thedata = self.__gather()\n valid = Tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the EFI binary to ensure we have the right signature addresses EfiPath EFI binary absolute path Maplist Function calls requiring signature, with their address SigList Function calls signature dictionary True if the signatures were successfully patched | def InsertSignatures(EfiPath, MapList, SigList):
global Options
with file(EfiPath, 'r+b') as f:
Width = max(len(Entry[0]) for Entry in MapList) + 3
for Entry in MapList:
f.seek(Entry[1] + 4)
f.write(struct.pack('I', EBC_CALL_SIGNATURE + SigList[Entry[0]]))
... | [
"def CheckSignatures(EfiPath, MapList, SigList):\r\n\r\n for Entry in MapList:\r\n # Check for missing signatures\r\n assert Entry[0] in SigList, Entry[0] + \": missing signature\"\r\n # Make sure the signature fits in 16 bits\r\n assert SigList[Entry[0]] < 0x10000, Entry[0] + \": inv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Warn the user about the consequences of private | def private_warn(*arg):
private = private_var.get()
if private:
response = tkmb.askokcancel(
"Are you sure?",
"Do you really want to encrypt this message?"
)
if not response:
private_var.set(False) | [
"def _private(self):\n pass",
"def test_fail_use_other_priv_def(self): # suppress(no-self-use)\n with ExpectedException(LinterFailure):\n run_linter_throw(\"_definition (ARGUMENT)\\n\",\n whitelist=[\"access/other_private\"])",
"def test_pass_used_own_priv_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the size of the text widget font from font_size | def set_font_size(*args):
size = font_size.get()
message_inp.configure(font=f'TKDefault {size}') | [
"def chg_text_size(self):\n font_size = self.sio_ui.textSizeInput.currentText()\n font_size = int(font_size.split(\"pt\")[0])\n self.data.font_size = font_size\n self.make_plot()",
"def _setFontSize(self, size):\n value = str(size)\n idx = self._size.findText(value)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checking contains model in the list models | def check_model_in_the_list_models(model_list, insert_model):
for model in model_list:
if model == insert_model:
return
assert False, "Not Contains model in the list:\nModel_list:\n{model_list}\nInsert model:\n{insert_model}" \
.format(model_list='\n'.join(str(item) for item in model... | [
"def all_words_in_model( wordlist, model ):\n for w in wordlist:\n if w not in model:\n return False\n return True",
"def checkModel(self, model):\n # TODO",
"def hasModel(self, model):\n if model in self.models:\n return S_OK()\n else:\n return S_ERROR(\"Model %s ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run a single line of code, must specify language as first argument | async def runl(self, ctx: commands.Context, lang: str, *, code: str):
result = await self._run_code(lang=lang, code=code)
await self._send_result(ctx, result) | [
"def evaluateCode(lang, code):",
"def run(self, language = LANGUAGE_DEFAULT):\r\n self.set_language(language)\r\n self.set_translation(language)\r\n self.test_print()",
"def run_text(self):\n source = self.te_code.get(1.0, END)\n self.inter.run_code(source, '<user-provided cod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a single value from the row matching the given constraints. The table is inferred if the primary key column (named table + '_id') is the one and only constraint or the requested field. | def get(self, field, table=None, **constraints):
keys = constraints.keys()
table = (table or
(len(keys) == 1 and keys[0].endswith('_id') and keys[0][:-3]) or
(field.endswith('_id') and field[:-3]))
condition = ' and '.join(key + ' = %s' for key in keys)
for row in... | [
"def getOne(table, field, val):\n\n try:\n # return session.query(table).filter(getattr(table, field).like(val)).all()[0]\n return session.query(table).filter(getattr(table, field) == val).all()[0]\n except:\n return None",
"def getRecordFromKey (self, field, value, table):\n\t\tquerySt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a list of the columns in a given table. | def get_columns(self, table):
if table not in self.columns:
self.columns[table] = [
row[0] for row in self.db.iter('describe ' + table)]
return self.columns[table] | [
"def get_columns(table):\n inspector = get_inspector()\n return inspector.get_columns(table)",
"def get_columns(self, table:str) -> list:\n\n cursor = self.get_db().execute(f\"SELECT * FROM {table} LIMIT 0\")\n columns = [col[0] for col in cursor.description]\n\n return columns",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replaces the list of answers for a concept with the given list. | def set_concept_answers(concept_id, answer_concept_ids):
db.execute(
'delete from concept_answer where concept_id = %s', concept_id)
for i, answer_concept_id in enumerate(answer_concept_ids):
odb.insert('concept_answer', concept_id=concept_id,
answer_concep... | [
"def update(answers):\n for answer in answers:\n if answer['answer'] == 'accept':\n accept_phrases.append(answer['text'])\n elif answer['answer'] == 'reject':\n reject_phrases.append(answer['text'])",
"def answers(self, answers):\n\n self._answers ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates or updates a concept with the given name, type, and class. | def put_concept(concept_id, name, locale, new_datatype_id, class_id):
datatype_id = db.get('datatype_id', concept_id=concept_id)
# Changing the datatype of an existing concept is illegal in OpenMRS.
if datatype_id and new_datatype_id != datatype_id:
raise ValueError("Concept %d: cann... | [
"def AddConcept(self, concept):\n self.concepts.append(concept)",
"def update(self, concept):\n raise NotImplementedError()",
"def retrieve_or_create(self, concept):\n raise NotImplementedError()",
"def concept(self, concept):\n\n self._concept = concept",
"def add(self, concept):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes all the form_fields from the given form. | def clear_form(form_id):
db.execute('update form_field set parent_form_field = null'
' where form_id = %s', form_id) # remove foreign keys
db.execute('delete from form_field where form_id = %s', form_id) | [
"def remove_all_fields(self):\n self.fields = None",
"def removeForm(self, form):\n self.forms.remove(form)",
"def remove_ei_form(self, form):\n if form in self.ei_forms:\n self.ei_forms.remove(form)",
"def whitelist_form_fields(form, whitlisted_fields):\n for schema in getA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies the chart definition given rows from the chart tab. | def apply_chart(rows, form_id):
clear_form(form_id)
section = None
sections = []
section_rows = []
for row in rows:
if row['section'].strip():
if section and section_rows:
sections.append((section, section_rows))
se... | [
"def apply_chart_sections(sections, form_id):\n clear_form(form_id)\n\n for i, (section, rows) in enumerate(sections):\n if section == '[chart_divider]':\n section_type = 'CHART_DIVIDER'\n else:\n section_type = section[:1] == '[' and 'TILE_ROW' or '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rewrites the given chart form to contain the specified sections with the specified selection and sequence of grid rows. The OpenMRS data | def apply_chart_sections(sections, form_id):
clear_form(form_id)
for i, (section, rows) in enumerate(sections):
if section == '[chart_divider]':
section_type = 'CHART_DIVIDER'
else:
section_type = section[:1] == '[' and 'TILE_ROW' or 'GRID_SECTION... | [
"def apply_chart(rows, form_id):\n clear_form(form_id)\n section = None\n sections = []\n section_rows = []\n\n for row in rows:\n if row['section'].strip():\n if section and section_rows:\n sections.append((section, section_rows))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct a UUID from a form name, and issue a warning if we can't guarantee that the UUID will be unique. | def create_uuid_from_form_name(name):
prefix = 'buendia-form-'
max_uuid_len = 38
max_name_len = max_uuid_len - len(prefix)
if len(name) > max_name_len:
warnings.warn(
"The form name '%s' has been clipped to create a unique form ID. "
"Note that if you ... | [
"def unique_name():\n return \"unique-{0}\".format(uuid.uuid4())",
"def generate(namespace, name):\n\n if name and namespace:\n return uuid.uuid5(namespace, name)\n return None",
"def make_unique(value):\r\n import uuid\r\n return \"{}_{}\".format(value, uuid.uuid4().hex[0:10])",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds our custom XSLT as a form resource to a specified form. | def init_form_xslt(form_id):
name = db.get('name', 'form', form_id=form_id) + '.xFormXslt'
resource_id = get_or_insert('form_resource',
form_id=form_id, name=name, value_reference=XSLT_UUID)
odb.update('form_resource', resource_id, datatype=XSLT_DATATYPE,
preferred... | [
"def __call__(self, f):\n tree = f.build_etree(lxml=True)\n return self.xslt(tree)",
"def register_form(self):\n f = Form()\n self.forms = f\n return f",
"def _wrap_form(self, parent_form_class):\n steptitle = pd_mf(u'Add ${name}',\n map... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to plot caustics and critical curves only from a lenstool output file | def plot_curves_lenstool(label = ' ', courves_file = 'ce.dat', marker = 'm.', \
plt_show = False):
# x_ca, y_ca = np.loadtxt( courves_file, usecols=(3, 4), unpack=True )
# x_cc, y_cc = np.loadtxt( courves_file, usecols=(1, 2), unpack=True )
x_cc, y_cc, x_ca, y_ca = \
np.loadtx... | [
"def plot_curves(self, courves_file = 'crit.dat', plt_show = False):\n x1_c, y1_c, u1_c, v1_c = \\\n np.loadtxt(courves_file, usecols = (0, 1, 2, 3), \\\n unpack=True)\n plt.figure(1 , figsize=(16, 8))\n plt.subplot(1, 2, 1).set_aspect(1)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to perform le lens inversion for point images using lenstool for siep model | def make_inversion_lenstool(image_positons, z_source, \
inversion_par_file = 'make_inversion_siep.par'):
write_multfile(image_positons, z_source, file_name = 'multfile.in')
str_sys = 'lenstool ' + inversion_par_file + ' -n > lenstool.out'
os.system(str_sys)
ell ... | [
"def landsat_nvet_func(img):\n #evi = ee.Image(img).expression(\n #'(2.5 * (b(\"nir\") - b(\"red\"))) / ' +\n #'(b(\"nir\") + 6 * b(\"red\") - 7.5 * b(\"blue\") + 1)')\n #return evi.select([0], ['EVI']).copyProperties(img, property_list)\n return ee.Image(img).select([0], ['EVI']).copyPropert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to read the information from the lens inversion | def read_inversion_info(file_dic):
#print_file_test = open('file_test.txt','w')
if not ( check_inversion_files(file_dic) ):
print 'error(read_inversion_info): problem with lenstool file names'
return 0
file_generate_arcs = file_dic['file_generate_arcs']
info_input_lens = fc.extract... | [
"def lens_info(self):\n try:\n self.tn.write(\"lc\".encode('ascii')+self.eof)\n return(self.read(self.tn.read_until(self.eof, timeout=2)))\n except Exception as ex:\n self.logger.warning(\"Cannot obtain extended lens information: \"+ str(ex))",
"def vector_info(map, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to copy files created by lenstool when doing the lens inversion | def copy_inversion_files(count, file_dic):
if not ( check_inversion_files(file_dic) ):
print 'error(copy_inversion_files): problem with lenstool file names'
return 0
results_directory = 'invertion_stat_results'
if results_directory[len(results_directory)-1] != '/':
results_directory ... | [
"def copy_files():\n\n # Load the Knifey-Spoony dataset.\n # This is very fast as it only gathers lists of the files\n # and does not actually load the images into memory.\n dataset = load()\n\n # Copy the files to separate training- and test-dirs.\n dataset.copy_files(train_dir=train_dir, test_di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if 'file_dic' has all file names created by lenstool inversion | def check_inversion_files(file_dic):
patern_dic = {'file_generate_arcs' : "", \
'file_source' : "", \
'file_make_inversion' : "", \
'file_best_fit' : "", \
'file_chires' : ""}
for i in patern_dic.keys():
os.path.isfile(file_dic[i])... | [
"def has_key(self, filename):\n return filename in self.keys",
"def has_file_key(self, key):\n return self.fileList.has_key( key )",
"def has_at_least_one_relevant_key(file_as_dict):\n for key in file_as_dict.keys():\n b = True\n for unwanted_key in non_selected_keys:\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merges multiple pose transformation into a single one. | def compose(pose_list: List['PoseTransform']) -> 'PoseTransform':
assert isinstance(pose_list, list)
pose_composed = pose_list[0]
for pose_current in pose_list[1:]:
# shrink the poses from the left
# assert pose_current._r is not None
# assert pose_current._t ... | [
"def trajectory_transform_inplace(\n trajectories: Trajectories,\n pose_transform_pre: PoseTransform = PoseTransform(),\n pose_transform_post: PoseTransform = PoseTransform()\n):\n for timestamp, sensor_id, pose in flatten(trajectories):\n trajectories[timestamp, sensor_id] = PoseTran... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check weekly how many audios are on audios/ folder and compare them with the ones from active episodes. If they don't match, old files will be erased from file system. | def clean_old_data():
logger.info('Cleaning standalone files on disk...')
for absolute_path in glob.glob(MEDIA_URL + '*'):
file_name = os.path.basename(absolute_path)
try:
relative_path = os.path.join(AUDIOS_URL, file_name)
audio = Audio.objects.get(filename=relative_path... | [
"def audio_files_check(argvs):\n os_cpu_n = os.cpu_count()\n totflist = []\n hashmap = {} # list of audio files were found\n t0 = time.time() # Program time start marker\n mypath = r''.join(map(str, argvs[0:1])) # Path for search (argument)\n my... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns tuple of (prefixer, cigar) from concatenated bytes or bytearray of data couple made up of qb64 or qb64b versions of pre+sig couple is used for receipts signed by nontransferable prefix keys | def decouple(data, deletive=False):
if isinstance(data, bytearray):
if not deletive:
data = bytearray(data) # make copy so does not delete underlying data
elif isinstance(data, memoryview):
data = bytearray(data)
elif hasattr(data, "encode"):
data = bytearray(data.encode... | [
"def multiTxPrefixEncoded():\n return ByteArray([\n 0x01, 0x00, 0x01, 0x00, # Version [0]\n 0x01, # Varint for number of input transactions [4]\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, # [5]\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns tuple of (diger, prefixer, cigar) from concatenated bytes of data triple made up of qb64 or qb64b versions of dig+pre+sig triple is used for escrows of unverified receipts signed by nontransferable prefix keys | def detriple(data, deletive=False):
if isinstance(data, bytearray):
if not deletive:
data = bytearray(data) # make copy so does not delete underlying data
elif isinstance(data, memoryview):
data = bytearray(data)
elif hasattr(data, "encode"):
data = bytearray(data.encode... | [
"def multiTxPrefixEncoded():\n return ByteArray([\n 0x01, 0x00, 0x01, 0x00, # Version [0]\n 0x01, # Varint for number of input transactions [4]\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, # [5]\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns tuple of (ediger, seal prefixer, seal seqner, seal diger, siger) from concatenated bytes of quintuple made up of qb64 or qb64b versions of quntipuple given by concatenation of edig+spre+ssnu+sdig+sig Quintuple is used for unverified escrows of validator receipts signed by transferable prefix keys | def dequintuple(data, deletive=False):
if isinstance(data, bytearray):
if not deletive:
data = bytearray(data) # make copy so does not delete underlying data
elif isinstance(data, memoryview):
data = bytearray(data)
elif hasattr(data, "encode"):
data = bytearray(data.enc... | [
"def der_encode_sig(*args):\n if len(args) == 3:\n v,r,s = args\n elif len(args) == 2:\n r,s = args\n elif len(args) == 1 and isinstance(args[0], tuple):\n return der_encode_sig(*args[0])\n b1, b2 = encode(r, 256), encode(s, 256)\n if len(b1) and changebase(b1[0], 256, 16, 1) in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attaches indexed signatures from sigers to KERI message data from serder | def messagize(serder, sigers):
msg = bytearray(serder.raw) # make copy into new bytearray so can be deleted
count = len(sigers)
counter = Counter(code=CtrDex.ControllerIdxSigs, count=count)
msg.extend(counter.qb64b)
for siger in sigers:
msg.extend(siger.qb64b)
return msg | [
"def sign(self, ser, pubs=None, verfers=None, indexed=True, indices=None):\n signers = []\n\n if pubs is None and verfers is None:\n raise ValueError(\"pubs or verfers required\")\n\n if pubs:\n for pub in pubs:\n verfer = coring.Verfer(qb64=pub) # needed t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attaches receipt couplets from cigars to KERI message data from serder | def receiptize(serder, cigars):
msg = bytearray(serder.raw) # make copy into new bytearray so can be deleted
count = len(cigars)
counter = Counter(code=CtrDex.NonTransReceiptCouples, count=count)
msg.extend(counter.qb64b)
for cigar in cigars:
if cigar.verfer.code not in NonTransDex:
... | [
"def processReceipt(self, serder, cigars):\n # fetch pre dig to process\n ked = serder.ked\n pre = serder.pre\n sn = self.validateSN(ked)\n\n # Only accept receipt if for last seen version of event at sn\n snkey = snKey(pre=pre, sn=sn)\n ldig = self.db.getKeLast(key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create incepting kever and state from inception serder Verify incepting serder against sigers raises ValidationError if not | def __init__(self, serder, sigers, baser=None, estOnly=None):
if baser is None:
baser = Baser() # default name = "main"
self.baser = baser
# may update state as we go because if invalid we fail to finish init
self.version = serder.version # version dispatch ?
ilk... | [
"def update(self, serder, sigers):\n if not self.transferable: # not transferable so no events after inception allowed\n raise ValidationError(\"Unexpected event = {} is nontransferable \"\n \" state.\".format(serder.ked))\n ked = serder.ked\n if se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Not original inception event. So verify event serder and indexed signatures in sigers and update state | def update(self, serder, sigers):
if not self.transferable: # not transferable so no events after inception allowed
raise ValidationError("Unexpected event = {} is nontransferable "
" state.".format(serder.ked))
ked = serder.ked
if serder.pre != se... | [
"async def _check_signature(self, event: EventBase, context: EventContext) -> None:\n signed = event.content[\"third_party_invite\"][\"signed\"]\n token = signed[\"token\"]\n\n prev_state_ids = await context.get_prev_state_ids(\n StateFilter.from_types([(EventTypes.ThirdPartyInvite, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns list of indices of verified signatures for serder, sigers, and verfers. Assigns verfer to appropriate siger based on index If no signatures verify then indices is empty | def verifySigs(self, serder, sigers, verfers):
# verify indexes of attached signatures against verifiers
for siger in sigers:
if siger.index >= len(verfers):
raise ValidationError("Index = {} to large for keys for evt = "
"{}.".format(sig... | [
"def sign(self, ser, pubs=None, verfers=None, indexed=True, indices=None):\n signers = []\n\n if pubs is None and verfers is None:\n raise ValueError(\"pubs or verfers required\")\n\n if pubs:\n for pub in pubs:\n verfer = coring.Verfer(qb64=pub) # needed t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns seal instance of SealLocation if seal validates with respect to Delegator's KEL Location Seal is from Delegate's establishment event Assumes state setup | def validateSeal(self, serder, sigers):
# verify seal pointing delegator event
seal = SealLocation(**serder.ked["da"])
# seal has pre sn ilk dig (prior dig)
ssn = self.validateSN(ked=seal._asdict(), inceptive=False)
# get the dig of the delegating event
key = snKey(pre=... | [
"def seal_is_valid(self):\n pass",
"def get_astral_location(hass):\n from astral import Location\n\n latitude = hass.config.latitude\n longitude = hass.config.longitude\n timezone = hass.config.time_zone.zone\n elevation = hass.config.elevation\n info = ('', '', latitude, longitude, timez... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns kever for its .pre | def kever(self):
return self.kevers[self.pre] if self.pre else None | [
"def pre(self):\n return self._pre",
"def svn_info_t_prejfile_get(svn_info_t_self): # real signature unknown; restored from __doc__\n return \"\"",
"def is_premed(self):\n if self.get('major',''):\n return('pre-med' in self['major'].split(\"|\"))\n return(False)",
"def prev_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract and return instance of klas from input message stream, ims, given stream state, cold, is txt or bny. Inits klas from ims using qb64b or qb2 parameter based on cold. | def _extract(ims, klas, cold=Colds.txt):
if cold == Colds.txt:
return klas(qb64b=ims, strip=True)
elif cold == Colds.bny:
return klas(qb2=ims, strip=True)
else:
raise ColdStartError("Invalid stream state cold={}.".format(cold)) | [
"def extract(ims, klas, cold=Colds.txt):\n if cold == Colds.txt:\n return klas(qb64b=ims, strip=True)\n elif cold == Colds.bny:\n return klas(qb2=ims, strip=True)\n else:\n raise kering.ColdStartError(\"Invalid stream state cold={}.\".format(cold))",
"def _ext... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns generator to extract and return instance of klas from input message stream, ims, given stream state, cold, is txt or bny. Inits klas from ims using qb64b or qb2 parameter based on cold. Yields if not enough bytes in ims to fill out klas instance. | def _extractor(ims, klas, cold=Colds.txt):
while True:
try:
if cold == Colds.txt:
return klas(qb64b=ims, strip=True)
elif cold == Colds.bny:
return klas(qb2=ims, strip=True)
else:
raise ColdSt... | [
"def _extractor(ims, klas, cold=Colds.txt, abort=False):\n while True:\n try:\n if cold == Colds.txt:\n return klas(qb64b=ims, strip=True)\n elif cold == Colds.bny:\n return klas(qb2=ims, strip=True)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns generator to process all messages from incoming message stream, ims until ims is exhausted (empty) then returns. If ims not provided then process messages from .ims Must be framed. | def allProcessor(self, ims=None, framed=None, pipeline=None, cloned=None):
if ims is not None: # needs bytearray not bytes since deletes as processes
if not isinstance(ims, bytearray):
ims = bytearray(ims) # so make bytearray copy
else:
ims = self.ims # use ins... | [
"def processor(self, ims=None, framed=None, pipeline=None, cloned=None):\n if ims is not None: # needs bytearray not bytes since deletes as processes\n if not isinstance(ims, bytearray):\n ims = bytearray(ims) # so make bytearray copy\n else:\n ims = self.ims # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns generator to continually process messages from incoming message stream, ims. Yields waits whenever ims empty. If ims not provided then process messages from .ims | def processor(self, ims=None, framed=None, pipeline=None, cloned=None):
if ims is not None: # needs bytearray not bytes since deletes as processes
if not isinstance(ims, bytearray):
ims = bytearray(ims) # so make bytearray copy
else:
ims = self.ims # use instan... | [
"def processor(self, ims=None):\n if ims is not None: # needs bytearray not bytes since deletes as processes\n if not isinstance(ims, bytearray):\n ims = bytearray(ims) # so make bytearray copy\n else:\n ims = self.client.rxbs # use instance attribute by default... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes one messages from incoming message stream, ims, when provided. Otherwise process message from .ims Returns once one message is processed. Convenience executor for .processOneGen when ims is not live, i.e. fixed | def processOne(self, ims=None, framed=True, pipeline=False, cloned=False):
processor = self.msgProcessor(ims=ims,
framed=framed,
pipeline=pipeline,
cloned=cloned)
while True:
... | [
"def processor(self, ims=None, framed=None, pipeline=None, cloned=None):\n if ims is not None: # needs bytearray not bytes since deletes as processes\n if not isinstance(ims, bytearray):\n ims = bytearray(ims) # so make bytearray copy\n else:\n ims = self.ims # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process one event serder with attached indexd signatures sigers | def processEvent(self, serder, sigers):
# fetch ked ilk pre, sn, dig to see how to process
ked = serder.ked
try: # see if code of pre is supported and matches size of pre
Prefixer(qb64b=serder.preb)
except Exception as ex: # if unsupported code or bad size raises error
... | [
"def verifySigs(self, serder, sigers, verfers):\n # verify indexes of attached signatures against verifiers\n for siger in sigers:\n if siger.index >= len(verfers):\n raise ValidationError(\"Index = {} to large for keys for evt = \"\n \"{}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process one receipt serder with attached cigars | def processReceipt(self, serder, cigars):
# fetch pre dig to process
ked = serder.ked
pre = serder.pre
sn = self.validateSN(ked)
# Only accept receipt if for last seen version of event at sn
snkey = snKey(pre=pre, sn=sn)
ldig = self.db.getKeLast(key=snkey) # r... | [
"def iap_process_receipt(request, receipt_data):\n #TODO To be safer against botting, the receipt_data uniqueness constraint\n # needs to be done atomically.\n if IapReceipt.objects.filter(receipt_data=receipt_data).exists():\n # Already processed this receipt, fail silently.\n return {'balan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process one transferable validator receipt (chit) serder with attached sigers | def processChit(self, serder, sigers):
# fetch pre, dig,seal to process
ked = serder.ked
pre = serder.pre
sn = self.validateSN(ked)
# Only accept receipt if for last seen version of receipted event at sn
ldig = self.db.getKeLast(key=snKey(pre=pre, sn=sn)) # retrieve di... | [
"def processReceipt(self, serder, cigars):\n # fetch pre dig to process\n ked = serder.ked\n pre = serder.pre\n sn = self.validateSN(ked)\n\n # Only accept receipt if for last seen version of event at sn\n snkey = snKey(pre=pre, sn=sn)\n ldig = self.db.getKeLast(key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns Serder instance of establishment event that is authoritative for event in KEL for pre at sn. Returns None if no event at sn accepted in KEL for pre | def fetchEstEvent(self, pre, sn):
found = False
while not found:
dig = bytes(self.db.getKeLast(key=snKey(pre, sn)))
if not dig:
return None
# retrieve event by dig
raw = bytes(self.db.getEvt(key=dgKey(pre=pre, dig=dig)))
if no... | [
"def processEvent(self, serder, sigers):\n # fetch ked ilk pre, sn, dig to see how to process\n ked = serder.ked\n try: # see if code of pre is supported and matches size of pre\n Prefixer(qb64b=serder.preb)\n except Exception as ex: # if unsupported code or bad size raises... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate throush escrows and process any that may now be finalized | def processEscrows(self):
try:
self.processOutOfOrders()
self.processPartials()
self.processDuplicitous()
self.processUnverifieds()
self.processTransUnverifieds()
except Exception as ex: # log diagnostics errors etc
if logger.isE... | [
"def finalize(self):\n for iterator in six.itervalues(self._iterators):\n iterator.finalize()",
"def process_entire_queue(self):\r\n\t\twhile self.queue:\r\n\t\t\tself._dequeue()",
"def process_entire_queue(self):\r\n while self.queue:\r\n self._dequeue()",
"def processOutO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process events escrowed by Kever that were only partially fulfilled. Either due to missing signatures or missing dependent events like a delegating event. But event has at least one verified signature. Escrowed items are indexed in database table keyed by prefix and sequence number with duplicates inserted in insertion... | def processPartials(self):
ims = bytearray()
key = ekey = b'' # both start same. when not same means escrows found
while True: # break when done
for ekey, edig in self.db.getPseItemsNextIter(key=key):
try:
pre, sn = splitKeySN(ekey) # get pre a... | [
"def processDuplicitous(self):\n\n ims = bytearray()\n key = ekey = b'' # both start same. when not same means escrows found\n while True: # break when done\n for ekey, edig in self.db.getLdeItemsNextIter(key=key):\n try:\n pre, sn = splitKeySN(eke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process events escrowed by Kever that are recieved outoforder. An event is out of order if its prior event has not been accepted into its KEL. Without the prior event there is no way to know the key state and therefore no way to verify signatures on the outoforder event. Escrowed items are indexed in database table key... | def processOutOfOrders(self):
ims = bytearray()
key = ekey = b'' # both start same. when not same means escrows found
while True: # break when done
for ekey, edig in self.db.getOoeItemsNextIter(key=key):
try:
pre, sn = splitKeySN(ekey) # get pr... | [
"def processDuplicitous(self):\n\n ims = bytearray()\n key = ekey = b'' # both start same. when not same means escrows found\n while True: # break when done\n for ekey, edig in self.db.getLdeItemsNextIter(key=key):\n try:\n pre, sn = splitKeySN(eke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process event receipts escrowed by Kever that are unverified. A receipt is unverified if the associated event has not been accepted into its KEL. Without the event there is no way to know where to store the receipt couplets. The escrow is a triple with dig+spre+sig the verified receipt is just the couple spre+sig that ... | def processUnverifieds(self):
ims = bytearray()
key = ekey = b'' # both start same. when not same means escrows found
while True: # break when done
for ekey, etriplet in self.db.getUreItemsNextIter(key=key):
try:
pre, sn = splitKeySN(ekey) # ge... | [
"def processTransUnverifieds(self):\n\n ims = bytearray()\n key = ekey = b'' # both start same. when not same means escrows found\n while True: # break when done\n for ekey, equinlet in self.db.getVreItemsNextIter(key=key):\n try:\n pre, sn = split... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process event receipts from transferable identifiers (validators) escrowed by Kever that are unverified. A transferable receipt is unverified if either the receipted event has not been accepted into the receipted's KEL or the establishment event of the receiptor has not been accepted into the receipter's KEL. Without e... | def processTransUnverifieds(self):
ims = bytearray()
key = ekey = b'' # both start same. when not same means escrows found
while True: # break when done
for ekey, equinlet in self.db.getVreItemsNextIter(key=key):
try:
pre, sn = splitKeySN(ekey) ... | [
"def processUnverifieds(self):\n\n ims = bytearray()\n key = ekey = b'' # both start same. when not same means escrows found\n while True: # break when done\n for ekey, etriplet in self.db.getUreItemsNextIter(key=key):\n try:\n pre, sn = splitKeySN... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process events escrowed by Kever that are likely duplicitous. An event is likely duplicitous if a different version of event already has been accepted into the KEL. Escrowed items are indexed in database table keyed by prefix and sn with duplicates given by different dig inserted in insertion order. This allows FIFO pr... | def processDuplicitous(self):
ims = bytearray()
key = ekey = b'' # both start same. when not same means escrows found
while True: # break when done
for ekey, edig in self.db.getLdeItemsNextIter(key=key):
try:
pre, sn = splitKeySN(ekey) # get pr... | [
"def processOutOfOrders(self):\n\n ims = bytearray()\n key = ekey = b'' # both start same. when not same means escrows found\n while True: # break when done\n for ekey, edig in self.db.getOoeItemsNextIter(key=key):\n try:\n pre, sn = splitKeySN(eke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for brains_get | def test_brains_get(self):
pass | [
"def test_get_boat(self):\n pass",
"def test_get_ban(self):\n pass",
"def test_market_bonds_get(self):\n pass",
"def test_list_bills(self):\n pass",
"def test_braces_disabled():\n assert get_html(BRACES_TEXT) == \"<p>I am a {{braces}} example.</p>\"",
"def test_retrieve_bill... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for brains_id_get | def test_brains_id_get(self):
pass | [
"def test_ambassadors_id_get(self):\n pass",
"def test_volleyballcoachs_id_get(self):\n pass",
"def test_books_id_get(self):\n pass",
"def test_catalogidentifiers_id_get(self):\n pass",
"def test_australianfootballleagues_id_get(self):\n pass",
"def test_drugs_id_get(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the projection matrix from the current viewing position. elev stores the elevation angle in the z plane azim stores the azimuth angle in the x,y plane dist is the distance of the eye viewing point from the object point. | def get_proj(self):
relev, razim = np.pi * self.elev/180, np.pi * self.azim/180
xmin, xmax = self.get_xlim3d()
ymin, ymax = self.get_ylim3d()
zmin, zmax = self.get_zlim3d()
# transform to uniform world coordinates 0-1.0,0-1.0,0-1.0
worldM = proj3d.world_transformation(x... | [
"def get_proj(self):\n relev, razim = np.pi * self.elev/180, np.pi * self.azim/180\n\n xmin, xmax = self.get_xlim3d()/self.pbaspect[0]\n ymin, ymax = self.get_ylim3d()/self.pbaspect[1]\n zmin, zmax = self.get_zlim3d()/self.pbaspect[2]\n\n # transform to uniform world coordinates 0-1.0,0-1.0,0-1.0 \n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes mouse button callbacks to enable 3D rotation of the axes. Also optionally sets the mouse buttons for 3D rotation and zooming. ============ ======================================================= Argument Description ============ ======================================================= rotate_btn The integer ... | def mouse_init(self, rotate_btn=1, zoom_btn=3):
self.button_pressed = None
canv = self.figure.canvas
if canv != None:
c1 = canv.mpl_connect('motion_notify_event', self._on_move)
c2 = canv.mpl_connect('button_press_event', self._button_press)
c3 = canv.mpl_conn... | [
"def mouse_init(self, rotate_btn=1, pan_btn=2, zoom_btn=3):\n self.button_pressed = None\n # coerce scalars into array-like, then convert into\n # a regular list to avoid comparisons against None\n # which breaks in recent versions of numpy.\n self._rotate_btn = np.atleast_1d(rota... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return x string formatted. This function will use the attribute self.fmt_xdata if it is callable, else will fall back on the xaxis major formatter | def format_xdata(self, x):
try:
return self.fmt_xdata(x)
except TypeError:
fmt = self.w_xaxis.get_major_formatter()
return sensible_format_data(fmt, x) | [
"def x_formatter_cb( self, ax ):\n ax.set_xlim( xmin=self.begin_num,xmax=self.end_num )\n dl = common.PrettyDateLocator()\n df = common.PrettyDateFormatter( dl )\n ax.xaxis.set_major_locator( dl )\n ax.xaxis.set_major_formatter( df )\n ax.xaxis.set_clip_on(False)\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return y string formatted. This function will use the attribute self.fmt_ydata if it is callable, else will fall back on the yaxis major formatter | def format_ydata(self, y):
try:
return self.fmt_ydata(y)
except TypeError:
fmt = self.w_yaxis.get_major_formatter()
return sensible_format_data(fmt, y) | [
"def get_max_y(self, format=Array):\n try:\n yy = self.get_data_y(format)\n low, high = self.calc_indexes()\n yy = yy[low:high + 1]\n y = [float(e) for e in yy]\n except:\n y = []\n if len(y) == 0:\n return \"-\"\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return z string formatted. This function will use the attribute self.fmt_zdata if it is callable, else will fall back on the yaxis major formatter | def format_zdata(self, z):
try:
return self.fmt_zdata(z)
except (AttributeError, TypeError):
fmt = self.w_zaxis.get_major_formatter()
return sensible_format_data(fmt, z) | [
"def get_zlabel(self):\n label = self.zaxis.get_label()\n return label.get_text()",
"def get_zlabel(self):\n return self._frame.GetZaxis().GetTitle()",
"def format_ydata(self, y):\n try:\n return self.fmt_ydata(y)\n except TypeError:\n fmt = self.w_yaxis.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the CIEDE2000 ColorDifference from RGB inputs. | def rgb_cie94_color_difference(input: Tensor, target: Tensor, **kwargs) -> Tensor:
return cie94_color_difference(*map(rgb_to_cielab, (input, target)), **kwargs) | [
"def rgb_ciede2000_color_difference(input: Tensor, target: Tensor, **kwargs) -> Tensor:\n return ciede2000_color_difference(*map(rgb_to_cielab, (input, target)), **kwargs)",
"def delta_e_cie1976(color1, color2):\r\n\r\n color1_vector = _get_lab_color1_vector(color1)\r\n color2_matrix = _get_lab_color2_ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the CIEDE2000 ColorDifference from RGB inputs. | def rgb_ciede2000_color_difference(input: Tensor, target: Tensor, **kwargs) -> Tensor:
return ciede2000_color_difference(*map(rgb_to_cielab, (input, target)), **kwargs) | [
"def rgb_cie94_color_difference(input: Tensor, target: Tensor, **kwargs) -> Tensor:\n return cie94_color_difference(*map(rgb_to_cielab, (input, target)), **kwargs)",
"def delta_e_cie1976(color1, color2):\r\n\r\n color1_vector = _get_lab_color1_vector(color1)\r\n color2_matrix = _get_lab_color2_matrix(col... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Synchronize the code repositories with upstreams. This is called once on the code host with a list of all components to synchronize. The script should fetch from upstream remotes, sync with a SCM server, or whatever your system does. The command should return a mapping of each component to an object containing a unique... | def synchronize(*components):
return {
# a component that needs to be built
"buildable": {
"token": "7be0db612ea365e1d9410763198bb79a9e28dfd6",
"buildhost": "build-01",
},
# a component that just gets deployed without build
"simple": {
"to... | [
"def sync_wikiversions(hosts, cfg):\n stats = log.Stats(cfg['statsd_host'], int(cfg['statsd_port']))\n with log.Timer('sync_wikiversions', stats):\n compile_wikiversions('stage', cfg)\n\n rsync = ssh.Job(hosts, user=cfg['ssh_user']).shuffle()\n rsync.command(\n 'sudo -u mwdeplo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deploy a component on a host. This is executed on each host to deploy. Rollingpin will pass a list of components with their build tokens as generated by the `build` command. This command is required if you want to run "d" commands in rollingpin. | def deploy(*components_with_tokens):
for component_with_token in components_with_tokens:
component, sep, build_token = component_with_token.partition("@")
assert sep == "@"
# TODO: put your deploy logic here! | [
"def deploy_build(args, pmt_entry, pbt):\n host = pmt_entry['host']\n phase = pmt_entry['phase']\n\n log.info(\" == start deploying the build for host %s at phase %s\", host, phase)\n\n # checkout the branch\n d_branch = pbt[phase]['branch']\n utils.run_command(\"cd \" + args.shoowo_dir + \";git c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restart a named service. This is executed on each host to restart a service. This command is required if you want to run "r" commands in rollingpin. | def restart(service):
# TODO: replace this with your relevant restart logic
assert service.isalpha()
run("service", service, "restart") | [
"def restart_service(name):\n subprocess.run([\n 'systemctl',\n 'restart',\n name\n ], check=True)",
"def restart_service(self, host_name):\n url = 'iscsi/service/restart/'\n params = {\n \"hostName\": host_name\n }\n self.send_http_api(url=url, pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Do basic setup and dispatch commands to their handlers. Rollingpin executes commands that take the format of "command [args...]". With the SSH transport, this program is executed with sudo and the command is passed as the first argument. e.g. deploy project maps to sudo /usr/local/bin/deploy deploy project Additionally... | def main(commands):
progname = os.path.basename(sys.argv[0])
if len(sys.argv) < 2:
print("USAGE: {} COMMAND [ARG...]".format(progname), file=sys.stderr)
sys.exit(1)
command_name = sys.argv[1]
args = sys.argv[2:]
def fatal_error(message_fmt, *args):
message = message_fmt.fo... | [
"def cli_runner(args):\n config = CLIConfig()\n\n set_logger_levels(args.debug)\n\n LOGGER.info('Issues? Report here: https://github.com/airbnb/streamalert/issues')\n\n cmds = {\n 'app': lambda opts: app_handler(opts, config),\n 'athena': lambda opts: athena_handler(opts, config),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calcula uma aproximação numérica para a integral definida de da função f dada, entre a e b, com n subintervalos (pares), pela regra de Simpson | def integracao_simpson(f, a, b, n):
if n % 2:
raise ValueError("n deve ser par (n=%d)" % n)
h = (b - a) / n
s = f(a) + f(b)
for i in range(1, n, 2):
s += 4 * f(a + i * h)
for i in range(2, n-1, 2):
s += 2 * f(a + i * h)
return s * h / 3 | [
"def simpson_integrate(f, a, b, N, points):\n total_sum = 0\n total_sum += f(points[0]) + f(points[N])\n\n first_sum = 0\n for i in range(1, N // 2):\n first_sum += f(points[2 * i])\n first_sum *= 2\n total_sum += first_sum\n\n second_sum = 0\n for j in range(1, (N // 2) + 1):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the unnormalized probabilities from hidden states. Optionally divide logits by a temperature, in order to influence predictions at | def get_logits(self, hidden_states: torch.FloatTensor,
temperature: float = 1.0):
return self.logits(hidden_states) / temperature | [
"def apply_temperature(prob, temperature):\r\n # Apply temperature\r\n if temperature != 1:\r\n # Inverse sigmoid\r\n x = -np.log(1 / prob - 1)\r\n # Apply temperature to sigmoid function\r\n prob = 1 / (1 + np.exp(-x / temperature))\r\n return prob",
"def probabilities_hidden... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the outside temperature as a PiecewiseConstant in the destination timezone. | def outside_temp(self) -> models.PiecewiseConstant:
month = MONTH_NAMES.index(self.event_month) + 1
wx_station = self.nearest_weather_station()
temp_profile = caimira.data.weather.mean_hourly_temperatures(wx_station = wx_station[0], month = MONTH_NAMES.index(self.event_month) + 1)
_, u... | [
"def ozone(self) -> float | None:\n return round_state(self._get_sensor_value(API_O3))",
"def solar_constant():\n return 1367.",
"def get_outdoor_temperature(self):\n if self.has_outdoor_temperature():\n outdoor_temp = self._get_thermostat_key(\"outdoor_temperature\")\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the nearest weather station (which has valid data) for this form | def nearest_weather_station(self) -> caimira.data.weather.WxStationRecordType:
return caimira.data.weather.nearest_wx_station(
longitude=self.location_longitude, latitude=self.location_latitude
) | [
"def get_nearest_station(latitude, longitude):\n url = '{}?api_key={}&filter[latitude]={}&filter[longitude]={}&sort=distance'.format(MBTA_BASE_URL,MBTA_API_KEY,latitude,longitude)\n # print(url)\n station_json = get_json(url)\n # print(station_json)\n station_name = station_json['data'][0]['attribute... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the presence interval given the start and end times (in minutes), and a number of monotonic, nonoverlapping, but potentially unsorted, breaks (also in minutes). | def present_interval(
self,
start: int,
finish: int,
breaks: typing.Optional[models.BoundarySequence_t] = None,
) -> models.Interval:
if not breaks:
# If there are no breaks, the interval is the start and end.
return models.SpecificInte... | [
"def compute_all_minutes(\n opens_in_ns: np.ndarray,\n break_starts_in_ns: np.ndarray,\n break_ends_in_ns: np.ndarray,\n closes_in_ns: np.ndarray,\n) -> np.ndarray:\n pieces = []\n for open_time, break_start_time, break_end_time, close_time in zip(\n opens_in_ns, break_starts_in_ns, break_e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function that returns the indices of the digits in `nums` that add up to create `target` | def return_indices(nums, target):
indices = []
i = 0
number_found = False
while not number_found:
my_target = nums[i]
for j in range(i+1,len(nums)):
my_target += nums[j]
if my_target == target:
number_found = True
indices =... | [
"def towSum1(nums, target):\n j = None\n lens = len(nums)\n for i in range(lens):\n expected_num = target - nums[i]\n if expected_num in nums:\n # 如果 expected_num 是 nums[i]本身的话就跳过\n if (nums.count(expected_num) == 1) & (expected_num == nums[i]):\n continue... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the active channel on the analyzer | def active_channel(self, channel):
old_timeout = self.resource.timeout
self.resource.timeout = 500
if channel in self.channel_list:
self.scpi.set_active_channel(channel)
else:
print('Channel %i not in list of channels. Create channel first'
% cha... | [
"def set_active_channel(self, channel=1):\n scpi_command = scpi_preprocess(\":INST:NSEL {:}\", channel)\n self.write(scpi_command)",
"def _switch_channel(self) -> None:\n if hasattr(self.instrument, \"channel_number\"):\n instr = cast(Instrument, self.instrument)\n instr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get an skrf.Frequency object for the current channel | def get_frequency(self, **kwargs):
#self.resource.clear()
channel = kwargs.get("channel", self.active_channel)
use_log = "LOG" in self.scpi.query_sweep_type(channel).upper()
f_start = self.scpi.query_f_start(channel)
f_stop = self.scpi.query_f_stop(channel)
f_npoints = se... | [
"def get_frequency(self, c, channel=-1):\n if (channel == -1):\n channel = self.guess_channel()\n\n try:\n frequency = self.binding.get_frequency_num(channel)\n return frequency * THz;\n except Exception, e:\n return self.handle_wavemeter_error(e)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
retrieve traces as 1port networks from a list returned by get_list_of_traces | def get_traces(self, traces, **kwargs):
self.resource.clear()
sweep = kwargs.get("sweep", False)
name_prefix = kwargs.get("name_prefix", "")
if name_prefix:
name_prefix += " - "
channels = OrderedDict()
for trace in traces:
ch = trace["channel"]
... | [
"def get_traces(self):\n\n self.rank = 0\n traces = []\n sub_traces = []\n current = []\n with open(self.file_path, 'r') as f:\n for line in f:\n current.append(line.strip('\\n').replace('<', '\\<').replace('>', '\\>'))\n sub_traces.append(current)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MINIJ Symmetric positive definite matrix MIN(i,j). A = MINIJ(N) is the NbyN symmetric positive definite matrix with A(i,j) = MIN(i,j). | def minij(n):
o = np.outer(np.ones(n), np.arange(1, n + 1))
ot = o.T
a = np.where(o < ot, o, ot)
return a | [
"def mat_min(M):\n # take a matrix we pass in, and fill the diagonal with the matrix max. This is\n # so that we don't grab any values from the diag.\n np.fill_diagonal(M, float(\"inf\"))\n\n # figure out the indices of the cell with the lowest value.\n i, j = np.unravel_index(M.argmin(), M.shape)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sign a dict of query params for private API calls | def sign(self, params: Dict[str, Any]) -> str:
assert self.secret is not None, "A client secret is required to sign requests."
query = urlencode(params)
signature = hmac.new(self.secret.encode(), query.encode(), hashlib.sha512)
return signature.hexdigest() | [
"def get_signed(self, params):\n _params = copy.copy(params)\n sort_params = sorted(_params.items(), key=operator.itemgetter(0))\n sort_params = dict(sort_params)\n sort_params['secret_key'] = self.secret\n string = urllib.parse.urlencode(sort_params)\n _sign = hashlib.md5(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and save an User with the given email, date username and password. | def _create_user(self, username, email, password):
now = datetime.now()
if username is None:
raise ValueError('Must include username')
if email is None:
raise ValueError('Must include email')
email = self.normalize_email(email)
user = self.model(
email=self.normalize_email(email),
username=usernam... | [
"def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None):\n \n \n if not email:\n raise ValueError('Users must have an email address')\n\n user = self.model(\n username=username,\n email=self.normalize_email(email)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the network object. | def __init__(self, network: Network):
self.graph = network.graph | [
"def initialize_networks(self):",
"def __init__(self, amount_nodes, amount_links):\n self.nodes = {}\n self.__createNetwork__(amount_nodes, amount_links)",
"def create_network(self):\n #Create the network\n self.network = Network(\"50.19.23.117\", 8080)",
"def initialize_networkHan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the graph of upregulated genes. | def get_upregulated_genes_network(self) -> Graph:
logger.info("In get_upregulated_genes_network()")
deg_graph = self.graph.copy() # deep copy graph
not_diff_expr = self.graph.vs(up_regulated_eq=False)
# delete genes which are not differentially expressed or have no connections to othe... | [
"def get_downregulated_genes_network(self) -> Graph:\n logger.info(\"In get_downregulated_genes_network()\")\n\n deg_graph = self.graph.copy() # deep copy graph\n not_diff_expr = self.graph.vs(down_regulated_eq=False)\n\n # delete genes which are not differentially expressed or have no ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the graph of downregulated genes. | def get_downregulated_genes_network(self) -> Graph:
logger.info("In get_downregulated_genes_network()")
deg_graph = self.graph.copy() # deep copy graph
not_diff_expr = self.graph.vs(down_regulated_eq=False)
# delete genes which are not differentially expressed or have no connections t... | [
"def get_upregulated_genes_network(self) -> Graph:\n logger.info(\"In get_upregulated_genes_network()\")\n\n deg_graph = self.graph.copy() # deep copy graph\n not_diff_expr = self.graph.vs(up_regulated_eq=False)\n\n # delete genes which are not differentially expressed or have no connec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the shortest paths graph between differentially expressed + special genes. | def get_shortest_paths_graph(
self,
genes_to_keep: list = None,
keep_isolated_nodes: bool = False,
):
logger.info("In get_shortest_paths_graph()")
sp_graph = self.graph.copy()
weights = list(1 - np.array(sp_graph.es['weight']))
sp_graph.es['weight'] = weights
... | [
"def get_shortest_paths(G, weight):\n sp = []\n for n1, n2 in itertools.combinations(G.nodes(), 2):\n try:\n sp.append(nx.shortest_path(G, n1, n2, weight=weight))\n except nx.NetworkXNoPath: # nodes not connected\n sp.append([])\n # add single nodes as length 0 paths.\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This routine finds the root of a function using Newton's method using a usersupplied Jacobian. It uses Given's rotation for QR_decomposition. | def newton_jacobian(f, x0, Jf, eps=1e-10):
# Initialization
globvar.ncalls = 0
x = np.copy(x0)
n = len(x)
J = np.zeros((n, n), dtype='float64')
fx = f(x)
# Begin root search
while True:
globvar.ncalls += 1
# Calculate Jacobian
J = Jf(x)
# Decompose and ... | [
"def _root(fun, x0, tol):\n log_status.count = 0\n sol = optimize.root(fun=fun, x0=x0,\n # method='broyden1',\n method='krylov',\n # method='df-sane',\n tol=tol,\n # options={'nit': 3},\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
生成某只股票的全部退市时间信息 info dict 形式 有关状态的说明: 1上市,2暂停上市,3恢复上市,4终止上市,5摘牌,6退市整理期 ++++++ | InnerCode | SecuCode | ListedDate | ChangeDate | ChangeType | ++++++ | def gen_delisted_info(code, timestamp):
conn = generate_mysqlconnection()
# 注意如果不加引号的报错: Warning: (1292, "Truncated incorrect DOUBLE value: 'X11098'")
query_sql = """
SELECT A.InnerCode,A.SecuCode,A.ListedDate,B.ChangeDate,B.ChangeType
from stk_liststatus B,const_secumainall A WHERE
A.Inner... | [
"def get_info(self):\n now = self.when()\n return {\n 'time': now.strftime('%I:%M %p'),\n 'day': now.strftime('%A'),\n 'cycle': self.cycles.cycle_for_time(now.time())\n }",
"def determineUnitHistory():\n\tunitTracker = Unitiser()\n\t\n\timport transactions\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the distance matrix where each element m[i][j] is the distance between X1[i] and X2[j]. | def compute_dist_matrix(X1, X2, distance):
N, M = X1.shape[0], X2.shape[0]
dist_matrix = np.zeros((N, M))
for i in range(N):
for j in range(M):
dist_matrix[i][j] = dist(X1[i], X2[j], distance=distance)
return dist_matrix | [
"def compute_distances(X1, X2):\n M = X1.shape[0]\n N = X2.shape[0]\n assert X1.shape[1] == X2.shape[1]\n\n dists = np.zeros((M, N))\n\n # YOUR CODE HERE\n # Compute the L2 distance between all X1 features and X2 features.\n # Don't use any for loop, and store the result in dists.\n #\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the file and return the class EvenMorePizza | def ReadInputFile(file:int)->EvenMorePizza:
self.files = ('a_example.in','b_little_bit_of_everything.in', 'c_many_ingredients.in','d_many_pizzas.in','e_many_teams.in')
EvenMorePizza temporalValue
file = open(files[file])#open the file
data = doc.Read().strip(' ,\n').split('\n')
file.close(... | [
"def load_food_info(filename: str):\n result = FoodDB()\n\n with open(filename, \"r\") as f:\n for this_line in f:\n this_line = this_line.strip()\n if \"\" != this_line:\n # we have one food line..\n # format is abc def ghi (contains fish[, peanuts])... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
retruns sprites for the UI | def get_sprites(self):
return self.sprites | [
"def sprites():\n return Globals.instance.sprites",
"def get_sprite(idx):\n #print \"in get_sprite: idx = %s\" % str(idx)\n return _sprite_list[idx]",
"def get_sprite(self):\n return self.sprite",
"def get_sprites(self, file, width, height, D, U, R, L):\n pygame.sprite.Sprite.__init__(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean local build directory | def clean_local():
local('rm -fr build')
local('mkdir -p build') | [
"def clean(self):\n\t\tif os.path.isdir(self.paths['build']):\n\t\t\tshutil.rmtree(self.paths['build'])",
"def _clean_native_build():\n rmtree(BUILD_DIR)",
"def clean(ctx):\n ctx.run(f\"python setup.py clean\")\n dist = ROOT.joinpath(\"dist\")\n build = ROOT.joinpath(\"build\")\n print(f\"[clean]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |