query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
SetElement(itkArray2DD self, unsigned long long row, unsigned long long col, double const & value) | def SetElement(self, row: 'unsigned long long', col: 'unsigned long long', value: 'double const &') -> "void":
return _itkArray2DPython.itkArray2DD_SetElement(self, row, col, value) | [
"def SetElement(self, row: 'unsigned long long', col: 'unsigned long long', value: 'float const &') -> \"void\":\n return _itkArray2DPython.itkArray2DF_SetElement(self, row, col, value)",
"def SetElement(self, row: 'unsigned long long', col: 'unsigned long long', value: 'unsigned int const &') -> \"void\":... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SetSize(itkArray2DD self, unsigned int m, unsigned int n) | def SetSize(self, m: 'unsigned int', n: 'unsigned int') -> "void":
return _itkArray2DPython.itkArray2DD_SetSize(self, m, n) | [
"def SetSize(self, m: 'unsigned int', n: 'unsigned int') -> \"void\":\n return _itkArray2DPython.itkArray2DF_SetSize(self, m, n)",
"def SetSize(self, m: 'unsigned int', n: 'unsigned int') -> \"void\":\n return _itkArray2DPython.itkArray2DUI_SetSize(self, m, n)",
"def set_max_noutput_items(self, m:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
__init__(itkArray2DF self) > itkArray2DF __init__(itkArray2DF self, unsigned int rows, unsigned int cols) > itkArray2DF __init__(itkArray2DF self, itkArray2DF array) > itkArray2DF __init__(itkArray2DF self, vnl_matrixF matrix) > itkArray2DF | def __init__(self, *args):
_itkArray2DPython.itkArray2DF_swiginit(self, _itkArray2DPython.new_itkArray2DF(*args)) | [
"def __init__(self, *args):\n _itkArray2DPython.itkArray2DD_swiginit(self, _itkArray2DPython.new_itkArray2DD(*args))",
"def __init__(self, *args):\n _itkMatrixPython.itkMatrixD22_swiginit(self, _itkMatrixPython.new_itkMatrixD22(*args))",
"def __init__(self, *args):\n _itkArray2DPython.itkAr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill(itkArray2DF self, float const & v) | def Fill(self, v: 'float const &') -> "void":
return _itkArray2DPython.itkArray2DF_Fill(self, v) | [
"def Fill(self, v: 'double const &') -> \"void\":\n return _itkArray2DPython.itkArray2DD_Fill(self, v)",
"def Fill(self, v: 'unsigned int const &') -> \"void\":\n return _itkArray2DPython.itkArray2DUI_Fill(self, v)",
"def Fill(self, value: 'float const &') -> \"void\":\n return _itkMatrixPy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetElement(itkArray2DF self, unsigned long long row, unsigned long long col) > float const & | def GetElement(self, row: 'unsigned long long', col: 'unsigned long long') -> "float const &":
return _itkArray2DPython.itkArray2DF_GetElement(self, row, col) | [
"def GetElement(self, row: 'unsigned long long', col: 'unsigned long long') -> \"double const &\":\n return _itkArray2DPython.itkArray2DD_GetElement(self, row, col)",
"def __getitem__(self, *args):\n return _RMF_HDF5.Floats___getitem__(self, *args)",
"def __getitem__(self, *args) -> \"std::vector<... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SetElement(itkArray2DF self, unsigned long long row, unsigned long long col, float const & value) | def SetElement(self, row: 'unsigned long long', col: 'unsigned long long', value: 'float const &') -> "void":
return _itkArray2DPython.itkArray2DF_SetElement(self, row, col, value) | [
"def SetElement(self, row: 'unsigned long long', col: 'unsigned long long', value: 'double const &') -> \"void\":\n return _itkArray2DPython.itkArray2DD_SetElement(self, row, col, value)",
"def SetElement(self, row: 'unsigned long long', col: 'unsigned long long', value: 'unsigned int const &') -> \"void\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SetSize(itkArray2DF self, unsigned int m, unsigned int n) | def SetSize(self, m: 'unsigned int', n: 'unsigned int') -> "void":
return _itkArray2DPython.itkArray2DF_SetSize(self, m, n) | [
"def SetSize(self, m: 'unsigned int', n: 'unsigned int') -> \"void\":\n return _itkArray2DPython.itkArray2DD_SetSize(self, m, n)",
"def SetSize(self, m: 'unsigned int', n: 'unsigned int') -> \"void\":\n return _itkArray2DPython.itkArray2DUI_SetSize(self, m, n)",
"def set_size(self, ijk):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
__init__(itkArray2DUI self) > itkArray2DUI __init__(itkArray2DUI self, unsigned int rows, unsigned int cols) > itkArray2DUI __init__(itkArray2DUI self, itkArray2DUI array) > itkArray2DUI __init__(itkArray2DUI self, vnl_matrixUI matrix) > itkArray2DUI | def __init__(self, *args):
_itkArray2DPython.itkArray2DUI_swiginit(self, _itkArray2DPython.new_itkArray2DUI(*args)) | [
"def __init__(self, *args):\n _itkArray2DPython.itkArray2DD_swiginit(self, _itkArray2DPython.new_itkArray2DD(*args))",
"def __init__(self, *args):\n _itkArray2DPython.itkArray2DF_swiginit(self, _itkArray2DPython.new_itkArray2DF(*args))",
"def __init__(self, *args):\n _itkMatrixPython.itkMat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill(itkArray2DUI self, unsigned int const & v) | def Fill(self, v: 'unsigned int const &') -> "void":
return _itkArray2DPython.itkArray2DUI_Fill(self, v) | [
"def Fill(self, v: 'double const &') -> \"void\":\n return _itkArray2DPython.itkArray2DD_Fill(self, v)",
"def Fill(self, v: 'float const &') -> \"void\":\n return _itkArray2DPython.itkArray2DF_Fill(self, v)",
"def Fill(self, value: 'double const &') -> \"void\":\n return _itkMatrixPython.it... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetElement(itkArray2DUI self, unsigned long long row, unsigned long long col) > unsigned int const & | def GetElement(self, row: 'unsigned long long', col: 'unsigned long long') -> "unsigned int const &":
return _itkArray2DPython.itkArray2DUI_GetElement(self, row, col) | [
"def GetElement(self, row: 'unsigned long long', col: 'unsigned long long') -> \"double const &\":\n return _itkArray2DPython.itkArray2DD_GetElement(self, row, col)",
"def GetElement(self, row: 'unsigned long long', col: 'unsigned long long') -> \"float const &\":\n return _itkArray2DPython.itkArray... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SetElement(itkArray2DUI self, unsigned long long row, unsigned long long col, unsigned int const & value) | def SetElement(self, row: 'unsigned long long', col: 'unsigned long long', value: 'unsigned int const &') -> "void":
return _itkArray2DPython.itkArray2DUI_SetElement(self, row, col, value) | [
"def SetElement(self, row: 'unsigned long long', col: 'unsigned long long', value: 'double const &') -> \"void\":\n return _itkArray2DPython.itkArray2DD_SetElement(self, row, col, value)",
"def SetElement(self, row: 'unsigned long long', col: 'unsigned long long', value: 'float const &') -> \"void\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SetSize(itkArray2DUI self, unsigned int m, unsigned int n) | def SetSize(self, m: 'unsigned int', n: 'unsigned int') -> "void":
return _itkArray2DPython.itkArray2DUI_SetSize(self, m, n) | [
"def SetSize(self, m: 'unsigned int', n: 'unsigned int') -> \"void\":\n return _itkArray2DPython.itkArray2DD_SetSize(self, m, n)",
"def SetSize(self, m: 'unsigned int', n: 'unsigned int') -> \"void\":\n return _itkArray2DPython.itkArray2DF_SetSize(self, m, n)",
"def SetSize(self, *args) -> \"void\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the next number in line, starting at position pos. Returns number starting position and length as (start, end) or None. | def find_next_number(line, pos=0):
m = number_re.search(line[pos:])
if m:
span = m.span()
return (span[0]+pos,span[1]+pos) | [
"def infer_next_position(raw: str, line_no: int, line_pos: int) -> Tuple[int, int]:\n # No content?\n if not raw:\n return line_no, line_pos\n split = raw.split(\"\\n\")\n return (\n line_no + len(split) - 1,\n line_pos + len(raw) if len(split) == 1 else ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array with all of the numbers in the line | def numbers_in_line(line):
ret = []
pos = 0
while True:
loc = find_next_number(line, pos)
if not loc:
break
ret.append(loc)
pos = loc[1]
return ret | [
"def line2numbers(line):\n l = [x for x in line.strip(\"\\n\").split(\" \")]\n l = filter_(l, lambda a: a != '')\n l = map_(l, lambda a: int(a))\n return l",
"def parse_line(line):\n return [int(v) for v in line.strip().split()]",
"def test_line_to_numbers() -> None:\n assert sc.line_to_nu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a number and returns a boolean stating whether or not the number was in scientific form | def in_scientific_form(val):
return (re.search(r"[+\-]?\d+(\.)?\d*[eE][+\-]?\d+", val)) != None | [
"def is_scientific(number):\n if convert_to_scientific_notation(float(number)) == number:\n return True\n return False",
"def _is_number(s) -> bool:\n try:\n float(s)\n except ValueError:\n return False\n else:\n return True",
"def is_number(n):\n try:\n floa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a cleaned decimal and returns the value's number of trailing zeros | def num_trailing_zeros(val):
val = str(val)
counter = 0
for char in reversed(val):
if char == "." or char != "0" : break
elif char == "0" : counter += 1
return counter | [
"def get_float_decimals(x: float):\n str_rep = str(x).split(\".\")\n if len(str_rep) == 1:\n return 0 \n return len(str_rep[1])",
"def strip_trailing_zeros(cls, s):\n # Make sure there's a '.' in the string.\n if s.find('.') < 0:\n return s\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Odd little function to return the number of significant figures in a number. It kills everything to the right of the e and removes the period | def find_sigfigs(x):
sigfig_re = re.compile("([0-9.]+)")
m = sigfig_re.search("{:e}".format(float(x))) # turn to scientific form
if m:
val = m.group(1).replace(".", "")
while val[-1:] == '0': # remove all trailing zeros
val = val[0:-1]
return len(val)
return 0 # n... | [
"def find_sigfigs(x):\n # Kill everything to the right of the e and remove the period\n m = sigfig_re.search(\"{:e}\".format(float(x)))\n if m:\n val = m.group(1).replace(\".\",\"\")\n while val[-1:]=='0':\n val = val[0:-1]\n return len(val)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Like open, but if filename exists and mode is 'w', produce an error | def safe_open(filename, mode, return_none=False, zap=False):
if 'w' in mode and os.path.exists(filename) and not zap:
rounder_logger.error("ABORT: Output file exists '{}'. Please delete "
"or rename the file and restart the program".format(filename))
if return_none:
retur... | [
"def open_text_file_write_fails(filename, file_mode):\n if 'w' in file_mode:\n raise OSError(\"Mocked failure: Cannot open {} in mode {}\".\n format(filename, file_mode))\n # Delegate the context manager yield to REAL_OPEN_TEXT_FILE()\n return REAL_OPEN_TEXT_FILE(filename, file_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function converts the file format of a .xls or .ods (Open Office) spreadsheet to the file format of an xlsx spreadsheet. | def convert_to_xlsx(fname):
import os
# Cannot use win32 API unless on a Windows machine
try:
import win32com.client as win32
except ImportError:
rounder_logger.error("ABORT: Program is failing to convert spreadsheet "
"to xlsx version spreadsheet. Automated ... | [
"def convert_xlsx_to_xls(inp_dict):\n if inp_dict[\".xlsx\"]:\n for fname in inp_dict[\".xlsx\"]:\n fname = os.path.abspath(fname.encode(\"utf-8\"))\n fname = os.path.abspath(fname.decode(\"utf-8\"))\n excel = EnsureDispatch('Excel.Application')\n wb = excel.Wor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function converts the file format of a .docx or .odt (Open Office) text document to the file format of a plain .txt file | def convert_word_to_txt(fname):
import os
# Cannot use win32 API unless on a Windows machine
try:
import win32com.client as win32
except ImportError:
rounder_logger.error("ABORT: Program is failing to the document to a "
".txt file. Automated conversion only ... | [
"def doc2txt(doc_file, txt_file):\n\treturn _textract_file(doc_file, txt_file)",
"def word2txt():\n pin = 'data/test.docx'\n pout = os.path.splitext(pin)[0] + '.txt'\n\n doc = docx.Document(pin)\n text = '\\n'.join([p.text for p in doc.paragraphs])\n\n with open(pout, 'w') as fout:\n print(t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scans through excel spreadsheet checks if any cells use formulas. If so, it will create a new spreadsheet with the cells containing formulas colored in. The function will return a boolean to indicate whether or not a formula was found. | def check_for_excel_formulas(fname):
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
FILL_RED = PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid')
formula_exists = False
wb = load_workbook(fname) # Open the workbook
for sheetname in wb.sheetnam... | [
"def test_check_for_excel_formulas():\n import shutil\n from openpyxl import load_workbook\n from openpyxl.styles import PatternFill\n\n TEST_FN = \"test_formula.xlsx\"\n NOT_ROUNDED_TEST_FN = \"test_formula_notrounded.xlsx\"\n FILL_RED = PatternFill(start_color='FF0000', end_color='F... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns n to the nearest number | def nearest(n, number):
return math.floor((n / number) + 0.5) * number | [
"def nearest_int(num):\n return int(np.round(num))",
"def nearest10(self, n):\r\n return int(divmod(n + 5, 10)[0]*10)",
"def sqrt_nearest(n):\n a, b = n, 0\n while a != b:\n a, b = a--n//a>>1, a\n return a",
"def _sqrt_nearest(n, a):\n if n <= 0 or a <= 0:\n raise ValueErro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implements the DRB rounding rules for counts. Note that we return a string, so that we can report N < 15 | def round_counts(n):
n = int(n)
assert n == math.floor(n) # make sure it is an integer; shouldn't be needed with above
assert n >= 0
if 0 <= n < 15: return LESS_THAN_15
if 15 <= n <= 99: return str(nearest( n, 10))
if 100 <= n <= 999: return str(nearest( n, 50))
... | [
"def sigfigs(num, n):\r\n return round(num,n-len(str(int(num))))",
"def _round_repeats(self, repeats):\n return int(math.ceil(self.depth_coefficient * repeats))",
"def rounding():\n return int(parameters['rounding'])",
"def round_repeats(repeats):\n return int(math.ceil(depth_coefficient * rep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate through the contents and gather the counts of words | def count_words(self, contents):
wordCounts = {}
for i in self.ngramCounts:
if i == 0: # want the default to be the size of the corpus
total = 0
for line in contents:
words = line.split(" ")
words = [ w.strip() for w in ... | [
"def count_words(filename):",
"def word_count():\n word_counter = Counter()\n\n # read files and count words\n for file_path in Path(INPUTS_PATH).rglob(\"*\"):\n if file_path.is_file():\n print(f\"Processing input file: {file_path.as_posix()}\")\n word_counter += Counter(file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate payprice from normal distribution | def generate_payprice(mu=1., sigma=0.5):
return max(0.1, normal(mu, sigma, 1)[0]) | [
"def get_price():\n return uniform(1.0, 350.0)",
"def generate_prices(reference_price, sigma, total):\n return [random.normalvariate(reference_price, sigma) for i in range(total)]",
"def loyalty_discount(price: float) -> float:\n return sqrt(price)/100",
"def price_relative():",
"def profit_fro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return checkout shipping price. It takes in account all plugins. | def checkout_shipping_price(
*,
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
discounts: Optional[Iterable[DiscountInfo]] = None,
) -> "TaxedMoney":
calculated_checkout_shipping = manager.calculate_checkout_shippi... | [
"def base_checkout_delivery_price(\n checkout_info: \"CheckoutInfo\",\n lines: Iterable[\"CheckoutLineInfo\"] = None,\n) -> Money:\n currency = checkout_info.checkout.currency\n\n shipping_price = base_checkout_undiscounted_delivery_price(checkout_info, lines)\n\n is_shipping_voucher = (\n che... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the total cost of the checkout. Total is a cost of all lines and shipping fees, minus checkout discounts, taxes included. It takes in account all plugins. | def checkout_total(
*,
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
discounts: Optional[Iterable[DiscountInfo]] = None,
) -> "TaxedMoney":
calculated_checkout_total = manager.calculate_checkout_total(
che... | [
"def checkout_line_total(\n *,\n manager: \"PluginsManager\",\n checkout_info: \"CheckoutInfo\",\n lines: Iterable[\"CheckoutLineInfo\"],\n checkout_line_info: \"CheckoutLineInfo\",\n discounts: Iterable[DiscountInfo] = [],\n) -> \"TaxedMoney\":\n address = checkout_info.shipping_address or che... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the total price of provided line, taxes included. It takes in account all plugins. | def checkout_line_total(
*,
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
discounts: Iterable[DiscountInfo] = [],
) -> "TaxedMoney":
address = checkout_info.shipping_address or checkout_info.billing_addr... | [
"def _calc_line_base_price(self, cr, uid, line, context=None):\n return line.price_unit",
"def _amount_line(self, cr, uid, ids, prop, unknow_none, unknow_dict):\n res = {}\n tax_obj = self.pool.get('account.tax')\n cur_obj = self.pool.get('res.currency')\n for line in self.brows... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test main() function. Mock argparse and replace with stubs. Verify process_all_files called with expected arguments. | def test_main_function(self, m_process_all_files, m_argparser):
myargs = StubArgs()
m_argparser.return_value = StubArgumentParser(myargs)
retval = main()
m_process_all_files.assert_called_with(workdir='.', simon_sez=False,
mapfile=None) | [
"def test_main(self):\n results = main(0.1, files)\n # 1\n self.assertEqual(results, \"All Done Successfully\")\n results = main(0.1, get_files_bad_file_path())\n # 2\n self.assertIn(\"skipping to next\", results)\n results = main(0.1, get_files_bad_type())\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute list of statements | def execute_list(self, stmt: List[loxStmtAST.Stmt]) -> None:
for st in stmt:
st.accept(self) | [
"def execute_query_list(cur, conn, query_list):\n try:\n for query in query_list:\n cur.execute(query)\n conn.commit()\n except psycopg2.Error as e:\n print(\"Error executing query list\")\n print(e)",
"def batch_execute(self, sql_list):\n with self.connecti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute block stateemt called by visit_block_stmt | def execute_block(self, stmt: List[loxStmtAST.Stmt], environment: loxenvironment.Environment) -> None:
previous_env: loxenvironment.Environment = self.environment
try:
self.environment = environment
for statement in stmt:
self.execute(statement)
finally:
... | [
"def _parse_block(self):\n self.parse_state = 'block'\n # only variable declarations are currently implemented so this works.\n if self._current_tk_type() == 'TK_VAR':\n self._parse_declarations()\n self._parse_statement_sequence()",
"def execute(self, codeblock):\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get variable (at resolved location) | def lookup_variable(self, name: loxtoken.Token, expr: loxExprAST.Expr) -> object:
distance: int = self.locals.get(expr)
if distance is not None:
return self.environment.get_at(distance, name.lexeme)
else:
return self.globals.get(name) | [
"def get_variable(self, variable):\n return self.session.globalenv[variable][0]",
"def lookup_var(self, var):\n if var in self.binding:\n return self.binding[var]\n elif self.parent is not None:\n return self.parent.lookup_var(var)\n else:\n raise Environme... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if two objects are equal | def is_equal(o1: object, o2: object) -> bool:
if o1 is None and o2 is None:
return True
if o1 is None:
return False
return o1 == o2 | [
"def same(obj1, obj2):\n \n return _py_id(obj1) == _py_id(obj2)",
"def equals(self, obj: object) -> bool:\n ...",
"def __eq__(self, other):\n return are_equal(self, other)",
"def test_equal_on_equal(self):\n a = objects.OpaqueObject(self.bytes_a, enums.OpaqueDataType.NONE)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if one or two operands are numeric (float) | def check_number_operands(operator: loxtoken.Token, op1: Any, op2: Any = None) -> bool:
if op2 is None:
if isinstance(op1, float):
return True
raise_error(LoxRuntimeError, operator, "Operand must be a number.")
else:
if isinstance(op1, float) and isins... | [
"def check_for_float(check):",
"def is_numeric(value):\n return isinstance(value, int) or isinstance(value, float)",
"def is_numeric(value):\n return isinstance(value, int) or isinstance(value, float)",
"def is_float(*args): \n try:\n for i in args:\n float(i)\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the following Keras model | dense| dense | | merge dense | dense| | def test_simple_merge(self):
input_tensor = Input(shape=(3,))
x1 = Dense(4)(input_tensor)
x2 = Dense(5)(x1)
x3 = Dense(6)(x1)
x4 = merge([x2, x3], mode="concat")
x5 = Dense(7)(x4)
model = Model(input=[input_tensor], output=[x5])
input_names = ["data"]
... | [
"def test_merge_multiply(self):\n input_tensor = Input(shape=(3,))\n x1 = Dense(4)(input_tensor)\n x2 = Dense(5)(x1)\n x3 = Dense(5)(x1)\n x4 = merge([x2, x3], mode=\"mul\")\n x5 = Dense(7)(x4)\n\n model = Model(input=[input_tensor], output=[x5])\n input_names... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the following Keras model | dense| dense | | merge dense | dense| | def test_merge_multiply(self):
input_tensor = Input(shape=(3,))
x1 = Dense(4)(input_tensor)
x2 = Dense(5)(x1)
x3 = Dense(5)(x1)
x4 = merge([x2, x3], mode="mul")
x5 = Dense(7)(x4)
model = Model(input=[input_tensor], output=[x5])
input_names = ["data"]
... | [
"def test_simple_merge(self):\n input_tensor = Input(shape=(3,))\n x1 = Dense(4)(input_tensor)\n x2 = Dense(5)(x1)\n x3 = Dense(6)(x1)\n x4 = merge([x2, x3], mode=\"concat\")\n x5 = Dense(7)(x4)\n\n model = Model(input=[input_tensor], output=[x5])\n input_name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert correctness of field_roles attributed to h_order fields. | def test_set_field_roles(h_order: Hub):
expected_roles = [
{"field": "order_id", "role": FieldRole.BUSINESS_KEY},
{"field": "r_timestamp", "role": FieldRole.METADATA},
{"field": "h_order_hashkey", "role": FieldRole.HASHKEY},
{"field": "r_source", "role": FieldRole.METADATA},
]
... | [
"def test_list_roles(self):\n pass",
"def _assert_fields(self, dictionary):\n pass",
"def test_all_roles(self):\n pass",
"def test_roles_widget(self, admin_dashboard):\n admin_roles_tab = admin_dashboard.select_roles()\n expected_dict = self._role_el.ROLE_SCOPES_DICT\n actual_dic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert correctness of SQL generated in role playing Hub class. | def test_role_playing_hub_load_sql(
test_path: Path, h_customer_role_playing: RolePlayingHub
):
expected_result = (
test_path / "sql" / "expected_result_role_playing_hub.sql"
).read_text()
assert h_customer_role_playing.sql_load_statement == expected_result | [
"def test_raw_sql(self):\n\n # GIVEN raw SQL command\n sql = 'SELECT id, date_joined from auth_user WHERE id > %s;'\n params = ['0']\n\n # WHEN executing the SQL\n cursor = TestModel.execute_sql(sql, params)\n\n # THEN it should succeed\n results = cursor.fetchall()\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
decode the tupple (terme, masque) to make a string readable by 0,1, for example (9, 4) gives 101& | def decode_bin(tup_terme, nbr):
terme, msq = tup_terme
return "".join(['-' if msq & (1 << k) else '1' if terme & (1 << k )
else '0' for k in range(nbr-1, -1, -1)]) | [
"def decodebinaire(a):\n n = 0\n p = 1\n for i in range(len(a)-1,-1,-1):\n # p est 2^i et n est a[7]*2^0 + a[6]*2^1 + ... + a[i+1]*2^{i+1}\n n += a[i] * p\n p *= 2\n return(chr(n))",
"def decode(bits, code):\r\n result = \"\"\r\n running_bits = \"\"\r\n\r\n for bit in bit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Discovery of essential terms. From the lists of binary terms table_1 and table_0, returns the essential terms and the list of terms 1 not covered remaining | def __terme_essentiel(table_1, table_0, nbr):
table_essentiel = []
flag = 1 << nbr
msq1 = (1 << nbr)- 1
for tb1 in table_1:
if (tb1 & flag) == 0:
pt_unique = __pt_facteur_unique(tb1, table_0, nbr)
fl = 0
... | [
"def vocabularyIntrodctions(pseudosentences, width = 20):\n from sets import Set\n # First get for each pseudosentence the set of new terms they introduce\n seenWords = Set()\n pseudosentence_new_terms = []\n for sentence in pseudosentences:\n newWords = Set()\n for word in sentence:\n if not (word ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
생방송 채널 정보를 가져온다. channelid = 생방송 채널 번호(K01, K02 등등) quality = 화질(pypooq.Highquality, pypooq.Mobilequality 등등) credential = 인증 정보, 없을 시 미리보기 주소가 반환될 수 있다 | def getchannelinfo(self, channelid):
requestquery = {}
requestquery.update(Commonquery)
requestquery['credential'] = self.credential or "None"
request = self.session.get(self.apiaddress+'/live/channels/'+channelid, params=requestquery)
return request.json() | [
"def getchannelinfo(self, channelid, quality, credential=None):\n credential = credential or self.credential\n requestquary = {\n 'deviceTypeId': 'pc',\n 'marketTypeId': 'generic',\n 'deviceModelId': 'none',\n 'credential': credential,\n 'quality'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
프로그램 VOD 목록을 가져온다. programid = 프로그램 번호 limit = 최대 결과 수 | def getvodlist(self, programid, limit=1000, offset=0, orderby="new"): #new or old
requestquery = {"offset":offset, "limit":limit, "orderby":orderby}
requestquery.update(Commonquery)
requestquery['credential'] = self.credential or "None"
vodlist = self.session.get(self.apiaddress + '/vod... | [
"def getvodlist(self, programid, limit=1000, credential=None):\n credential = credential or self.credential\n\n requestquary = {\n 'deviceTypeId': 'pc',\n 'marketTypeId': 'generic',\n 'apiAccessCredential': 'EEBE901F80B3A4C4E5322D58110BE95C',\n 'offset': '0'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
VOD 정보를 가져온다. programid = 프로그램 번호 | def getvodinfo(self, contentid):
requestquery = {}
requestquery.update(Commonquery)
requestquery['credential'] = self.credential or "None"
vodinfo = self.session.get(self.apiaddress + '/vod/contents/'+contentid, params=requestquery)
return vodinfo.json() | [
"async def vod_info(self, vod_id: str) -> dict:\n url = BRIME_API + f'channel/{vod_id}?client_id={self.client_auth}'\n return await self._post(url)",
"def show_vdcs_detail(self):\n for v in self.vdcs:\n print self.vdcs[v]",
"def getvodinfo(self, programid, episodeid, quality, cre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
스트림 주소를 가져온다. action = "hls", "download" 둘 중 하나 contentid = 컨텐츠 번호 quality = 화질(480p, 720p, 1080p 등등) contenttype = "vod", "live" 둘 중 하나 authtype = "cookie", "token" 둘 중 하나 authtype이 cookie이고 playurl 사용 시 awscookie를 같이 사용할것 | def getstream(self, action, contentid, quality, contenttype, authtype, isabr=False, ishevc=False):
requestquery = {
"contentid":contentid,
"contenttype":contenttype,
"action":"hls",
"quality":quality,
"deviceModelId":"none",
"guid":self.gui... | [
"def download(self, account, code):\n\n url = Spider.BASE_URL + \"/p/%s/?taken-by=%s\" % (code, account)\n r = self.session.get(url)\n content_match = re.search(r\"<script.*?>\\s*?window._sharedData\\s*?=\\s*?({.*}).*?</script>\", r.text,\n re.MU... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a context with a sequence database | def fixture_sequence_ctx(sequence_db: Manager) -> Dict[str, Manager]:
return {"db": sequence_db} | [
"def get_translation_db(seqDB):\n try:\n return seqDB.translationDB\n except AttributeError: # create a new TranslationAnnot DB\n tdb = TranslationDB(seqDB)\n try:\n seqDB.translationDB = tdb\n except AttributeError:\n pass # won't let us cache? Just hand back... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a context with a database only initialized with snps | def fixture_snp_ctx(snp_db: Manager) -> Dict[str, Manager]:
return {"db": snp_db} | [
"def context():\n if _initial_pid != os.getpid():\n # Forked, clear the existing context to avoid issues.\n # TODO(ochang): Remove this hack once on Python 3, where we can set\n # multiprocessing.set_start_method to not fork.\n context_module._state.context = None # pylint: disable=protected-access\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Spawn the players Overrides one of the players in CoopScreen with an AI | def spawn_players(self) -> None:
#Create the player
self.player1 = Player(self.sensitivity, self.screen_width, self.screen_height, self.screen_width//(3/2), self.screen_height-50, self.player_lives, self.fps, self.player1_bullet, Direction.UP, self.debug)
#Create the AI
self.player2 = A... | [
"def make_npcs(self):\n for name in prepare.GFX:\n if name != self.player.name:\n pos = [random.randint(50,400), random.randint(50,400)]\n speed = random.randint(1,2)\n way = random.choice(prepare.DIRECTIONS)\n actors.AISprite(pos, speed,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the given clause to the CNF MazeKnowledgeBase | def tell (self, clause):
self.clauses.add(clause) | [
"def add_clause(self, clause):\n self.abstract_clauses.append(clause)",
"def add_clause(self, clause):\n return self._compile(clause)",
"def add_clause(self, clause):\n self.solver.add_clause(clause)\n if self.dump is not None:\n self.dump.write(\" \".join(map(str, clause)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a MazeClause query, returns True if the KB entails the query, False otherwise | def ask (self, query):
temp_kb = copy.deepcopy(self)
for prop in query.props:
# get the clauses
clause = [(prop, False if query.props.get(prop) else True)]
clause = MazeClause(clause)
temp_kb.tell(clause)
while True:
kb = list(temp_kb.c... | [
"def _is_query(act: Message):\n k = 'is_search_query'\n return k in act and act[k]",
"def check_query(self, querytext):\n try:\n self.parse_query(querytext)\n return True\n except ParseError:\n return False",
"def hasterm(self, query_term):\n\n if not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
we calculate the waiting time as the time it takes for the previous processes (the burst times), and for the first process we don't have to wait (the time starts at zero.) Note that we don't actually wait for these times (no use of time.sleep) we just calculate them. | def calculate_waiting_times(self):
# let's count time in general units
wait_times = []
current = wait_time = self.processes[0].arrival_time
for p in self.processes:
# We won't actually wait :)
# if the arrival
wait_time = wait_time - p.arrival_time
... | [
"def _calculate_periodic_loop_sleep_time(self, time_for_process):\n if time_for_process > self.min_time_per_process_loop:\n sleep_time = 0\n else:\n sleep_time = self.min_time_per_process_loop - time_for_process\n\n return sleep_time",
"def _calculate_wait_time(self) -> ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the turnaround time is how long it takes to wait, start, and finish so we care about the burst time of the process too! | def calculate_turnaround_times(self, wts=None):
trts = []
if wts == None:
wts = self.calculate_waiting_times()
for p in self.processes:
waiting_time = wts.pop(0)
trt = waiting_time + p.burst_time
trts.append(trt)
return trts | [
"def run_time(self, speed: int, time: int, then: Stop = Stop.HOLD, wait: bool = True):\n ...",
"def eval_turnaround_time(self, start_time):\n for event in self.clevents:\n event.wait()\n end_time = start_time\n for key in self.events['gpu'].keys():\n if self.event... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method returns a list of names that are results of searching phrase | def get_search_results(self):
return self.get_list_of_names(self.SEARCH_RESULTS) | [
"def search(words):\n newlist = [w for w in words if 'son' in w]\n return newlist",
"def find_names(text):\n\n names = []\n\n # spacy doc\n doc = nlp(text)\n\n # pattern\n pattern = [{'LOWER': 'prime'},\n {'LOWER': 'minister'},\n {'POS': 'ADP', 'OP': '?'},\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unfollow profile by mowing mouse to a button then click on it | def unfollow_profile(self):
self.find_clickable_element(self.ISFOLLOWED_BTN).click() | [
"def btn_unfollow_clicked(self, widget, data=None):\n print \"unfollow clicked\"",
"def clickViewProfile(self):\n self.waitForElement(locator=self._viewProfileBtn, locatorType=\"xpath\")\n element = self.getElementList(locator=self._viewProfileBtn, locatorType=\"xpath\")\n self.element... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method returns list of followed profiles names | def get_followed_profiles(self):
return self.get_list_of_names(self.FOLLOWED_PROFILES) | [
"def profiles_names(self):\n url = get_url('profiles')\n response = self._get(url)\n raise_on_error(response)\n return response.json()",
"def get_profile_names():\n import botocore.session\n return botocore.session.get_session().full_config.get('profiles', {}).keys()",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse name from transcript.py | def parse_name(self, transcript: str) -> None:
name_match = re.match(
r".*(?=Unofficial\ UNDERGRADUATE\ ACADEMIC\ RECORD)", transcript, RE_OPT
)
if not name_match:
raise ValueError("Name not found")
self.name = name_match.group(0).strip() | [
"def Extract_Names(transcript_name):\n # Split up title and capitalise words\n upper_names = []\n for i in transcript_name.split(\"_\"):\n upper_names.append(i.title())\n\n # Combine names\n first_name = \" \".join(upper_names[:2])\n second_name = \" \".join(upper_names[2:])\n\n return [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse your major from header text from transcript. We assume only 1 major.txt | def parse_major(self, header_text: str) -> None:
major_match = re.search(r"(?<=Major:)\s*?\K.*?(?=\n)", header_text, RE_OPT)
if not major_match:
raise ValueError("Major not found")
self.major = major_match.group(0).strip() | [
"def parseFile(inTxt,ext):\n print 'starting parse'\n # Check extension to determine splitter\n dlmtr = None\n if ext == '.csv': dlmtr = ','\n elif ext == '.txt': dlmtr = None\n else: \n print 'unrecognized extension' \n return (0,0)\n \n # Go through and parse the individu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the string containing the study plan for major, year.txt | def get_plan_str(self, transcript_text: str) -> str:
first_sem_match = re.search(r".*?---\K\d*\s\w*(?=---)", transcript_text)
if not first_sem_match:
raise ValueError("Could not identify any semesters on transcript")
first_sem = first_sem_match.group(0)
year = first_sem.split... | [
"def toStudentString(self):\r\n return \"{0}th year, section {1}, {2} {3}\".format(self.batch, self.batch_id, self.batch, self.batch_id)",
"def fetch_online_study_plan():\n page_source = urlopen(LINK_CS).read()\n soup = BeautifulSoup(page_source, 'html.parser')\n main_content = soup.find(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the plan from your study plan. | def initialize_plan(self, transcript_s: str) -> None:
plan_s = self.get_plan_str(transcript_s)
def get_term_match(transcript_partial: str) -> Match[str]:
match_obj: Match[str] = re.search(r".*?\KTERM\s\d+", transcript_partial)
return match_obj
def remove_semester(transc... | [
"def plan(self, plan):\n\n self._plan = plan",
"def initialize_survey(self, **kwargs):",
"def __init__(self, project=None):\n HyppopySolver.__init__(self, project)\n self._sampler = None",
"def from_composite_plan(cls, plan: CompositePlan, latest: bool = False):\n from renku.comman... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill plan from list of courses taken or to be taken from. | def fill_plan(self, course_list: List[Course]) -> None:
for transcript_course in course_list:
for semester in self.plan:
if not transcript_course.fulfilled:
for sem_course in semester.required_courses:
if not transcript_course.fulfilled and... | [
"def fillPlan(self):\n\n # for every time step up to the max step\n for t in range(1, self.planLength + 1):\n #check if entries for that step exist\n if t in self.plan:\n # if less entries than elevators\n if len(self.plan[t]) != self.elevatorCount:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill out course plan to `Output.txt`. | def output_schedule(self) -> None:
with open("Output.txt", "w") as out_file:
for sem in self.plan:
out_file.write(sem.title.center(15 + 20 + 50 + 5) + "\n\n")
for course in sem.required_courses:
if course.special:
out_file.w... | [
"def fill_plan(self, course_list: List[Course]) -> None:\n for transcript_course in course_list:\n for semester in self.plan:\n if not transcript_course.fulfilled:\n for sem_course in semester.required_courses:\n if not transcript_course.ful... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a boolean to indicate if we need to reschedule another iteration. | def should_reschedule(self, iteration):
if not self.max_iterations:
return True
return iteration < self.max_iterations | [
"def can_reschedule(self) -> bool:\n return pulumi.get(self, \"can_reschedule\")",
"def IsRerun(self):\n return self.prev_test_context is not None",
"def is_recurrent(self) -> bool:\n return True",
"def runnable(self):\n if \"calculations\" not in self.ctx:\n return True # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return False if word already in trie, otherwise return True and add | def check_present_and_add(self, word):
current_node = self.root_node
is_new_word = False
# iterate through trie adding missing notes
for char in word:
if char not in current_node:
is_new_word = True
current_node[char] = {}
current_node = current_node[char]
# mark e... | [
"def add_to_trie(root, word):\n cur = root\n i = 0\n n = len(word)\n while i < n:\n j = ord(word[i]) - 48\n if cur.children[j] is not None:\n cur = cur.children[j]\n # Check if we just shadowed a word\n if cur.is_num or i == n - 1:\n return F... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unittest skip test decorator. Allow to skip test by device properties depends of current device state (adb or fastboot). | def SkipByDefault(ifPlatform=None, ifDeviceName=None, ifProductName=None, ifAndroidVersion=None,
ifSystem=None, rule='=='):
def find_test_suite(test_hash, test_name):
"""
Find TestSuite by TestCase name and TestSuite name
Args:
test_hash (int): Hash of Test f... | [
"def test_should_skip(self):\n pass",
"def test_skips(self):\n log.info(\"executing ExampleTestCase.test_skips\")",
"def skipMobile():\n\n def decorator(test_method):\n @wraps(test_method)\n def wrapper(*args, **kwargs):\n test_case_obj = args[0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find TestSuite by TestCase name and TestSuite name | def find_test_suite(test_hash, test_name):
for case in CONFIG.UNITTEST.SELECTED_TEST_CASES:
for suite in case['suites']:
if id(getattr(suite['class'], test_name, False)) == test_hash:
return case, suite
return None, None | [
"def selectTestCaseByName(self, name):\r\n # define search string\r\n searchString = '//testcase[@name=\"%s\"]' % name\r\n testCase = self._testSetDocument.find(searchString)\r\n\r\n\r\n return testCase and TestCaseNode(testCase, self) or None",
"def get_suite(mname):\n cases = []\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return of times a number is followed by a greater number. | def find_greater_numbers(nums):
times = 0
for loop in range(len(nums) - 1):
for follow in range(loop + 1, len(nums)):
if (nums[loop] < nums[follow]):
times+= 1
return times | [
"def greater_number(number_1=0, number_2=0):\n bigger_number = 0\n\n if number_1 > number_2:\n bigger_number = number_1\n else:\n bigger_number = number_2\n\n return bigger_number",
"def find_greater_numbers(nums):\n\n\n higher_count = 0\n \n if len(nums) > 0:\n last_num = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes a new job from an AWS Sagemaker training job. | def from_training_job(cls, job: TrainingJob) -> Job:
return Job(
job.hyperparameters["model"],
job.hyperparameters["dataset"],
_extract_configuration(job),
_extract_performance(job),
source_job=job,
) | [
"def from_training_job_name(\n cls, training_job_name: str, sagemaker_session: Session = None, **kwargs\n ):\n\n def call_describe_training_job():\n \"\"\"Load existing training job.\"\"\"\n try:\n training_job_data = sagemaker_session.sagemaker_client.describe_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the job from the file system at the specified directory. This should only be called on a directory where a job has previously been saved. | def load(cls, directory: Path) -> Job:
model = directory.parts[-3]
dataset = directory.parts[-2]
with (directory / "config.json").open("r") as f:
config = json.load(f)
with (directory / "performance.json").open("r") as f:
performance = json.load(f)
retur... | [
"def load(self):\n filename = \"%s/%s\" % (JOB_DIR, self.name)\n self.data = joblib.load(filename)",
"def read_job(self, path):\n\n with open(path, 'r') as fopen:\n self.job = load(fopen)",
"def load(path):\n with open(join(path, 'job.pkl'), 'rb') as file:\n job... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the list of performances for all models associated with this job. The variances of all metrics will be set to 0. | def performances(self) -> list[Performance]:
return [
Performance(
training_time=Metric(p["training"]["duration"], 0),
latency=Metric(self.static_metrics["latency"], 0),
num_model_parameters=Metric(
self.static_metrics["num_model_pa... | [
"def getAllMetrics(self):\n result = self.getReportMetrics()\n result.update(self.getOptimizationMetrics())\n return result",
"def get_metrics(\n self,\n models: Optional[List[Model]] = None,\n metric_selection: Optional[List[str]] = None,\n ) -> DataFrame:\n if models is N... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the forecasts on the test set for the model with the specified index. | def get_forecast(self, index: int) -> QuantileForecasts:
# If this job was initialized from Sagemaker, load it from the Sagemaker job
if self.source_job is not None:
with self.source_job.artifact(cache=False) as artifact:
return QuantileForecasts.load(
art... | [
"def forecast_ds(self, test_ds, forecasts):\n \n plen = len(test_ds)\n sample_cnt = forecasts[0].samples.shape[0]\n assert(plen == len(forecasts))\n \n\n #build a new forecasts object\n nf = []\n for fc in forecasts:\n nfc = SampleForecast(samples =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stores all data associated with the training job in an autogenerated, unique folder within the provided directory. The job is stored under `//`. Storing jobs via this function allows to decouple experimental results completely from AWS Sagemaker. | def save(self, path: Path, include_forecasts: bool = True) -> None:
assert self.source_job is not None, (
"Job cannot be saved if it was not initialized from an AWS"
" Sagemaker job."
)
# First, we generate the folder name
components = [f"seed-{self.config['seed'... | [
"def createJobFolders(self):\n os.makedirs(os.path.join(self.data_folder, \"1_original_data\"))\n os.mkdir(os.path.join(self.data_folder, \"2_combined\"))\n os.mkdir(os.path.join(self.data_folder, \"3_misc\"))\n os.mkdir(os.path.join(self.data_folder, \"4_client_excel\"))\n os.mkd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all jobs loaded from the provided analysis object. | def load_jobs_from_analysis(analysis: Analysis) -> list[Job]:
return [Job.from_training_job(job) for job in analysis] | [
"def get_all_jobs():\n return base_jobs.JobMetaclass.get_all_jobs()",
"def get_all(cls, shark):\n jobs = []\n for j in shark.api.jobs.get_all():\n jobs.append(cls(shark, j))\n return jobs",
"def get_all_jobs():\n jobs = []\n\n for app in get_apps():\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all jobs stored in the provided directory, assuming that the directory is structured as `//`. | def load_jobs_from_directory(directory: Path) -> list[Job]:
return [
Job.load(directory / model / dataset / job)
for model in os.listdir(directory)
if (directory / model).is_dir() and model in MODEL_REGISTRY
for dataset in os.listdir(directory / model)
if (directory / model /... | [
"def get_jobs():\n jobs = [os.path.join(JOBS_DIR, job)\n for job in os.listdir(JOBS_DIR)\n if job != '.gitignore']\n return jobs",
"def scan(directory, cnx):\n print(\"Scanning {}\".format(directory))\n dirs = filter(\n os.path.isdir, map(lambda x: os.path.join(directory, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visualize dispatch algorithm for a specific week for a single household | def plot_dispatch(pv, demand, E, week=30):
sliced_index = (pv.index.week==week)
pv_sliced = pv[sliced_index]
demand_sliced = demand[sliced_index]
self_consumption = E['inv2load'][sliced_index]
direct_self_consumption = np.minimum(pv_sliced,demand_sliced)# E['inv2load'][sliced_index]
indire... | [
"def plot_dispatch(pv, demand, E, week=30):\n\n sliced_index = (pv.index.week==week)\n pv_sliced = pv[sliced_index]\n demand_sliced = demand[sliced_index]\n self_consumption = E['inv2load'][sliced_index]\n \n direct_self_consumption = np.minimum(pv_sliced,demand_sliced)# E['inv2load'][sliced_index... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Self consumption maximization pv + battery dispatch algorithm. | def dispatch_max_sc(pv, demand, inv_size,param, return_series=False):
bat_size_e_adj = param['BatteryCapacity']
bat_size_p_adj = param['MaxPower']
n_bat = param['BatteryEfficiency']
n_inv = param['InverterEfficiency']
timestep = param['timestep']
# We work with np.ndarrays as they are much faste... | [
"def dispatch_max_sc(pv, demand, inv_size,param, return_series=False):\n bat_size_e_adj = param['BatteryCapacity']\n bat_size_p_adj = param['MaxPower']\n n_bat = param['BatteryEfficiency']\n n_inv = param['InverterEfficiency']\n timestep = param['timestep']\n # We work with np.ndarrays as they are... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a dictionary mapping socket module constants to their names. | def get_constants(prefix):
return dict( (getattr(socket, n), n)
for n in dir(socket)
if n.startswith(prefix)
) | [
"def get_constants(prefix):\n return {getattr(socket, name): name \n for name in dir(socket) if name.startswith(prefix)}",
"def __get_ip_protocols(self):\n ip_proto_prefix = 'IPPROTO_'\n return dict((getattr(socket, n), n[len(ip_proto_prefix):]) \\\n for n in dir(socket) if n.st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setter of objects directory | def setObjectsDir(self,objects_dir):
self.objects_dir=objects_dir | [
"def objects_directory_path_name():\n return environment_variable_as_path_name(\"OBJECTS\")",
"def set_dir(self, dir):\n self.dir = dir",
"def __set__(self, obj, val):\n try:\n self._resolve(val)\n except IOError, e:\n Parameterized(name=\"%s.%s\"%(obj.name,self._at... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This functions gets the coordinates of the centroids of each object detected inside an image. All the objects must be inside a folder, and there must be an image per each detected object. This functions is a complement of shrimps_cropper | def getCentroids(self):
images=[]
centroids_dict={}
#Find all images of the objects
for file in os.listdir(objects_dir):
if file.endswith(self.extension):
images.append(os.path.join(self.objects_dir, file)) | [
"def centroids(img):\n _, _, _, centr = cv2.connectedComponentsWithStats(img)\n return centr[1:]",
"def get_coord(folder_to_images):\n paths_to_images_list = CloudTools.load_images_paths(folder_to_images)\n\n # Process the images, convert to low resolution\n image_objs = CloudTools.prep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This functions parses a dict with the centroid of objects to a csv) | def centroidsToCsv(centroids_dict):
file=open("centroids.csv","w")
file.write("image,cx,cy"+"\n")
for k,v in centroids_dict:
cx,cy=v
cx,cy=int(cx),int(cy)
line=k+","+str(cx)+","+str(cy)+"\n"
file.write(line)
file.close() | [
"def print_centroids(centroids):\n print('\\n')\n for i, centroid in enumerate(centroids):\n print('centroid {}:'.format(i), centroid['members'])",
"def save_closest_words_to_centroids():\n with open('cluster_files.json', 'r') as f:\n cf = json.load(f)\n cwords = []\n for clfile in cf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serializes metric function or `Metric` instance. | def serialize(metric, use_legacy_format=False):
if use_legacy_format:
return legacy_serialization.serialize_keras_object(metric)
return serialize_keras_object(metric) | [
"def write_metric(self, metric_name: str, metric_value: Union[float, int]):\n self._metrics.append(Metric(metric_name, metric_value))",
"def tostring(self, **kwargs):\n # pylint: disable=unused-argument\n import pprint\n return pprint.pformat(dict(self.metrics), indent=4)",
"def to_m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deserializes a serialized metric class/function instance. | def deserialize(config, custom_objects=None, use_legacy_format=False):
if use_legacy_format:
return legacy_serialization.deserialize_keras_object(
config,
module_objects=globals(),
custom_objects=custom_objects,
printable_module_name="metric function",
... | [
"def deserialize_metric(config: Dict[str, Any], helper: PredictHelper) -> Metric:\n if config['name'] == 'MinADEK':\n return MinADEK(config['k_to_report'], [deserialize_aggregator(agg) for agg in config['aggregators']])\n elif config['name'] == 'MinFDEK':\n return MinFDEK(config['k_to_report'], ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves a Keras metric as a `function`/`Metric` class instance. The `identifier` may be the string name of a metric function or class. >>> metric = tf.keras.metrics.get("categorical_crossentropy") >>> type(metric) >>> metric = tf.keras.metrics.get("CategoricalCrossentropy") >>> type(metric) You can also specify `conf... | def get(identifier):
if isinstance(identifier, dict):
use_legacy_format = "module" not in identifier
return deserialize(identifier, use_legacy_format=use_legacy_format)
elif isinstance(identifier, str):
return deserialize(str(identifier))
elif callable(identifier):
return ide... | [
"def get_metric_func(metric_name):\n return load_class(METRIC_MAPPINGS[metric_name])",
"def get_metric(name: str, *args, **kwargs) -> Metric:\n return METRIC_DICT.get(name, None)(*args, **kwargs)",
"def get_evaluation_metric(config):\n\n def _metric_class(class_name):\n m = importlib.import_modu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Import predicted chemical shifts from a ShiftX2 results file. | def import_pred_shifts(self, input_file, filetype, offset=None):
# If no offset value is defined, use the default one
if offset==None:
offset = self.pars["pred_offset"]
if filetype == "shiftx2":
preds_long = pd.read_csv(input_file)
if any(pre... | [
"def read_shiftx2(input_file, offset=0):\n preds_long = pd.read_csv(input_file)\n preds_long[\"NUM\"] = preds_long[\"NUM\"] + offset # Apply any offset to residue numbering\n preds_long[\"Res_name\"] = preds_long[\"NUM\"].astype(str)+preds_long[\"RES\"]\n if any(preds_long.columns == \"CHAIN\"): pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add dummy rows to obs and preds to bring them to the same length. Also discard any atom types that aren't present in both obs and preds. | def add_dummy_rows(self):
obs = self.obs.copy()
preds = self.preds.copy()
# Delete any prolines in preds
preds = preds.drop(preds.index[preds["Res_type"]=="P"])
# Restrict atom types
# self.pars["atom_set"] is the set of atoms to be used in the ... | [
"def _obs_with_one_hot(self, obs):\n oh_obs = np.concatenate([self.one_hot, obs])\n return oh_obs",
"def test_get_dummies_good():\n\tdf_true = pd.read_csv(\"test/sample_data.csv\")\n\tdf_test = df_true.copy()\n\ttype_dummy = pd.get_dummies(df_true['type']).rename(columns=lambda x: 'type_' + str(x))\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use the Hungarian algorithm to find the highest probability matching (ie. the one with the lowest log probability sum), with constraints. Returns a data frame with the SS_names and Res_names of the matching. (Doesn't change the internal state of the NAPS_assigner instance.) | def find_best_assignments(self, inc=None, exc=None):
obs = self.obs
preds = self.preds
log_prob_matrix = deepcopy(self.log_prob_matrix)
if inc is not None:
# Check for conflicting entries in inc
conflicts = inc["SS_name"].duplicated(keep=False) | inc["Res... | [
"def find_alt_assignments(log_prob_matrix, best_match_indexes, N=1, by_res=True, verbose=False, return_full_assignments=False):\n # Calculate sum probability for the best matching\n best_sum_prob = sum(log_prob_matrix.lookup(log_prob_matrix.index[best_match_indexes[0]], \n log_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a dataframe with full assignment information, given a dataframe of SS_name and Res_name. Matching may have additional columns, which will also be kept. | def make_assign_df(self, matching, set_assign_df=False):
obs = self.obs
preds = self.preds
log_prob_matrix = self.log_prob_matrix
valid_atoms = list(self.pars["atom_set"])
extra_cols = set(matching.columns).difference({"SS_name","Res_name"})
assign_df = pd.merge(... | [
"def get_matching_names(understat_names, fpl_names): \n understat_names, fpl_names = understat_names['player_name'].unique(), fpl_names['player_name'].unique()\n seq = difflib.SequenceMatcher()\n understat_similar = []\n fpl_similar = []\n ratio = []\n for i in range(len(understat_names)):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a plot of the maximum sequential mismatch between i1, i and i+1 residues | def plot_seq_mismatch(self):
assign_df = self.assign_df
# Check that the assignment data frame has the right columns
if not all(pd.Series(['Max_mismatch_prev', 'Max_mismatch_next']).
isin(assign_df.columns)):
return(None)
else:
# Pad Re... | [
"def max_value(self, plot = False, ylim = False):\n i = []\n candidates = []\n max_number = []\n \n # Initialize sequence - try to pass to list with length > 1, otherwise just 0 \n try: # Case when we have a list of numbers passed as argument\n last_iteration = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the weighted sum for a neuron, given its input and weight vectors. | def weighted_sum(W, X):
if len(W) != len(X):
print("Dimension of weight vector should be same as input vector.")
return
else:
H = 0
for i in range(len(W)):
H += (W[i] * X[i])
return H | [
"def calculate_weighted_sum(\n inputs: np.ndarray, weights: np.ndarray, bias: np.ndarray\n) -> np.ndarray:\n return np.sum(inputs * weights) + bias",
"def weighted_sum(self, inputs):\r\n weighted_sum = 0\r\n for i in range(self.num_inputs):\r\n weighted_sum += self.weights[i]*inputs[i]\r\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Driver function to run the learning mechanism for the perceptron. | def perceptron_learning(train_data, W, epoch = 3):
for T in range(epoch):
print("\nEpoch:", T + 1)
for i in range(len(train_data)):
X = train_data[i][0]
target_Y = train_data[i][1]
W = forward_pass(X, target_Y, W)
print("\tUpdated Weights: {0}\n"... | [
"def runPerceptron(numTrainValues, numTestValues, pixels, tune, useTrainedWeights, info):\n t = time.clock()\n perceptronClassifier = perceptron.Perceptron(range(10), 3)\n\n if useTrainedWeights:\n perceptronClassifier.useTrainedWeights()\n else:\n print \"Loading Testing Data....\\n\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate run level workflow for a given model. | def fsl_run_level_wf(
model,
step,
bids_dir,
output_dir,
work_dir,
subject_id,
database_path,
smoothing_fwhm=None,
smoothing_level=None,
smoothing_type=None,
use_rapidart=False,
detrend_poly=None,
align_volumes=None,
smooth_autocorrelations=False,
despike=Fals... | [
"def run_model(model):\n\n model.create_initialised_input()\n\n model.run_from_buffer()\n\n output = model.output_parse()\n return output",
"def main():\n # fix date/time\n _ = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n workflow = Workflow(constants=constants)\n\n job_type... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The typeconstraint decorator allows a function or method to be augmented with strict (runtime) type asserts for all passed function arguments and returned return values. | def typeconstraints(typelist, rvtype=None):
if __debug__:
#typelist should be a valid list of types and/or callables
_check_typelist(typelist)
if rvtype != None:
_check_typelist(rvtype)
def _type_constraint_assert(typelist, kwtypelist, args, kwargs, name):
#Ma... | [
"def method(rtype):\n\n def decorator(func):\n argcount = func.__code__.co_argcount\n argnames = func.__code__.co_varnames[:argcount]\n ndefaults = 0\n if func.__defaults__:\n ndefaults = len(func.__defaults__)\n\n argNames = func.__code__.co_varnames[(argcount - nde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is the public view that displays only published posts. The view also returns a UNIX timestamp of the most recently updated post. This timestamp is compared with the `LastUpdate` value to determine when the page should be refreshed. Every 5 seconds, the `latest` timestamp is compared with the `LastUpdate` timestamp... | def home(request):
posts = Post.objects.filter(published=True)
latest = 0
if posts:
latest = Post.objects.latest('updated').unix_time()
return render(request, 'posts/home.html', {'posts':posts, 'latest':latest}) | [
"def published_after(self) -> Type[QuerySet]:\n return Post.objects.filter(published__gt=self.published, published__lt=timezone.now()) if self.is_published() else Post.objects.none()",
"def latest(request):\n post_list = Post.objects.exclude(hidden = True).order_by('-created')\n paginator = Paginator... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view allows an authenticated staff user to publish or unpublish an article by clicking a button. Clicking the button toggles the current state of the selected Post's `published` field. It also updates the `LastUpdated` time to be the time when the Post was updated (saved), tracked by its `updated` field This field... | def toggle_publish(request,id):
instance = get_object_or_404(Post, id=id)
if request.method=="POST":
instance.published = not instance.published
instance.save()
t, created = LastUpdate.objects.get_or_create(id=1)
t.updated = instance.updated
t.save()
cach... | [
"def publish(self):\n\t\tif self.published == True:\n\t\t\tself.published = False\n\t\t\tself.published_date = None\n\t\t\tself.save()\n\t\telse:\n\t\t\tself.published = True\n\t\t\tself.published_date = timezone.now()\n\t\t\tself.save()",
"def publish(self):\n self.published_date = timezone.now()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is the URL that is polled by the publicfacing page. It returns a UNIX timestamp of the last time an article was published or unpublished. This timestamp comes from the `LastUpdated`, a table that stores and updates only one row with one datetime column. Publishing and unpublishing are the only two actions that cle... | def refresh(request):
t, created = LastUpdate.objects.get_or_create(id=1)
if created:
t.save()
t = t.unix_time()
else:
t = t.unix_time()
latest = int(t) - 2
return JsonResponse({'latest':int(latest)}) | [
"def home(request):\n\n posts = Post.objects.filter(published=True)\n latest = 0\n if posts:\n latest = Post.objects.latest('updated').unix_time()\n\n return render(request, 'posts/home.html', {'posts':posts, 'latest':latest})",
"def time_published(self):\n return self._time_published",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints the relative amount of geotted photos for different tags. | def compute_geotag_usage():
year = 2014
for tag in TEST_TAGS:
tags = [tag]
query = FlickrQuery(tags=tags, year=year)
geotagged_query = FlickrQuery(tags=tags, year=year, only_geotagged=True)
total = flickr_api.count_photos(query)
geotagged = flickr_api.count_photos(geot... | [
"def check_all_tag_photo_counts(self):\n data = self.db.get_query_as_list(\n '''\n select * from tag\n '''\n )\n\n for tag in data:\n print()\n print(tag)\n # query for the number of photos using the tag\n # compare it... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check cash report validation. | def test_cash_report_validation(self):
self.assertEqual(self.cash_report.caffe, self.caffe)
with self.assertRaises(Exception):
CashReport.objects.create(
creator=self.kate,
caffe=self.filtry,
cash_before_shift=2000,
cash_after... | [
"def test_read_cash(self):\n filename = get_current_path() + '\\\\samples\\\\statement.xls'\n wb = open_workbook(filename=filename)\n ws = wb.sheet_by_name('Sheet1')\n \n row = 194 # the cash fields starts at A195\n cash = []\n n = read_cash(ws, row, cash)\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is where we execute the weak classifier (could be changed depends on how we use scikitlearn) | def run_weak_classifier(x: np.ndarray, c: svm.SVC) -> int:
x = x.reshape((1, 36))
return 1 if c.predict(x)[0] == 1 else 0 | [
"def run_all_classifiers(self):\n\t\tself.classifier_processes.run_all_worker_processes(self.queue)",
"def apply_classifier(self):\n for detected_object in self.detected_objects:\n detected_object.predict_class(self.original_image)",
"def __init__(self, classes, featureStrategy, clf = None, ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to get the points density some kilometers around. | def get_points_density(df, around=5):
grad_to_lat = 1 / 111
grad_to_lon = 1 / 85
densities = np.empty((df.shape[0],), dtype="float64")
for i in tqdm(range(df.shape[0]), desc="GETTING POINTS DENSITY"):
lon, lat = df["lon"].iloc[i], df["lat"].iloc[i]
min_lon = lon - around * grad_to_lon
... | [
"def density(self, x):",
"def distances(self, points=None):\n return self.radius * self.inner_angles(points=points).value",
"def density(self):\n return self.get_density()",
"def density():\n\tpass",
"def diameter(points):\n if len(points[0]) == 2:\n return bounds2D(points)[0]\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets altitudes for each point in the dataset. | def get_altitude(points):
altitudes = np.zeros((len(points),), dtype="float64")
for i, point in tqdm(enumerate(points), desc="GETTING ALTITUDE"):
p = Point(point[0], point[1])
altitudes[i] = alt.NM_COTA.iloc[
np.argmin([p.distance(alt.geometry.iloc[j]) for j in range(alt.shape[0])])
... | [
"def altitudes(self):\n s = self.sides\n v = self.vertices\n return {v[0]: s[1].perpendicular_segment(v[0]),\n v[1]: s[2].perpendicular_segment(v[1]),\n v[2]: s[0].perpendicular_segment(v[2])}",
"def altitude(self) -> int:\n return self._point.altitude",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function takes an iterable of points (lon, lat), and for each of those points, it checks how many "var" are in 2 km around (squareform). "var" here refers to the name of the "interesting point" from Nomecalles, therefore this function will return how many churches are 2km around of each of the points, how many hos... | def get_close_interest_points(
points, dicvar=None, var=None, around=2, points_compare=None
):
grad_to_lat = 1 / 111
grad_to_lon = 1 / 85
lons = [p[0] for p in points]
lats = [p[1] for p in points]
min_lons = [lon - around * grad_to_lon for lon in lons]
max_lons = [lon + around * grad_to_lon... | [
"def count_constellations(points, dist):\n return len(set(find_constellations(points, dist)))",
"def find_crime_areas(segmented_points):\n\n # once all of the interpolated points are loaded into segmented_points\n # loop through them again to find out which places are high crime.\n bad_neighborhood_cr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to retrieve the postal code for points, where points are in the form (lon, lat). Using the cod_postales df, which has the polygons for each postal code, it checks which of those polygons each point falls into. | def get_postal_codes(pts):
codigos = np.zeros((len(pts),))
for i, p in tqdm(enumerate(pts), desc="GETTING POSTAL CODES"):
p = Point(p[0], p[1])
for j in range(cod_postales.shape[0]):
if cod_postales.geometry.iloc[j].contains(p):
codigos[i] = cod_postales.geocodigo.ilo... | [
"def get_coordinates(postal_code):\n # TODO IMPROVE: ideally we want the exact coordinates of postal_code not the ones of the closest...\n # TODO IMPROVE: ...postal code !!\n # we pre loaded PC_COORD to speed up computations\n name = PC_COORD.ix[(PC_COORD['Postal Code']-postal_code).abs().argsort()[0]]\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |