query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Add symtab dynamic structure. | def add_dt_symtab(self, op):
d_tag = AssemblerVariable(("d_tag, DT_SYMTAB = 6", PlatformVar("addr"), 6))
d_un = AssemblerVariable(("d_un", PlatformVar("addr"), op))
self.__data[0:0] = [d_tag, d_un]
self.refresh_name_label() | [
"def parseSymbols(self):\n for sec in self.sections:\n if sec.sh_type == SHT_SYMTAB:\n symtab = sec.getBytes()\n while symtab:\n if self.bits == 32:\n newsym = Elf32Symbol(symtab)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an empty symbol. | def add_symbol_empty(self):
if osarch_is_32_bit():
self.add_data(("empty symbol", 4, (0, 0, 0, 0)))
elif osarch_is_64_bit():
self.add_data(("empty symbol", 4, (0, 0)))
self.add_data(("empty symbol", PlatformVar("addr"), (0, 0)))
else:
raise_unknown_address_size() | [
"def setBlank(self, blankSymbol):\n self.blank = blankSymbol",
"def _set_symbol(self, symbol, blank=False):\n self._symbols.add(symbol)\n\n try:\n assert self._blank_symbol == None or not blank\n if blank:\n self._blank_symbol = symbol\n except:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reconstruct data from bytestream. | def reconstruct(self, bytestream):
self.__data = []
while 0 < len(bytestream):
front = bytestream[0]
bytestream = bytestream[1:]
constructed = front.reconstruct(bytestream)
if constructed:
bytestream[:constructed] = []
self.__data += [front] | [
"def unpack(self, data):\r\n data_size = len(data)\r\n msg_magic, msg_length, msg_type = self.unpack_header(data)\r\n msg_size = self.struct_header_size + msg_length\r\n # Message shouldn't be any longer than the data\r\n if data_size >= msg_size:\r\n payload = data[sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a name end label to last assembler variable. | def refresh_name_end_label(self):
end_label = "%s_end" % (self.__name)
for ii in self.__data:
ii.remove_label_post(end_label)
if 0 < len(self.__data):
self.__data[-1].add_label_post(end_label) | [
"def generate_end_label(scope):\n name=scope['loop']\n return [f'label {name.upper()}_END{scope[\"current_\"+name]}']",
"def make_end(name): \n return '</'+name+'>'",
"def add_suffix(self, suffix: str):\n self.target = tuple(var + suffix for var in self.target)\n\n self.scope = tuple(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get cumulative size of data. | def size(self):
ret = 0
for ii in self.__data:
ret += int(ii.get_size())
return ret | [
"def totalsize(self):\n return sum([sz for sz in self.iterate()])",
"def get_size(self):\n cum_size = 0\n for stream in self.__streams.values():\n cum_size += sys.getsizeof(stream)\n for trace in stream:\n cum_size += sys.getsizeof(trace)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if command basename starts with given string. | def command_basename_startswith(self, op):
return self.__command_basename.startswith(op) | [
"def startswith(string, prefix):\n return string.startswith(prefix) and safe_split_index(string, len(prefix)) == len(prefix)",
"def is_command(text):\n return text.startswith('/')",
"def startswith(self, x):\n return self.name.startswith(x)",
"def _check_output_prefix(arg: str) -> str:\n\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate linker command for given mode. | def generate_linker_flags(self):
self.__linker_flags = []
if self.__command_basename.startswith("g++") or self.__command_basename.startswith("gcc"):
self.__linker_flags += ["-nostartfiles", "-nostdlib", "-Xlinker", "--strip-all"]
elif self.__command_basename.startswith("clang"):
self.__linker_fl... | [
"def set_linker_script(self, op):\n self.__linker_script = [\"-T\", op]",
"def generate_loader(mode, symbols, definition, linker):\n if \"vanilla\" == mode:\n loader_content = generate_loader_vanilla()\n elif \"dlfcn\" == mode:\n loader_content = generate_loader_dlfcn(symbols, linker)\n else:\n loa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate link library list libraries. | def get_library_list(self):
ret = []
prefix = "-l"
if self.__command_basename.startswith("cl."):
prefix = "/l"
for ii in self.__libraries:
ret += [prefix + ii]
return ret | [
"def linking_library_dirs(self):",
"def to_links(libs):\n #return [filter_link(a) for a in ['-l'+s for s in libs]]\n return [a for a in ['-l'+s for s in libs]]",
"def add_linking_library(self, library):",
"def library_dirs(self):",
"def _get_links(self, library):\n links = []\n for link_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get linker script from linker, improve it, write improved linker script to given file. | def generate_linker_script(self, dst, modify_start = False):
(so, se) = run_command([self.__command, "--verbose"])
if 0 < len(se) and is_verbose():
print(se)
match = re.match(r'.*linker script\S+\s*\n=+\s+(.*)\s+=+\s*\n.*', so, re.DOTALL)
if not match:
raise RuntimeError("could not extract s... | [
"def change_ld(binary, ld):\n if not os.access(ld, os.R_OK): \n log.failure(\"Invalid path {} to ld\".format(ld))\n return None\n \n \n if not isinstance(binary, ELF):\n if not os.access(binary, os.R_OK): \n log.failure(\"Invalid path {} to binary\".format(binary))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Link a binary file with no bells and whistles. | def link_binary(self, src, dst):
cmd = [self.__command, "--entry=" + str(PlatformVar("entry")), src, "-o", dst] + self.__linker_script
(so, se) = run_command(cmd)
if 0 < len(se) and is_verbose():
print(se)
return so | [
"def link_file(source, target):\n try:\n os.symlink(source, target)\n except AttributeError:\n try:\n os.link(source, target)\n except AttributeError:\n copy_file(source, target)",
"def link_to_blob(self, path, csum):\n new_link = self.csum_to_path(csum)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set libraries to link. | def set_libraries(self, lst):
self.__libraries = lst | [
"def _set_libraries(self, libraries):\n\tself.addLibraries(libraries)",
"def add_linking_library(self, library):",
"def linking_library_dirs(self):",
"def _add_linking_libs(context, call):\n libs = getattr(call, \"libs\", ())\n if libs:\n context.add_linking_libs(libs)",
"def addLibraries(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use given linker script. | def set_linker_script(self, op):
self.__linker_script = ["-T", op] | [
"def generate_linker_script(self, dst, modify_start = False):\n (so, se) = run_command([self.__command, \"--verbose\"])\n if 0 < len(se) and is_verbose():\n print(se)\n match = re.match(r'.*linker script\\S+\\s*\\n=+\\s+(.*)\\s+=+\\s*\\n.*', so, re.DOTALL)\n if not match:\n raise RuntimeError(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add extra compiler flags. | def add_extra_compiler_flags(self, op):
if is_listing(op):
for ii in op:
self.add_extra_compiler_flags(ii)
elif not op in self.__include_directories and not op in self.__definitions:
self.__compiler_flags_extra += [op] | [
"def set_c_flags_hook(build_ext, ext):\n std_flag = get_c_std_flag(build_ext.compiler)\n if std_flag is not None:\n ext.extra_compile_args.append(std_flag)",
"def try_add_flag(args, compiler, flag, ext=None):\n if try_compile(compiler, flags=args+[flag], ext=ext):\n args.append(flag)",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compile and link a file directly. | def compile_and_link(self, src, dst):
cmd = [self.get_command(), src, "-o", dst] + self.__compiler_flags + self.__compiler_flags_extra + self.__definitions + self.__include_directories + self.get_linker_flags() + self.get_library_directory_list() + self.get_library_list()
(so, se) = run_command(cmd)
if 0 < ... | [
"def link(prog_path: str, o_files: List[File]) -> File:\n print(\"linking\")\n os.system(\"gcc -o {prog_path} {o_files}\".format(\n prog_path=prog_path,\n o_files=' '.join(o_file.path for o_file in o_files),\n ))\n return File(prog_path)",
"def __makeLinkable(self, inputFile, args):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set include directory listing. | def set_include_dirs(self, lst):
prefix = "-I"
if self.command_basename_startswith("cl."):
prefix = "/I"
self.__include_directories = []
for ii in lst:
if os.path.isdir(ii):
new_include_directory = prefix + ii
if new_include_directory in self.__compiler_flags_extra:
... | [
"def include_dirs(self):",
"def write_include_dir(self):\n\n incl_dir = self.tree.find(\n '//ns:ItemGroup/ns:ClCompile/ns:AdditionalIncludeDirectories',\n namespaces=self.ns\n )\n if incl_dir is None:\n incl_dir = self.tree.find(\n '//ns:ItemDef... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate direct C code for data block. | def generate_c_data_block(self):
ret = "static const uint8_t elfling_weights[] =\n{\n "
for ii in range(len(self.__weights)):
if 0 < ii:
ret += ", "
ret += "%i" % (self.__weights[ii])
ret += "\n};\n\nstatic const uint8_t elfling_contexts[] =\n{\n "
for ii in range(len(self.__contex... | [
"def cdataBlock(self, data):\n pass",
"def code_gen(self):\r\n\r\n if getattr(self, 'struct_code', False):\r\n return self.struct_code\r\n\r\n no_recycling = self.no_recycling\r\n\r\n self.consts = []\r\n\r\n c_support_code_apply = []\r\n c_init_code_apply = []... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the C uncompressor source. | def generate_c_source(self):
return template_elfling_source % (self.generate_c_data_block(), ELFLING_WORK, ELFLING_OUTPUT, ELFLING_UNCOMPRESSED, len(self.__contexts), ELFLING_WORK, self.get_input_offset(), ELFLING_OUTPUT, self.get_uncompressed_size(), ELFLING_UNCOMPRESSED) | [
"def gen_csource(protocol):\n\tdef format_default(reg):\n\t\t\"\"\"Given a reg, return its default value formatted as a string for inclusion in\n\t\t a C source file.\"\"\"\n\t\tif reg.size == \"accum\":\n\t\t\treturn str(float(reg.default)) + \"k\"\n\t\telse:\n\t\t\treturn str(int(reg.default)) + \"L\"\n\n\ts = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get contexts. Contains dummy data until compression has been ran. | def get_contexts(self):
return self.__contexts | [
"def contexts(self):\n return self._contexts",
"def get_contexts(self):\n return self._contexts",
"def _context_list(self):\r\n url = \"{}/contexts/\".format(self._org_url)\r\n contexts = self._request(url)\r\n if not contexts:\r\n LOGGER.warning(\"No contexts available... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the input offset for compressed data. | def get_input_offset(self):
return ELFLING_PADDING + len(self.__data) - 4 | [
"def offset(self):\r\n return self.buf[0].unib[9:11]",
"def get_data_offset(bs):\n return bs[12] >> 4",
"def gguf_get_data_offset(ctx: ffi.CData) -> int:\n ...",
"def data_offset(self):\n if self.raw_data_length() < 5 or self.raw_data_length() >= 0x80000000:\n return self.absolu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get uncompressed size. Contains dummy value until compression has been ran. | def get_uncompressed_size(self):
return self.__uncompressed_size | [
"def get_uncompressed_size(self):\n if not self.is_compressed():\n return self.size\n elif self.data is None:\n raise ValueError('Data not read from record')\n else:\n return unpack('<L', self.data[:4])[0]",
"def layers_compressed_size(self):\n # don't ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the working area size required for decompression. | def get_work_size(self):
# TODO: Extract this value from the source.
return (4 << 20) * 16 | [
"def get_uncompressed_size(self):\n return self.__uncompressed_size",
"def get_size(self):\n return get_dir_size(self.run_dir)",
"def layers_compressed_size(self):\n # don't have this information at this point\n return None",
"def getWorkingPlayAreaSize(self):\r\n fn = self.func... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write elfling uncompressor source into given location. | def write_c_source(self, dst):
wfd = open(dst, "wt")
wfd.write(self.generate_c_source())
wfd.close() | [
"def main(sourcefile, output, compress, minify, minify_obfuscate,\n line_width, export_symbol):\n\n name = os.path.splitext(os.path.basename(sourcefile.name))[0]\n output.write(mkblob(name=name, code=sourcefile.read(), minify=minify,\n compress=compress, minify_obfuscate=minify_obfuscate,\n line_widt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get linkable library object name. | def get_library_name(self, linker):
return linker.get_library_name(self.__library.get_name()) | [
"def libraryName(self):\n return _osgAnimation.LinkVisitor_libraryName(self)",
"def _libname(self):\n return os.path.basename(self._libpath)",
"def _libname(self, libpath):\n # Cut off 'lib' at the beginning of filename, and '.a' at end.\n return os.path.basename(libpath)[3:-2]",
"def dll_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a symbol listing. | def add_symbols(self, lst):
for ii in lst:
self.__symbols += [Symbol(ii, self)] | [
"def AddSymbol(self,name,stype,body=None):\n if self.IsSymbol(name):\n raise Exception('Program Bug -- name \"%s\" already exists is symbols' % name);\n self.symbols['list'].append(name);\n self.symbols['type'].append(stype);\n self.symbols['body'].append(body);",
"def add_symbol(self, symbol):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Analyze given preprocessed C source for symbol names. | def analyze_source(source, prefix):
symbolre = re.compile(r"[\s:;&\|\<\>\=\^\+\-\*/\(\)\?]" + prefix + "([a-zA-Z0-9_]+)[\s\(]")
results = symbolre.findall(source, re.MULTILINE)
ret = set()
for ii in results:
symbolset = set()
symbolset.add(ii)
ret = ret.union(symbolset)
return ret | [
"def ParseVMSymbols(self, filename, start, end):\n pipe = os.popen('nm -n %s | c++filt' % filename, 'r')\n try:\n for line in pipe:\n row = re.match('^([0-9a-fA-F]{8}) . (.*)$', line)\n if row:\n addr = int(row.group(1), 16)\n if addr < start and addr < end - start:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the loader code. | def generate_loader(mode, symbols, definition, linker):
if "vanilla" == mode:
loader_content = generate_loader_vanilla()
elif "dlfcn" == mode:
loader_content = generate_loader_dlfcn(symbols, linker)
else:
loader_content = generate_loader_hash(symbols)
ret = template_loader % (definition, loader_cont... | [
"def generate_loader_vanilla():\n return template_loader_vanilla",
"def codegen():",
"def _load_source(self):\r\n pass",
"def setup_loader():\n # The type of loader to use, see simuran.loaders.loader_list.py for options\n # For now nc_loader is the most common option\n # loader = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate dlopen/dlsym loader code. | def generate_loader_dlfcn(symbols, linker):
dlfcn_string = ""
current_lib = None
for ii in symbols:
symbol_lib = ii.get_library().get_name()
if current_lib != symbol_lib:
if current_lib:
dlfcn_string += "\"\\0%s\\0\"\n" % (ii.get_library_name(linker))
else:
dlfcn_string += "\"%... | [
"def generate_loader(mode, symbols, definition, linker):\n if \"vanilla\" == mode:\n loader_content = generate_loader_vanilla()\n elif \"dlfcn\" == mode:\n loader_content = generate_loader_dlfcn(symbols, linker)\n else:\n loader_content = generate_loader_hash(symbols)\n ret = template_loader % (definit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate import by hash loader code. | def generate_loader_hash(symbols):
return template_loader_hash % (str(PlatformVar("entry")), len(symbols)) | [
"def gen_import(self) -> str:\n as_name = self.exported_parts[-1]\n if as_name == self.imported_name:\n import_line = 'from {} import {}'.format(self.imported_module,\n self.imported_name)\n else:\n import_line = 'from {} import {} as {}'.format(self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate loader that actually leaves the loading to the operating system. | def generate_loader_vanilla():
return template_loader_vanilla | [
"def generate_loader(mode, symbols, definition, linker):\n if \"vanilla\" == mode:\n loader_content = generate_loader_vanilla()\n elif \"dlfcn\" == mode:\n loader_content = generate_loader_dlfcn(symbols, linker)\n else:\n loader_content = generate_loader_hash(symbols)\n ret = template_loader % (definit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a listing of definitions from replacement symbols to real symbols. | def generate_symbol_definitions(mode, symbols, prefix, definition):
direct = []
tabled = []
for ii in symbols:
direct += [ii.generate_rename_direct(prefix)]
tabled += [ii.generate_rename_tabled(prefix)]
if "vanilla" == mode:
tabled = direct
return template_symbol_definitions % (definition, "\n".jo... | [
"def definitions(self, target_data):\n for definition in self.from_target_data(target_data).data.definitions:\n yield f\"-D {definition}\"",
"def glt_latex_definitions():\n # ...\n t = Symbol('t')\n m = Symbol('m')\n s = Symbol('s')\n a = Symbol('a')\n # ...\n\n # ...\n d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the symbol struct definition. | def generate_symbol_struct(mode, symbols, definition):
if "vanilla" == mode:
return ""
definitions = []
hashes = []
symbol_table_content = ""
for ii in symbols:
definitions += [" %s;" % (ii.generate_definition())]
hashes += [" %s%s," % (ii.generate_prototype(), ii.get_hash())]
if "dlfcn" != mo... | [
"def generate_symbol_definitions(mode, symbols, prefix, definition):\n direct = []\n tabled = []\n for ii in symbols:\n direct += [ii.generate_rename_direct(prefix)]\n tabled += [ii.generate_rename_tabled(prefix)]\n if \"vanilla\" == mode:\n tabled = direct\n return template_symbol_definitions % (defi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compress a file to be a selfextracting filedumping executable. | def compress_file(compression, pretty, src, dst):
str_tail = "sed 1d"
str_cleanup = ";exit"
if pretty:
str_tail = "tail -n+2"
str_cleanup = ";rm ~;exit"
if "lzma" == compression:
command = ["xz", "--format=lzma", "--lzma1=preset=9e,lc=1,lp=0,pb=0", "--stdout"]
header = "HOME=/tmp/i;%s $0|lzcat>~... | [
"def compress(infile):\r\n cmd = ' '.join([\"gzip\", \"-f\", infile])\r\n pipe = subprocess.run(cmd, shell=True,\r\n stdout=subprocess.PIPE,\r\n stderr=subprocess.PIPE)",
"def compress_file(self, filename):\n # pylint: disable=consider-using-with\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if given file contains nothing but ASCII7 text. | def file_is_ascii_text(op):
if not os.path.isfile(op):
return False
fd = open(op, "rb")
while True:
line = fd.readline()
if 0 >= len(line):
fd.close()
return True
try:
line.decode("ascii")
except UnicodeDecodeError:
fd.close()
return False | [
"def is_text(self, filename):\n payload = open(filename, 'rb').read(512)\n _null_trans = bytes.maketrans(b\"\", b\"\")\n if not payload:\n # Empty files are considered text\n return True\n if b\"\\0\" in payload:\n # Files with null bytes are likely binar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the UND symbols required for this platform. | def get_platform_und_symbols():
ret = None
if osname_is_freebsd():
ret = sorted(["environ", "__progname"])
if is_verbose():
print("Checking for required UND symbols... " + str(ret))
return ret | [
"def get_symbol(self):\n return []",
"async def _load_supported_symbols() -> List[Symbol]:\n return []",
"def symbols(self):\n path = \"/v1/symbols\"\n return self._get(path)",
"def ionic_symbols(self) -> list[str]:\n return self.to_list().symbols",
"def symbols(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell if given register is used for saving the stack. | def is_stack_save_register(op):
return op.lower() in ('rbp', 'ebp') | [
"def append_register(self, register):\n register_str, is_saved = register # pylint: disable=I0011,W0612\n\n if is_saved:\n self.__history.append(register)\n return True\n\n return False",
"def is_on_stack(self, address):\n return self.is_address_of_type(address, Memor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell if a variable can be deconstructed. | def is_deconstructable(op):
return isinstance(op, int) or (isinstance(op, PlatformVar) and op.deconstructable()) | [
"def deconstructable(self):\n return isinstance(self.get(), int)",
"def deconstructable(self):\n return isinstance(self.get(), int)",
"def _pfp__can_unpack(self):\n return self._pfp__pack_type is not None",
"def valid(v): # this is a var, return true if it's valid.\n\tif v.cat == \"Continuou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell if given parameter is a listing. | def is_listing(op):
return isinstance(op, (list, tuple)) | [
"def IsList(param):\n if type(param) is types.ListType:\n return True\n return False",
"def test_listing_available(self):\n portal_types = api.portal.get_tool(name='portal_types')\n self.assertTrue(LISTING_TYPE in portal_types)",
"def is_list(self):\n answer = self._call('is_list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to merge segments in a given list inplace. | def merge_segments(lst):
ii = 0
while True:
jj = ii + 1
if len(lst) <= jj:
return lst
seg1 = lst[ii]
seg2 = lst[jj]
if seg1.merge(seg2):
if seg2.empty():
del lst[jj]
else:
ii += 1
else:
ii += 1
return lst | [
"def merge_segdb(segdbs):\n segdb = segdbs[0]\n for r in segdbs[1:]:\n segdb.extend(r)\n return segdb",
"def submitlist(jb, ls):\n segstart, segend = calculatestartend(ls) # Get the segment id for the current segment\n seg = None\n opp = None\n with jb.lock: # Lock the segments dicti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the architecture is 32bit. | def osarch_is_32_bit():
return osarch_match("32-bit") | [
"def osarch_is_32_bit():\n return osarch_match(\"32-bit\")",
"def is_32bit(self):\n return self.machine in ['i386', 'i586', 'i686']",
"def isIntelX86_32bit():\n return String(System.getProperty(\"os.arch\", \"null\").strip()).toLowerCase(Locale.ROOT) == \"x86\"",
"def is_32bit(self) -> bool:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the architecture maps to amd64. | def osarch_is_amd64():
return osarch_match("amd64") | [
"def osarch_is_amd64():\n return osarch_match(\"amd64\")",
"def is_os_64bit():\n import platform\n return platform.machine().endswith('64')",
"def is64bit():\r\n return platform.machine().endswith('64')",
"def is_64bit(self):\n return self.machine == 'x86_64'",
"def is64bit(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the architecture maps to ia32. | def osarch_is_ia32():
return osarch_match("ia32") | [
"def osarch_is_ia32():\n return osarch_match(\"ia32\")",
"def osarch_is_32_bit():\n return osarch_match(\"32-bit\")",
"def osarch_is_32_bit():\n return osarch_match(\"32-bit\")",
"def isIntelX86_32bit():\n return String(System.getProperty(\"os.arch\", \"null\").strip()).toLowerCase(Locale.ROOT) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if osarch matches some chain resulting in given value. | def osarch_match(op):
arch = g_osarch
while True:
if op == arch:
return True
arch = platform_map_iterate(arch)
if not arch:
break
return False | [
"def osarch_match(op):\n arch = g_osarch\n while True:\n if op == arch:\n return True\n arch = platform_map_iterate(arch)\n if not arch:\n break\n return False",
"def test_usearch_supported_version(self):\r\n acceptable_version = [(5, 2, 236), (5, 2, 236)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the operating system name maps to FreeBSD. | def osname_is_freebsd():
return ("FreeBSD" == g_osname) | [
"def host_os_is(osname):\n if os.name == osname:\n return True\n return False",
"def determine_if_os_is_posix_compliant():\n return bool(os.name == \"posix\")",
"def osname_is_linux():\n return (\"Linux\" == g_osname)",
"def is_linux():\n return guess_os() == 'linux'",
"def is_linux():\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the operating system name maps to Linux. | def osname_is_linux():
return ("Linux" == g_osname) | [
"def is_linux():\n return guess_os() == 'linux'",
"def is_linux():\n if os.name == 'posix':\n return True\n return False",
"def os_is_linux():\n return platform.system() == \"Linux\" and \"raspberrypi\" not in platform.uname()",
"def is_linux():\n return sys.platform[:5] == \"linux\"",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Common function to raise an error if os architecture address size is unknown. | def raise_unknown_address_size():
raise RuntimeError("platform '%s' addressing size unknown" % (g_osarch)) | [
"def check_architecture(target_architecture):\n if target_architecture == ARCH_16_BIT:\n # should be fine, most computers are at least 32 bit these days\n pass\n elif target_architecture == ARCH_32_BIT:\n # should be fine, most computers are at least 32 bit these days\n pass\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read information from an ELF file using readelf. Return as dictionary. | def readelf_get_info(op):
ret = {}
(so, se) = run_command(["readelf", "--file-header", "--program-headers", op])
match = re.search(r'LOAD\s+\S+\s+(\S+)\s+\S+\s+(\S+)\s+\S+\s+RWE', so, re.MULTILINE)
if match:
ret["base"] = int(match.group(1), 16)
ret["size"] = int(match.group(2), 16)
else:
raise Ru... | [
"def get_elf_info(filepath):\n local_path = pwndbg.gdblib.file.get_file(filepath)\n with open(local_path, \"rb\") as f:\n elffile = ELFFile(f)\n header = dict(elffile.header)\n segments = []\n for seg in elffile.iter_segments():\n s = dict(seg.header)\n s[\"x_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Truncate file to size reported by readelf first PT_LOAD file size. | def readelf_truncate(src, dst):
info = readelf_get_info(src)
size = os.path.getsize(src)
truncate_size = info["size"]
if size == truncate_size:
if is_verbose():
print("Executable size equals PT_LOAD size (%u bytes), no truncation necessary." % (size))
shutil.copy(src, dst)
else:
if is_verbos... | [
"def testTruncate(self):\n # Check truncation at all possible boundaries (including start and end).\n for size in range(0, self.TEST_FILE_SIZE + self.TEST_FILE_BLOCK_SIZE,\n self.TEST_FILE_BLOCK_SIZE):\n sparse_file = self._clone_sparse_file()\n ih = bpttool.ImageHandler(sparse_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add the serialized data of the FIFO to the current FIFO. | def addFIFO(self, fifo):
if not isinstance(fifo, MessageFIFO):
raise SerializationError('fifo is not of type MessageFIFO.')
self._buf += fifo | [
"def push(self, data):\n self.data.append(data)",
"def add_last(self, data):\n self.deque.append(data)",
"def enque(self, data):\n\t\tself._queue.append(data)",
"def _AddSerializedEvent(self, event):\n identifier = identifiers.SerializedStreamIdentifier(\n self._last_stream_numbers['ev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the FIFO containing the remaining data. | def getFIFO(self):
return self._buf | [
"def fifo(self):\n return self.__fifo",
"def queue_fifo(self):\n return deque(list(self.queue()))",
"def pop_sm(self):\r\n while True:\r\n # wait to receive a read request\r\n req = yield self.r_in_pipe.get()\r\n # model read latency\r\n #for i in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run an Import volumes protocol. | def runImportVolumes(cls, pattern, samplingRate):
cls.protImport = cls.newProtocol(ProtImportVolumes,
filesPath=pattern,
samplingRate=samplingRate
)
cls.launchProtocol(cls.protImpor... | [
"def ImportVolume(self, **kwargs):\n logger.debug('ImportVolume called')\n self.ImportManifestUrl = kwargs['Image.ImportManifestUrl']\n self.ImportType = 'ImportVolume'\n\n # launch thread to go import volume\n worker = threading.Thread(target=self.handle_import,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searches and loads target files, and runs compile_target() on a multiprocessing pool with parallel number of processes. kwargs are passed to compile_target() | def compile_targets(
inventory_path, search_paths, output_path, parallel, targets, labels, ref_controller, **kwargs
):
# temp_path will hold compiled items
temp_path = tempfile.mkdtemp(suffix=".kapitan")
# enable previously compiled items to be reference in other compile inputs
search_paths.append(t... | [
"def compile_targets(target_path, search_path, output_path, parallel, **kwargs):\n # temp_path will hold compiled items\n temp_path = tempfile.mkdtemp(suffix='.kapitan')\n pool = multiprocessing.Pool(parallel)\n # append \"compiled\" to output_path so we can safely overwrite it\n compile_path = os.pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generates the hashes for the inventory per target and jsonnet/jinja2 folders for caching purposes | def generate_inv_cache_hashes(inventory_path, targets, cache_paths):
inv = inventory_reclass(inventory_path)
cached.inv_cache = {}
cached.inv_cache["inventory"] = {}
cached.inv_cache["folder"] = {}
if targets:
for target in targets:
try:
cached.inv_cache["invento... | [
"def create_build_hash(self):\n\n # The hash order is:\n # - The build script\n # - The build specificity\n # - The build group and umask\n # - The src archive.\n # - For directories, the mtime (updated to the time of the most\n # recently updated file) i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a list of targets that have changed since last compilation | def changed_targets(inventory_path, output_path):
targets = []
inv = inventory_reclass(inventory_path)
saved_inv_cache = None
saved_inv_cache_path = os.path.join(output_path, "compiled/.kapitan_cache")
if os.path.exists(saved_inv_cache_path):
with open(saved_inv_cache_path, "r") as f:
... | [
"def env_get_outdated_hook(app, env, added, changed, removed):\n import os\n\n reread = set()\n\n for target in app.env.domaindata[\"broxygen\"][\"targets\"].values():\n before_mtime = os.stat(target.generated_file)\n build_target(env, target)\n after_mtime = os.stat(target.generated_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save the cache to .kapitan_cache for inventories per target and folders | def save_inv_cache(compile_path, targets):
if cached.inv_cache:
inv_cache_path = os.path.join(compile_path, ".kapitan_cache")
# If only some targets were selected (-t), overwride only their inventory
if targets:
saved_inv_cache = None
try:
with open(in... | [
"def save_cache(self, cache_dir):\n if not self.is_numeric:\n raise ValueError(\"No need to save if not numeric\")\n if self.is_supervised:\n raise NotImplementedError(\"Caching not yet implemented for supervised views\")\n\n os.makedirs(cache_dir, exist_ok=True)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a list of target objects from the inventory | def load_target_inventory(inventory_path, targets, ignore_class_notfound=False):
target_objs = []
inv = inventory_reclass(inventory_path, ignore_class_notfound)
# if '-t' is set on compile, only loop through selected targets
if targets:
targets_list = targets
else:
targets_list = in... | [
"def get_inventory(self):\n from noc.inv.models.object import Object\n\n return list(Object.objects.filter(data__management__managed_object=self.id))",
"def get_equipment_from_inventory(self):\n return [x for x in self.inventory if x.is_equip()]",
"def hittable_targets(self):\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a list of targets where the labels match, otherwise just return the original targets | def search_targets(inventory_path, targets, labels):
if not labels:
return targets
try:
labels_dict = dict(label.split("=") for label in labels)
except ValueError:
raise CompileError(
"Compile error: Failed to parse labels, should be formatted like: kapitan compile -l en... | [
"def get_target_nets(self):\n return [getattr(self, f'target_{k}') for k in self.model \n if f'target_{k}' in self.model]",
"def targets(self, target_ids=None):\n return [self._target()]",
"def identify(cls, targets):\r\n return cls.combine_ids(target.id for target in targets)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compiles target_obj and writes to compile_path | def compile_target(target_obj, search_paths, compile_path, ref_controller, globals_cached=None, **kwargs):
start = time.time()
compile_objs = target_obj["compile"]
ext_vars = target_obj["vars"]
target_name = ext_vars["target"]
if globals_cached:
cached.from_dict(globals_cached)
use_go_... | [
"def compile_target_file(target_file, search_path, compile_path, **kwargs):\n target_obj = load_target(target_file)\n target_name = target_obj[\"vars\"][\"target\"]\n compile_obj = target_obj[\"compile\"]\n ext_vars = target_obj[\"vars\"]\n\n for obj in compile_obj:\n if obj[\"type\"] == \"jso... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates a target_obj Returns a dict object if target is valid Otherwise raises ValidationError | def valid_target_obj(target_obj, require_compile=True):
schema = {
"type": "object",
"properties": {
"vars": {"type": "object"},
"secrets": {
"type": "object",
"properties": {
"gpg": {
"type": "objec... | [
"def validate(self, obj):\n\n raise Error(\"Not implemented.\")",
"def _validate_object_reference(instance: typing.Dict[str, typing.Any], schema: typing.Dict[str, typing.Any], path: typing.List[str]) -> None:\n if not isinstance(instance, dict):\n raise ValidationError('instance must be dict', pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validates compiled output according to schemas specified in the inventory | def schema_validate_compiled(args):
if not os.path.isdir(args.compiled_path):
logger.error("compiled-path %s not found", args.compiled_path)
sys.exit(1)
if not os.path.isdir(args.schemas_path):
os.makedirs(args.schemas_path)
logger.info("created schema-cache-path at %s", args.sc... | [
"def check_database_content(self):\n\n self.run()\n for resource in self.datapackage.resources:\n resource_path = resource.local_data_path\n if os.path.exists(resource_path):\n options = {'schema': {'schema': resource.descriptor['schema']}}\n pipe = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validates given files according to kubernetes manifest schemas schemas are cached from/to cache_dir validate_data must be of structure ((kind, version), validate_files) | def schema_validate_kubernetes_output(validate_data, cache_dir):
(kind, version), validate_files = validate_data
KubernetesManifestValidator(cache_dir).validate(validate_files, kind=kind, version=version) | [
"def schema_validate_compiled(args):\n if not os.path.isdir(args.compiled_path):\n logger.error(\"compiled-path %s not found\", args.compiled_path)\n sys.exit(1)\n\n if not os.path.isdir(args.schemas_path):\n os.makedirs(args.schemas_path)\n logger.info(\"created schema-cache-path ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an instance of a extended cookie auth helper. | def manage_addBlowfishExtendedCookieAuthHelper(self, id, title='',
RESPONSE=None, **kw):
self = self.this()
o = BlowfishExtendedCookieAuthHelper(id, title, **kw)
self._setObject(o.getId(), o)
o = getattr(aq_base(self), id)
if RESPONSE is not None:
RE... | [
"def manage_addSecureLoginCookieAuthHelper(self, id, title='',\n RESPONSE=None, **kw):\n self = self.this()\n\n o = SecureLoginCookieAuthHelper(id, title, **kw)\n self._setObject(o.getId(), o)\n o = getattr(aq_base(self), id)\n\n if RESPONSE is not None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts note attributes into primitive values suitable for serialization and puts them into a dict. | def to_dict(self):
note_dict = {
'body': self.body,
'tags': self.tags,
'created_at': self.serialize_timestamp(self.created_at),
'modified_at': self.serialize_timestamp(self.modified_at),
'id': self.id
}
assert ... | [
"def test_note_asdict(fake_note_with_video_attachment):\n\n note_id_value: str = str(uuid.uuid4())\n a_note = Note.from_dict(note_id_value, fake_note_with_video_attachment)\n assert \"msdyn_workorder\" == a_note.asdict()['object_type']\n assert a_note.work_order_id == a_note.asdict()['work_order_id']\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts raw values from specified dict into a Note. The dict is expected to be suitable for serialization and therefore the values are expected to be of specific primitive types. | def from_dict(cls, note_dict):
missing_properties = set(cls.SERIALIZED_ATTRIBUTE_TYPES.keys()) - set(note_dict.keys())
if len(missing_properties) > 0:
raise MissingProperties("Some required properties are missing: {}".format(missing_properties))
for attribute in cls.SERIALIZED_ATTR... | [
"def from_dict(cls, dct):\n if dct.pop('type') != cls.__name__:\n fmt = 'Can not construct Note from dict %s'\n raise ValueError(fmt % dct)\n\n return cls(**dct)",
"def test_note_asdict(fake_note_with_video_attachment):\n\n note_id_value: str = str(uuid.uuid4())\n a_note ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return if this rule matches the URL. What to do if rule is matched is up to developer. Most likely ``.is_exception`` attribute should be taken in account. | def match_url(self, url, options=None):
options = options or {}
for optname in self.options:
if optname == 'match-case': # TODO
continue
if optname not in options:
raise ValueError("Rule requires option %s" % optname)
if optname == '... | [
"def can_handle(self, url):\n return self.url_re.match(url)",
"def match_url(self, url):\n pass",
"async def has_url(self, url: StrOrURL) -> bool:\n key = self.create_key('GET', url)\n return await self.responses.contains(str(key)) or await self.redirects.contains(str(key))",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether this rule can return meaningful result, given the `options` dict. If some options are missing, then rule shouldn't be matched against, and this function returns False. | def matching_supported(self, options=None):
if self.is_comment:
return False
if self.is_html_rule: # HTML rules are not supported yet
return False
options = options or {}
keys = set(options.keys())
if not keys.issuperset(self._options_keys):
... | [
"def is_valid(option_set):\n area = get_area(option_set)\n duration = get_duration(option_set)\n timepoint = get_time(option_set)\n\n # unknown options\n if area > AREA_VICE_MODEL or duration > DURATION_SEASON or \\\n timepoint > TIME_FOURTH_SEASON:\n return False\n\n # v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert AdBlock rule to a regular expression. | def rule_to_regex(cls, rule):
if not rule:
raise ValueError("Invalid rule")
# return rule
# escape special regex characters
rule = re.sub(r"([.$+?{}()\[\]\\])", r"\\\1", rule)
# XXX: the resulting regex must use non-capturing groups (?:
# for performance... | [
"def parseRule(s):\n return Parser._convertRule(ruleNT.parseString(s))",
"def arn_pattern_to_regex(arn_pattern): \n if not arn_pattern.startswith(\"arn:\"):\n raise ValueError(\"ARN pattern does not begin with 'arn:'.\")\n\n arn_segments = arn_pattern.split(':', 5)\n if len(arn_segments)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return if ``url``/``options`` are matched by rules defined by ``general_re``, ``domain_required_rules`` and ``rules_with_options``. ``general_re`` is a compiled regex for rules without options. | def _matches(self, url, options,
general_re, domain_required_rules, rules_with_options):
if general_re and general_re.search(url):
return True
rules = []
if 'domain' in options and domain_required_rules:
src_domain = options['domain']
for dom... | [
"def match_url(self, url, options=None):\n options = options or {}\n for optname in self.options:\n if optname == 'match-case': # TODO\n continue\n\n if optname not in options:\n raise ValueError(\"Rule requires option %s\" % optname)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> list(_domain_variants("foo.bar.example.com")) ['foo.bar.example.com', 'bar.example.com', 'example.com'] >>> list(_domain_variants("example.com")) ['example.com'] | def _domain_variants(domain):
parts = domain.split('.')
for i in range(len(parts), 1, -1):
yield ".".join(parts[-i:]) | [
"def list_domain_names():\n pass",
"def subdomains(self, domain: str) -> List[str]:\n subdomains: List[str] = []\n for entry in self.psql_query(\n \"\"\"\n select distinct(lower(name_value))\n FROM certificate_and_identities cai\n WHERE plainto_tsquery(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a compiled regex combined (using OR) from a list of ``regexes``. If there is nothing to combine, None is returned. | def _combined_regex(regexes, flags=re.IGNORECASE, use_re2=False, max_mem=None):
joined_regexes = "|".join(r for r in regexes if r)
if not joined_regexes:
return None
if use_re2:
import re2
return re2.compile(joined_regexes, flags=flags, max_mem=max_mem)
return re.compile(joined_... | [
"def regex_join(regexes):\n return \"|\".join(\"(?:%s)\" % r for r in regexes)",
"def to_regex(*args:List[str], flags:int=0, compile:bool=True) -> Union[str, re.compile]:\n pattern = \"\".join(args)\n\n if compile:\n return re.compile(pattern, flags=flags)\n else:\n flagstring = re_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for ``_create_occurrence`` method. | def test_create_occurrence(self):
occurrence = self.event._create_occurrence(now())
self.assertEqual(type(occurrence), Occurrence, msg=(
'Method ``_create_occurrence`` did not output the right type.')) | [
"def test_create_occurrence(self):\n pass",
"def create_occurrence (self):\n return self.create_topic().create_occurrence(self.create_topic(),\n 'Occurrence')",
"def test_create_activity_occurrence(self):\n pass",
"def test_get_occurrenc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for instantiation of the ``EventCategory`` model. | def test_instantiation(self):
event_category = EventCategory()
self.assertTrue(event_category) | [
"def test_create_category(self):\n pass",
"def test_create_cat_object():\n from .scripts.initializedb import create_cat_object\n cat_object = create_cat_object(\"a\", \"b\", \"c\", \"c\")\n assert isinstance(cat_object, Category)",
"def test_category_model_entry(self):\n data = self.data1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for instantiation of the ``EventRelation`` model. | def test_instantiation(self):
event_relation = mixer.blend('calendarium.EventRelation')
self.assertTrue(event_relation) | [
"def test_create_event_model_missing_creator(self):\n with self.assertRaises(ValidationError):\n e = Event(title=self.TITLE)\n e.save()",
"def test_instantiation(self):\n event_category = EventCategory()\n self.assertTrue(event_category)",
"def test_relations(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for instantiation of the ``Occurrence`` model. | def test_instantiation(self):
occurrence = Occurrence()
self.assertTrue(occurrence) | [
"def test_create_occurrence(self):\n occurrence = self.event._create_occurrence(now())\n self.assertEqual(type(occurrence), Occurrence, msg=(\n 'Method ``_create_occurrence`` did not output the right type.'))",
"def test_create_occurrence(self):\n pass",
"def test_get_occurrence(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for the ``delete_period`` function. | def test_delete_period(self):
occurrence = mixer.blend('calendarium.Occurrence')
occurrence.delete_period('all')
self.assertEqual(Occurrence.objects.all().count(), 0, msg=(
'Should delete only the first occurrence.'))
event = mixer.blend(
'calendarium.Event', sta... | [
"def test_delete_period_list(self):\n\t\tself.period_list.delete()\n\t\tself.assertFalse(self.period_list.pk)",
"def test_delete_grading_period_accounts(self):\r\n account_id = None # Change me!!\r\n id = None # Change me!!\r\n\r\n r = self.client.delete_grading_period_accounts(id, account_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for instantiation of the ``Rule`` model. | def test_instantiation(self):
rule = Rule()
self.assertTrue(rule) | [
"def test_create_rule(self):\n pass",
"def test_invalid_rule_mode_raises_when_create_rule(self):\n with self.assertRaises(InvalidRulesSchemaError):\n scanner_rules.Rule('exception', 0, [])",
"def test_rule(cls, rule, args, kwargs, expected, caplog):\n qalgebra.core.abstract_algebra.L... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send the EVT_PAGE_CHANGE to the parent. | def notify(self):
if self.GetParent() is not None:
evt = PageChangeEvent(from_page=self.GetName(),
to_page="page_annot_actions",
fct="")
evt.SetEventObject(self)
wx.PostEvent(self.GetParent(), evt) | [
"def page_changed(self, page):\n pass",
"def OnPage(self, event):\n try:\n newpage = int(self.page.GetValue())\n if 1 <= newpage <= self.numpages:\n if newpage != self.pageno:\n self.pageno = newpage\n self.ChangePage()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the current release of the application. By release, we mean the release from the version.json file à la Mozilla [1] (if any). If this file has not been found, it defaults to "NA". [1] | def get_release():
# Try to get the current release from the version.json file generated by the
# CI during the Docker image build
try:
with open(os.path.join(BASE_DIR, "version.json"), encoding="utf8") as version:
return json.load(version)["version"]
except FileNotFoundError:
... | [
"def read_release_version():\n with open(\"RELEASE-VERSION\", \"r\") as f:\n return f.readline().strip()",
"def current_release_version(ctx, param, value):\n version = None\n\n try:\n version = pkg_resources.resource_string(\n 'treadmill',\n 'VERSION.txt'\n )\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Kernels used for image processing | def __set_kernels(self):
self.clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) | [
"def __initializeKernels(self):\n # FFT plans:\n self.__initializeDopplerIfftPlan() # for Doppler Ifft\n self.__initializeDemodIfftPlan() # for demod \n self.__initializeSNRFftPlan() # for findSNR\n \n # GPU kernels\n kernel = self.CudaKernels\n ## kernels for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Masks a region specified by clockwise vertices. | def __mask_region(self, img, vertices):
mask = np.zeros_like(img)
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
cv2.fillConvexPoly... | [
"def set_region(img, vertices):\n mask = np.zeros_like(img)\n channel_count = img.shape[2]\n match_mask_color = (255,) * channel_count\n cv2.fillPoly(mask, vertices, match_mask_color)\n\n masked_img = cv2.bitwise_and(img, mask)\n\n new_mask = np.zeros(masked_img.shape[:2], np.uint8)\n\n bg = np... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enhances/sharpens the image using a clahe kernel | def __enhance_image(self, img):
blue = self.g.clahe.apply(img[:,:,0])
green = self.g.clahe.apply(img[:,:,1])
red = self.g.clahe.apply(img[:,:,2])
img[:,:,0] = blue
img[:,:,1] = green
img[:,:,2] = red
return img | [
"def __set_kernels(self):\n self.clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))",
"def applyUnsharp(image, kernel_size=(5, 5)):\n k=1.0\n sigma=1.0\n blurred = cv2.GaussianBlur(image, kernel_size, sigma) #Lowpass\n sharpened = float(k + 1) * image - float(k) * blurred #gmask\n sh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests the pipeline on one image | def test_one_image(self, img):
return self.__image_pipeline(img) | [
"def test_NIRCam_stage1(run_pipeline, fitsdiff_default_kwargs, output):\n rtdata = run_pipeline\n rtdata.output = output\n rtdata.get_truth(os.path.join(\"truth/nircam/test_detector1pipeline\", output))\n\n\n diff = FITSDiff(rtdata.output, rtdata.truth, **fitsdiff_default_kwargs)\n assert diff.identi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split fio reports and analysis after seperate lines is an list contains all fio reports | def split_report(self, lines):
start_line = 0
end_line = 0
fio_reports = []
for index in range(len(lines)):
if self._is_start(lines[index]):
start_line = index
end_line = 0
logging.debug("Found start line %s" % lines[index])
... | [
"def every_second_line(report):\n f = report\n \n result = []\n for line in f:\n result.append(line.strip())\n f.readline()",
"def data_process(self):\n logging.info('Processing the data and split files')\n lines = Utility.file_len(self.fname)\n self.lines_to_be, sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if report end As we just want to analysis IOPS, Bandwidth and latency to avoid report recieved abnormally our line end at any postion has submit/complete/issued/latency | def _is_end(self, line):
if re.match("\s+submit|complete|issued|latency\s+\:\s+.*", line):
return True | [
"def has_end_reason(self):\n # Someday I will have real end reasons\n return False",
"def report(self) -> bool:\n return int(self.packet[14:16], 16) == 3",
"def is_report(self):\n return True if self.type == 'ANL' else False",
"def is_call_ended(self) -> bool:",
"def closed_door_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get iops from result | def _get_iops(self, report):
match = re.search("iops\=(\d+)", report)
if match:
return int(match.group(1)) | [
"def iops(self) -> int:\n return pulumi.get(self, \"iops\")",
"def _op_t(self):\n return self.instr._insn.ops[self.opnum]",
"def get_opcodes():\n return OPCODES",
"def getResultAll(i=None):",
"def oper_result(self):\n return self._oper_result",
"def as_opcodes(self):\n raise... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get clat average from result | def _get_clat_avg(self, report):
match = re.search(".*clat\s*\((\w+)\).*avg\=\s*(\d+\.{0,1}\d*)",
report)
if match:
unit = match.group(1)
value = float(match.group(2))
if unit.lower() == "usec":
value = value / 1000
return v... | [
"def _get_average(self):\r\n if self.at_bats == 0:\r\n return 0.0\r\n\r\n return old_div(float(self.singles + self.doubles +\r\n self.triples + self.home_runs), self.at_bats)",
"def calcAvg(self):\n\n avg = (self.project + self.midterm + self.final) / 3\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get lat average from result | def _get_lat_avg(self, report):
match = re.search("\s*lat\s*\((\w+)\).*avg\=\s*(\d+\.{0,1}\d*)",
report)
if match:
unit = match.group(1)
value = float(match.group(2))
if unit.lower() == "usec":
value = value / 1000
return va... | [
"def average_lon(lon):\n sum = 0.0\n count = 0\n for num in lon:\n sum += num\n count += 1\n return sum / count",
"def gavg(idata):\n\t\n\twgt1=np.cos(np.deg2rad(idata.lat))*(idata*0+1)\n\tga=(wgt1*idata).sum(dim=['lat','lon'])/wgt1.sum(dim=['lat','lon'])\n\n\treturn ga",
"def getLatAv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple error reporting wrapper will allow us to plug in different error reporting backend(s) in the future | def init_error_reporting():
global error_reporter
SENTRY_DSN = 'https://e3b3b7139bc64177b9694b836c1c5bd6:fbd8d4def9db41d0abe885a35f034118@sentry.io/230474'
error_reporter = Client(SENTRY_DSN) | [
"def displayError(*args, **kwargs):\n \n pass",
"def run(self):\n self.simple_error()\n self.relative_error()",
"def error_test():\n checkresult(lib.ErrorTest())",
"def error_report(exc_info, program=None, output=\"\", email=None, files=[], listdirs=[], savedir=\"/tmp\", title=\"AUT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the fastest growing tweet. A tweet is the faster growing tweet if its "retweets/time" is bigger than the other's. >Tweet1 is 32.5 hours old and has 64 retweets. >Tweet2 is 3.12 hours old and has 30 retweets. >64/32.5 is smaller than 30/3.12 > tweet2 is the faster growing tweet. | def find_fastest_growing(tweets: list) -> Tweet:
fastest_growing = {}
for tweet in tweets:
fastest_growing[tweet.retweets / tweet.time] = tweet
return fastest_growing[max(fastest_growing)] | [
"def more_popular(twitter_data, a, b):\n \n a_popularity = len(all_followers(twitter_data, a)) \n b_popularity = len(all_followers(twitter_data, b))\n if a_popularity > b_popularity:\n return -1\n if a_popularity < b_popularity:\n return 1\n return username_first(twitter_data, a, b)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort tweets by popularity. Tweets must be sorted in descending order. A tweet is more popular than the other if it has more retweets. If the retweets are even, the newer tweet is the more popular one. >Tweet1 has 10 retweets. >Tweet2 has 30 retweets. >30 is bigger than 10 > tweet2 is the more popular one. | def sort_by_popularity(tweets: list) -> list:
tweets_by_popularity = sorted(tweets, key=lambda x: (x.retweets, -x.time), reverse=True) # Use lambda functions when an anonymous function is required for a short period of time.
return tweets_by_popularity | [
"def sort_hashtags_by_popularity(tweets: list) -> list:\n hashtags_by_popularity = {}\n pattern = r\"#\\w+\"\n for tweet in tweets:\n find_hashtag = re.findall(pattern, tweet.content)\n if not find_hashtag:\n continue\n else:\n for ht in find_hashtag:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter tweets by hashtag. Return a list of all tweets that contain given hashtag. | def filter_by_hashtag(tweets: list, hashtag: str) -> list:
tweets_with_hashtag = {} # findall(): Kui tekstis on rohkem kui üks regulaaravaldisele vastav alamsõne saab kõikide vastete järjendi moodustada funktsiooniga findall()
pattern = r"#\w+" # \w : tähed, numbrid, alakriips, + : 1 või rohkem
for tweet ... | [
"def get_hashtags(tweet):\r\n hashtags_liste = []\r\n hashtags = tweet.entities.get(\"hashtags\")\r\n for hashtag in hashtags :\r\n if hashtag['text'] in hashtags_liste:\r\n pass\r\n else:\r\n hashtags_liste.append(hashtag[\"text\"])\r\n return hashtags_liste",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort hashtags by popularity. Hashtags must be sorted in descending order. A hashtag's popularity is the sum of its tweets' retweets. If two hashtags are equally popular, sort by alphabet from AZ to az (upper case before lower case). >Tweet1 has 21 retweets and has common hashtag. >Tweet2 has 19 retweets and has common ... | def sort_hashtags_by_popularity(tweets: list) -> list:
hashtags_by_popularity = {}
pattern = r"#\w+"
for tweet in tweets:
find_hashtag = re.findall(pattern, tweet.content)
if not find_hashtag:
continue
else:
for ht in find_hashtag:
hashtags_by_... | [
"def sort_by_popularity(tweets: list) -> list:\n tweets_by_popularity = sorted(tweets, key=lambda x: (x.retweets, -x.time), reverse=True) # Use lambda functions when an anonymous function is required for a short period of time.\n return tweets_by_popularity",
"def hashtagCount(words):\n\n hashtags = wor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports grammar from path. Must work with relative and full paths. | def import_grammar(path):
grammar_name = os.path.basename(path).replace(".py", "")
grammar_file = f'restler_grammar_{grammar_name}_{os.getpid()}.py'
# import req_collection from given grammar
sys.path.append(os.path.dirname(path))
grammar = importlib.import_module(grammar_name)
req_collection =... | [
"def load_grammar(path):\n return SCFG(iterrules(smart_ropen(path)))",
"def parse_file(self, path):\r\n return self._parse(antlr3.ANTLRFileStream(path))",
"def Load(json_text, start_symbol, ignore='_reserved'):\n g = Grammar(json_text, start_symbol, ignore=ignore)\n g.canonicalize()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes all of the checkers, sets the appropriate checkers as enabled/disabled, and returns a list of checker objects | def get_checker_list(req_collection, fuzzing_requests, enable_list, disable_list, set_enable_first, custom_checkers, enable_default_checkers=True):
# Add any custom checkers
for custom_checker_file_path in custom_checkers:
try:
spec = importlib.util.spec_from_file_location('custom_checkers',... | [
"def create_checkers(config):\n\n checkers = []\n if 'checkers' in config:\n for checker_name, checker_config in config['checkers'].iteritems():\n if checker_name in __checkers:\n configs = None\n if type(checker_config) == list:\n configs = c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns content of the /etc/pki/tls/openssl.cnf file | def openssl_config():
config = open("/etc/pki/tls/openssl.cnf", "r")
contents = config.read().strip()
config.close()
return contents | [
"def _parse_opensslconf(self):\n# print \"parse_opensslconf\"\n _log.debug(\"__init__::parse_opensslconf\")\n if not self.config.read(self.configfile):\n# print \"could not parse config file\"\n # Empty openssl.conf file or could not successfully parse the file.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets section from OpenSSL config file | def openssl_config_get_section(section):
result = {}
parses = False
for line in openssl_config_strip(openssl_config()).split("\n"):
if line.lstrip().startswith("[") and line.rstrip().endswith("]") and line[1:-1].strip() == section:
parses = True
continue
if parses:
... | [
"def openssl_config():\n config = open(\"/etc/pki/tls/openssl.cnf\", \"r\")\n contents = config.read().strip()\n config.close()\n return contents",
"def get(section, key, inifile=\"settings.ini\"):\n config = ConfigParser.RawConfigParser()\n config.readfp(open(inifile))\n value = config.get(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map a 16bit image trough a lookup table to convert it to 8bit. | def map_uint16_to_uint8(files_hmds, lower_bound=0, upper_bound=40000):
# Check for errors
if not(0 <= lower_bound < 2**16) and lower_bound is not None:
raise ValueError('"lower_bound" must be in the range [0, 65535]')
elif not(0 <= upper_bound < 2**16) and upper_bound is not None:
raise Valu... | [
"def mapping(bits):\r\n return np.array([mappingTable[tuple(b)] for b in bits])",
"def image_16bit_to_8bit(img_16bit, autoscale=False):\n img_32 = np.array(img_16bit, dtype=np.uint32)\n\n if autoscale:\n min_intensity = np.min(img_32)\n img_32 -= min_intensity\n max_intensity = np.ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add audio into video | def add_audio_to_video(audio_path: Union[str, Path],
video_path: Union[str, Path],
out_video_path: [str, Path]) -> Path:
command = 'ffmpeg -loglevel warning -y -i "{}" -i "{}" -c:v copy -c:a copy -shortest {}'.format(
video_path.as_posix(),
audio_path.as... | [
"def add_audio(self, event):\n # The idea here is to use RVs stack to create two \"tracks\". The first input will be a\n # sequence of all the current sources, and the second the selected audio file.\n selected_files = commands.openMediaFileDialog(False, commands.OneExistingFile, \"\", \"\", \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copy another video's audio into current video | def copy_audio_from_another_video(no_audio_video_path: Union[str, Path],
with_audio_video_path: [str, Path],
out_video_path: [str, Path]) -> Path:
no_audio_video_path = Path(no_audio_video_path)
with_audio_video_path = Path(with_audio_video_pat... | [
"def transfer_audio(source_video: Any, target_video: Any) -> None:\n # First, validate that FFMPEG is installed, otherwise this method\n # will not be able to perform any actions and will instead result\n # in a cryptic error message (that is not really useful).\n if not is_ffmpeg_installed():\n print(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Effettua il calcolo usando metodo postfix. | def postfix(t_input):
# guardo se gli elementi contengono caratteri non validi
if is_valid(t_input) == 1:
# restituisco Invalid se sono stati trovati caratteri invalidi
result = "Invalid"
return result
# scorri di nuovo gli elementi
# NOTA: sarebbe piu' efficiente fare u... | [
"def prependPostfix(self,pre) :\n self._postfix = pre + self._postfix",
"def postfix(self):\n return self.__render_values(self.__prefix)",
"def infix_to_postfix(self, exp):\n\n try:\n for i in exp:\n #if the character is an operand output it\n if sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rotate an array k90 degrees in the counterclockwise direction around the given axis | def rot90(m, k=1, axis=2):
m = np.swapaxes(m, 2, axis)
m = np.rot90(m, k)
m = np.swapaxes(m, 2, axis)
return m | [
"def rot90(a, k=1, axes=(0, 1)):\n a_ndim = a.ndim\n if a_ndim < 2:\n raise ValueError('Input must be >= 2-d')\n\n axes = tuple(axes)\n if len(axes) != 2:\n raise ValueError('len(axes) must be 2')\n if axes[0] == axes[1] or abs(axes[0] - axes[1]) == a_ndim:\n raise ValueError('ax... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |