query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Load sample images for image manipulation. Loads both, ``china`` and ``flower``. Returns | def load_sample_images():
# Try to import imread from scipy. We do this lazily here to prevent
# this module from depending on PIL.
try:
try:
from scipy.misc import imread
except ImportError:
from scipy.misc.pilutil import imread
except ImportError:
raise ... | [
"def load_images(self):\n for f in glob.glob('pix/weather/*.png'):\n base = os.path.splitext(os.path.basename(f))[0]\n self.images[base] = itk.PhotoImage(file=f)",
"def load_images(self):\r\n self.standing_frame = [load_image(\"cat1.png\")]\r\n self.walk_frames_r = [load... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recreate the (compressed) image from the code book & labels | def recreate_image(codebook, labels, w, h):
d = codebook.shape[1]
image = np.zeros((w, h, d))
label_idx = 0
for i in range(w):
for j in range(h):
image[i][j] = codebook[labels[label_idx]]
label_idx += 1
return image | [
"def recreate_image(codebook, labels, w, h):\n d = codebook.shape[-1]\n image = np.zeros((w, h, d))\n label_idx = 0\n for i in range(w):\n for j in range(h):\n #print labels[label_idx], label_idx\n image[i][j] = codebook[labels[label_idx]]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
linearly scale the values of an array in the range [0, 1] | def scale01(arr):
walk_arr_01 = numpy.interp(arr, (numpy.amin(arr), numpy.amax(arr)), (-1, +1)) # linear scaling
return walk_arr_01 #return the scaled array
| [
"def linear_rescale(min, max, value):\n x = (value - min)/(max - min)\n return x",
"def scale0to1(img):\r\n\r\n min = np.min(img)\r\n max = np.max(img)\r\n\r\n if min == max:\r\n img.fill(0.5)\r\n else:\r\n img = (img-min) / (max-min)\r\n\r\n return img.astype(np.float32)",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
extends the init_buffer of OffsetColorProgram class by creating the additional carry flag VBO | def _init_buffers(self, v, n, _):
super()._init_buffers(v, n, _)
self.vbos.append(gl.glGenBuffers(1))
# init VBO 2 - dynamic color data
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbos[3])
loc = self.get_attribute_location("carried")
gl.glEnableVertexAttribArray(loc)
... | [
"def set_buffer(self, shader, offset):\n Buffer.bind_vbo(self.vertices)\n Buffer.bind_ebo(self.indexes)\n Buffer.get_attribute_location(shader, \"position\")\n Buffer.vertex_attribute(6, 0, 0)\n Buffer.get_attribute_location(shader, \"aNormal\")\n Buffer.vertex_attribute(6,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
updates the carry flag data (VBO3) | def update_carried(self, data):
self.use()
gpu_data = np.array(data, dtype=np.float32)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbos[3])
gl.glBufferData(gl.GL_ARRAY_BUFFER, gpu_data.nbytes, gpu_data, gl.GL_DYNAMIC_DRAW) | [
"def update_flags(self):\n # view mode, filled vs wirefrom\n if self.view['wireframe']:\n gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)\n else:\n gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL)\n\n # set fullscreen or windowed\n self.set_fullscreen(fu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets scale control bitword = 0 x, y frozen scales + 1 x is interactive + 2 y is interactive bit value 0/1 frozen/interactive | def set_scale_control(self, scale_ctl=3):
self._scale_ctl = scale_ctl | [
"def setScale(self, x, y):\r\n self.scale(x,y)",
"def set_scale(self, scale=2):\n\n CTRL_REG4 = self.single_access_read(0x23)\n\n scaleBits = 0b00 # default value\n self.scale = 2\n\n if scale == 4:\n scaleBits = 0b01\n self.scale = 4\n elif scale =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get versions of EFI, Boot ROM, OS & Mac Device as well as the SysUUID | def gather_system_versions(self):
# Get Mac model ID
self.hw_version = str(
IORegistryEntryCreateCFProperty(
IOServiceGetMatchingService(
0,
IOServiceMatching("IOPlatformExpertDevice")),
"model",
None,
... | [
"def getOSinfo_all():\n\tagentPlatForm = platform.system()\n\treturn agentPlatForm\n\t# print agentPlatForm\n\t# command_systeminfo = 'uname -a'\n\t# command_HDD_linux = 'df -h'\n\t# #get\n\t# systeminfo = os.system(command_systeminfo)\n\t# IPlist = socket.gethostbyname(socket.gethostname())\n\t# # HDD_linux = os.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the OS version are you running, what is the highest available build number? Are you running it? | def check_highest_build(self, sys_info, api_results):
if not api_results.get("latest_build_number"):
self.results[self.current_endpoint]["latest_build_number"] = self.__make_api_get(
'/apple/latest_build_number/%s' % (".".join(sys_info.get("os_ver").split(".")[:2])))
self.me... | [
"def version_max():\n return VERSION_MAX",
"def get_os_build_version():\n out = subprocess.check_output(['sysctl', '-n', 'kern.osversion'],\n universal_newlines=True).splitlines()\n assert len(out) == 1, out\n return out[0]",
"def get_os_release():\n return re.match('[\\d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Preprocess graphs by casting into FloatTensor and setting to cuda if available | def preprocess(dataset, cuda):
for g, _ in dataset:
for key_g, val_g in g.ndata.items():
processed = g.ndata.pop(key_g)
processed = processed.type('torch.FloatTensor')
if cuda:
processed = processed.cuda()
g.ndata[key_g] = processed
for... | [
"def ggml_cuda_compute_forward(params: ffi.CData, tensor: ffi.CData) -> bool:\n ...",
"def ggml_cuda_transform_tensor(data: ffi.CData, tensor: ffi.CData) -> None:\n ...",
"def _to_cpu(self):\n self._get_device('cpu')\n self.to(self.device)\n torch.cuda.empty_cache()",
"def ggml_mpi_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the languages stored in the dictionaries | def plot_languages(dict_usage_complexities, dict_cognitive_complexity):
attested_languages = (
frozenset(['nor', 'and', 'or', 'not']),
frozenset(['and', 'or', 'not']),
frozenset(['and', 'not']),
frozenset(['or', 'not']),
)
fig, ax = plt.subplots(figsize=(8.27,4))
for nam... | [
"def cistime_lang():\n timing.plot_scalings(compare='language')",
"def visualize_vecDict(vecDict):\n for url in vecDict:\n plt.plot(vecDict[url])\n plt.legend([key for key in vecDict])\n plt.title(f'Vectors for {len(vecDict)} Documents')\n plt.xlabel('Vector Dimensions')\n plt.ylabel('Doc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge draft invoices. Work only with same partner. You can merge invoices and refund invoices with echa other. Moves all lines on the first invoice. | def merge_invoice(self, cr, uid, invoices, context=None):
order_ids = []
pick_ids = []
if len(invoices) <= 1:
return False
parent = self.pool.get('account.invoice').browse(cr, uid, context['active_id'])
for inv in invoices:
if parent.partner_id != inv.part... | [
"def merge_purchase_invoice(self):\r\n active_id = self.env['purchase.order'].browse(self.env['purchase.order']._context.get('active_ids'))\r\n journal_id = self.env['account.journal'].search([('type', '=', 'purchase')]) \r\n active_id_count = 0\r\n active_count = 0\r\n exist_vend... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Return the standard path to the shared area on the current platform. | def shared_area_path() -> str:
try:
return os.environ["OITG_SHARED_AREA"]
except KeyError:
pass
if os.name == "nt": # Windows
return "Z:\\"
if os.name == "unix" or os.name == "posix": # Linux / OSX / ...
return os.path.expanduser("~/steaneShared/")
raise Exception... | [
"def get_share_path():\n cwd = os.path.dirname(__file__)\n share = os.path.join(cwd, '../share')\n return os.path.abspath(share)",
"def get_root_path():\n\n return \"\" if PLATFORM == \"windows\" else \"/\"",
"def path_extern_mounts(self) -> PurePath:\n return self.path_extern_supervisor / MO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the path to the given users analysis directory on the shared area (``/Users//analysis``). | def analysis_root_path(user: Optional[str] = None) -> str:
if user is None:
user = _get_user()
return os.path.join(shared_area_path(), "Users", user, "analysis") | [
"def todays_analysis_path(day: Optional[str] = None, user: Optional[str] = None) -> str:\n if day is None:\n day = date.today().isoformat()\n if user is None:\n user = _get_user()\n path = os.path.join(analysis_root_path(user=user), day)\n\n if not os.access(path, os.R_OK):\n # If t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the path to the analysis directory for the given day, defaulting to today. The analysis directory is intended to be used as working space for analysing data while it is taken, so that the code can easily be found again later if the data or conclusions reached are reexamined. If the directory does not exist, it i... | def todays_analysis_path(day: Optional[str] = None, user: Optional[str] = None) -> str:
if day is None:
day = date.today().isoformat()
if user is None:
user = _get_user()
path = os.path.join(analysis_root_path(user=user), day)
if not os.access(path, os.R_OK):
# If the dir does n... | [
"def set_up_directory(day):\n this_dir = os.path.dirname(__file__)\n new_dir = os.path.join(this_dir, 'day' + str(day))\n with contextlib.suppress(FileExistsError):\n os.mkdir(new_dir)\n new_file_name = os.path.join(new_dir, 'day' + str(day) + '.py')\n template_file_name = os.path.join(this_di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the path to an experiment's ARTIQ results directory. The standard results path is ``/artiqResults/``. | def artiq_results_path(experiment: Optional[str] = None) -> str:
path = os.path.join(shared_area_path(), "artiqResults")
if experiment is None:
try:
experiment = os.environ["OITG_EXPERIMENT"]
except KeyError:
raise Exception(
"No experiment supplied, and... | [
"def get_results_dir() -> str:\n return os.path.join(os.getcwd(), RESULTS_DIR)",
"def get_results_path(results_path, experiment, prefix, mode):\n if not experiment:\n raise ArgumentError('experiment cannot be empty')\n if not prefix:\n raise ArgumentError('prefix cannot be empty')\n if n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
estimate an MxF user factor matrix and an FxN item factor matrix from the MxN rating matrix | def factor_mat(all_dat, f_num, iterations, regularization):
# get # of users and # of items
[u_num, i_num] = all_dat.shape
# init user factors and item factors with random values
u_fac = np.matrix(np.random.rand(u_num, f_num)) # MxF
i_fac = np.matrix(np.random.rand(i_num, f_num)) # NxF
# calculate the preferen... | [
"def create_matrix(self):\n\n self.matrix = np.zeros((len(self.users), len(self.items)))\n\n for user in self.train_set['users']:\n for item in self.train_set['feedback'][user]:\n self.matrix[self.user_to_user_id[user]][self.item_to_item_id[item]] = \\\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get list of Domains for this API key. | def get_domains() -> List[str]:
ret = _call_endpoint("v1/domains")
# Example response:
# [{'createdAt': '2016-06-25T03:08:44.000Z',
# 'domain': 'mydomain.com',
# 'domainId': 12345678,
# 'expirationProtected': False,
# 'expires': '2020-06-25T03:08:44.000Z',
# 'holdRegistrar': False,
... | [
"def get_domains(self):\n\n response = self.call(method='getDomains')\n domains = []\n for d in response:\n domain = self.domain(domain=d['domain'])\n domains.append(domain)\n return domains",
"def get_domains(self):\n return self.rest_helper(\"/domains.jso... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get DNS entries for a specific domain | def get_domain_dns_records(domain):
url_suffix = "v1/domains/{}/records".format(domain)
ret = _call_endpoint(url_suffix)
if isinstance(ret, dict) and ret.get('code', None) == "UNKNOWN_DOMAIN":
# e.g. {'code': 'UNKNOWN_DOMAIN', 'message': 'The given domain is not registered, or does not have a zone f... | [
"def list(self, domain):\n return request(\n API_LIST.DNS_LIST.value,\n {\n 'email': self.email,\n 'token': self.token,\n 'domain': domain\n }\n )",
"def get_dns_records(self, d):\n try:\n host = d['host'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print each domain and its DNS records (for domains linked to this API key). | def print_all_dns_records():
for domain in sorted(get_domains()):
dns_records = get_domain_dns_records(domain)
print(domain)
pprint(dns_records)
print("*" * 50)
# TODO: poor man's rate limiter. improve?
time.sleep(2) | [
"def print_all_domain_lists(self):\n for list in self.domainCollection:\n print(list.url_identifier)",
"def display_elb_dns_entries():\n stack_name = get_stack_name()\n elb = get_connection(ELB)\n elb_dns_list = elb.list_domain_names(stack_name)\n for elb_dns in elb_dns_list:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a request handler class that redirects to supplied `url` | def redirect_handler_factory():
class RedirectHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(301)
domain = self.headers['host']
if ':' in domain:
domain = domain.split(':')[0]
self.send_header('Locatio... | [
"def redirect_handler_factory(url):\n class RedirectHandler(http.server.SimpleHTTPRequestHandler):\n def do_GET(self):\n self.send_response(302)\n self.send_header('Location', url)\n self.end_headers()\n\n return RedirectHandler",
"def redirect(url):",
"def redirect... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
loop and copy console>serial until config.exit_char character is found. when config.menu_char is found, interpret the next key locally. | def writer(self):
menu_active = False
try:
while self.alive:
try:
char = self.console.getkey()
except KeyboardInterrupt:
char = '\x03'
if menu_active:
# Menu character again/exit char... | [
"def writer(self):\n menu_active = False\n try:\n while self.alive:\n try:\n c = console.getkey()\n except KeyboardInterrupt:\n c = '\\x03'\n if menu_active:\n if c == MENUCHARACTER or c ==... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Getting mri (most recent influence) Returns 0 if no influence exists | def _get_mri(journal):
try:
return Influence.objects.filter(journal__issn=journal.issn).order_by('-date_stamp')[0]
except IndexError:
return 0 | [
"def getFirstLumi(self):\n if hasattr(self.data, \"production\"):\n if hasattr(self.data.production, \"firstLumi\"):\n return self.data.production.firstLumi\n return 1",
"def get_last_reward(self):\n return self.last_reward",
"def getInitialMomentum(self) -> int:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if the node is a "real" endpoint of an edge in the network, \ otherwise False. OSM data includes lots of nodes that exist only as \ points to help streets bend around curves. An end point is a node that \ | def is_endpoint(G: nx.Graph, node: int, strict=True):
neighbors = set(list(G.predecessors(node)) + list(G.successors(node)))
n = len(neighbors)
d = G.degree(node)
if node in neighbors:
# If the node appears in its list of neighbors, it self-loops. this is
# always an endpoint.
... | [
"def node_is_edge(self, node: MazeCell) -> bool:\n return node.x == 0 or node.x == self._ncols - 1 or node.y == 0 or node.y == self._nrows - 1",
"def has_edge(self, e):\r\n return e in self.edges",
"def isNodeRegisteredWithinEndpoint(self):\n pass",
"def is_external_edge(self, eid):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively build a path of nodes until you hit an endpoint node. Please note this method is taken directly from OSMnx, and can be found in \ | def build_path(
G: nx.Graph,
node: int,
endpoints: List[int],
path: List[int]) -> List[int]:
# For each successor in the passed-in node
for successor in G.successors(node):
if successor not in path:
# If successor is already in path, ignore it, otherwise add ... | [
"def get_path(self,first_node,last_node):\n edge_pattern=re.compile('edge_(?P<begin_node>\\w+)_(?P<end_node>\\w+)_(?P<iterator>\\w+)')\n exit_paths=self.get_exiting_edges(first_node)\n next_nodes=self.get_exiting_nodes(first_node)\n #be careful here using the wrong assignment statement b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a list of all the paths to be simplified between endpoint nodes. \ The path is ordered from the first endpoint, through the interstitial \ nodes, to the second endpoint. Please note this method is taken directly from OSMnx, and can be found in \ | def get_paths_to_simplify(G: nx.Graph, strict: bool=True) -> List[List[int]]:
# First identify all the nodes that are endpoints
endpoints = set([node for node in G.nodes()
if is_endpoint(G, node, strict=strict)])
# Initialize the list to be returned; an empty list
paths_to_simplif... | [
"def convert_paths(self):\n # convert to node sequences, dropping s'\n self.nodeseq_paths = []\n for path in self.paths:\n node_seq = [] # don't include s'\n for arc in path:\n node_seq.append(self.arc_info[arc]['destin'])\n self.nodeseq_paths.ap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Archive a GIT project and upload it to Dash. | def deploy_project(name, apikey, changed_files=None, repo=None,
branch='master'):
zbuff = StringIO()
if changed_files is not None:
changed_files = list(set(changed_files) | REQUIRED_FILES)
_archive_project(name, zbuff, changed_files, repo, branch)
zbuff.reset()
payload = {... | [
"def __gitCreateArchive(self):\n self.vcs.gitCreateArchive(self.project.getProjectPath())",
"def git_archive_and_upload_tar():\n current_branch = str(subprocess.Popen('git branch | grep \"*\" | sed \"s/* //\"', \\\n shell=True,\\\n stdin=subprocess.PIPE, \\\n stdout=subp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search existing spider names in a project | def search_spider_names(project, apikey, name=''):
payload = {'project': project, 'apikey': apikey, 'spider': name}
req = requests.get(DASH_API_URL + 'spiders/list.json',
params=payload)
if req.status_code == 200:
return [s.get('id') for s in req.json().get('spiders', [])]
... | [
"def site_search(name):\n return Site.find_by_name(name)",
"def searchSite(search_name):\n for obj in obj_list:\n if search_name == obj.name:\n print(obj)\n break\n else:\n print(\"No climbing site with that name found... Returning to main menu.\")\n menu()",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Download a zipped project from Dash. | def _download_project(name, apikey):
payload = {'apikey': apikey, 'project': name, 'version': 'portia'}
r = requests.get(DASH_API_URL + 'as/project-slybot.zip', params=payload)
return r.content | [
"def download_data():\n url = 'https://www.dropbox.com/s/h9ubx22ftdkyvd5/ml-latest-small.zip?dl=1'\n urllib.request.urlretrieve(url, 'ml-latest-small.zip')\n zfile = zipfile.ZipFile('ml-latest-small.zip')\n zfile.extractall()\n zfile.close()",
"def download_data():\n url = 'https://www.dropbox.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert to front facing coordinates | def get_front_facing_xz(self):
yaw_radian = math.radians(self.cur_rotation)
return cam.step * math.sin(yaw_radian) * math.cos(0), cam.step * math.cos(
yaw_radian) * math.cos(0) | [
"def make_front_pos(self):\n self.front_pos = (self.base_pos[0], (self.base_pos[1] - self.imageheight))\n\n self.front_pos = self.rotationxy(self.base_pos, self.front_pos, self.radians_angle)",
"def get_front_facing_xz():\n yaw_radian = math.radians(rot_deg)\n return move_speed * math.sin(yaw_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called by base init, after class change or format text change | def initFormat(self):
pass | [
"def init_text(self):\n d = self.declaration\n if d.text:\n self.set_text(d.text)\n if d.text_color:\n self.set_text_color(d.text_color)\n if d.text_alignment:\n self.set_text_alignment(d.text_alignment)\n if d.font_family or d.text_size:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change this field's type to newType with default format | def changeType(self, newType):
self.__class__ = globals()[newType + 'Format']
self.format = self.defaultFormat
self.initFormat() | [
"def changeFormatFieldType(self, formatName, fieldName, newFieldType):\n nodeFormat = (globalref.mainControl.activeControl.model.\n formats[formatName])\n field = nodeFormat.fieldDict[fieldName]\n field.changeType(newFieldType)",
"def reformat(self, newformat):\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns English name if assigned, o/w name | def englishName(self):
if self.enName:
return self.enName
return self.name | [
"def english_name(self) -> str | None:\n return self.get_display_name(Locale('en'))",
"def english_name(self):\n return self.language.english_name",
"def english_name(self):\n return self._english_name",
"def name_en(self):\n return self._name_en",
"def get_localized_name(name):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return name used for labels add for required fields | def labelName(self):
if self.isRequired:
return '%s*' % self.name
return self.name | [
"def label(field):\n if hasattr(field,'long_name'):\n return field.long_name\n elif hasattr(field,'units'):\n return \"%s (%s)\"%(field.nxname,field.units)\n else:\n return field.nxname",
"def name_field_label(self):\n return self._name_field_label",
"def label_name(self) ->... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return formatted text, properly escaped if not in titleMode | def formatOutput(self, storedText, titleMode, internal=False):
prefix = self.prefix
suffix = self.suffix
if titleMode:
if self.html:
storedText = self.removeMarkup(storedText)
if globalref.docRef.formHtml:
prefix = self.removeMarkup(prefix)... | [
"def __repr_title(self):\n return (\n self.title if not self.done\n else '̶'.join(c for c in self.title)\n )",
"def output_plain_sep_title(title):\n print(f\"{plain_sep_mark}\\t{title}{plain_sep_mark}\")",
"def html_title(title):\n return '<center><h1>%s</h1></center>' ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return tuple of this field's text in edit format and bool validity, using edit format option | def editText(self, item):
storedText = item.data.get(self.name, '')
result = self.formatEditText(storedText)
if self.isRequired and not result[0]:
return (result[0], False)
return result | [
"def storedText(self, editText):\n if editText in self.formatList:\n return (editText, True)\n return (editText, not editText and not self.isRequired)",
"def storedText(self, editText):\n try:\n return (repr(GenBoolean(editText)), True)\n except GenBooleanError:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return initial value in edit format, found in edit format option | def getEditInitDefault(self):
return self.formatEditText(self.initDefault)[0] | [
"def formatter(self):\n want_edit = str(self.ctype_box.currentText())\n default_value = self.data.get(want_edit, \"\")\n self.value_box.setText(default_value)",
"def getEditInitDefault(self):\n if self.initDefault in DateFormat.dateStampStrings:\n return DateFormat.dateStamp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of choices for setting the init default | def initDefaultChoices(self):
return [] | [
"def initDefaultChoices(self):\n return [entry[0] for entry in self.getEditChoices()]",
"def get_choices(self):\r\n return []",
"def get_choices(self, instance):\n if instance.type == BaseParameter.CHOICE_TYPE:\n return [\n x.value\n for x in instanc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return tuple of stored text from edited text and bool validity, using edit format option | def storedText(self, editText):
if editText in self.formatList:
return (editText, True)
return (editText, not editText and not self.isRequired) | [
"def storedText(self, editText):\n try:\n return (repr(GenBoolean(editText)), True)\n except GenBooleanError:\n if editText in self.formatList:\n return (editText, True)\n return (editText, not editText and not self.isRequired)",
"def editText(self, it... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return list of choices for combo box, each a tuple of edit text and any annotation text | def getEditChoices(self, currentText=''):
return [(text, '') for text in self.formatList] | [
"def get_choices(self):\r\n return []",
"def selection_field_vocab(context, widget, data):\n return [\n ('opt_1', _('opt_1', default=u'Option 1')),\n ('opt_2', _('opt_2', default=u'Option 2')),\n ('opt_3', _('opt_3', default=u'Option 3'))\n ]",
"def choices_completion_item() ->... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split textStr using editSep, double sep's become char | def splitText(self, textStr):
return [text.strip().replace('\0', self.editSep) for text in
textStr.replace(self.editSep * 2, '\0').
split(self.editSep)] | [
"def test_prepare_value_with_custom_separator(self):\n field = ListEditField(sep=';')\n\n self.assertEqual(\n field.prepare_value(' foo; bar ; baz '),\n ['foo', 'bar', 'baz'])",
"def split(string, sep='\\t'):\n return text_type.split(string, sep)",
"def tab2text(self, text,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return tuple of choices from inText sorted like format and True if all splits are valid and included | def sortedChoices(self, inText):
choices = self.splitText(inText)
sortedChoices = [text for text in self.formatList if text in choices]
if len(choices) == len(sortedChoices):
return (sortedChoices, True)
else:
return (sortedChoices, False) | [
"def complete_opt_allow_select_scan(self, text, *_):\n return [t for t in (\"true\", \"false\", \"yes\", \"no\") if t.startswith(text.lower())]",
"def _determine_guess(\n sentences: List[List[Literal]]) -> Tuple[bool, Tuple[str, bool]]:\n literals = [x[0] for x in sentences if len(x) == 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of choices for setting the init default | def initDefaultChoices(self):
return [entry[0] for entry in self.getEditChoices()] | [
"def initDefaultChoices(self):\n return []",
"def get_choices(self):\r\n return []",
"def get_choices(self, instance):\n if instance.type == BaseParameter.CHOICE_TYPE:\n return [\n x.value\n for x in instance.get_typed_parameter().get_available_choic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort menu list choices | def sortChoices(self):
self.formatList.sort() | [
"def _buildSortMenu(cls):\r\n res = [(elt[0], elt[1]) for elt in cls._SORT_OPTIONS]\r\n cls._SORT_MENU = [('relevance', 'relevance')] + res",
"def choice_sort(A):\n pass",
"def sort(self):\n self.BoxList.sort(key=lambda x: x.id_, reverse=False)",
"def shell_sort(input_list):",
"def applicati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set initial value from editor version using edit format option | def setInitDefault(self, editText):
if editText in DateFormat.dateStampStrings:
self.initDefault = DateFormat.dateStampStrings[0]
else:
TextFormat.setInitDefault(self, editText) | [
"def formatter(self):\n want_edit = str(self.ctype_box.currentText())\n default_value = self.data.get(want_edit, \"\")\n self.value_box.setText(default_value)",
"def getEditInitDefault(self):\n if self.initDefault in DateFormat.dateStampStrings:\n return DateFormat.dateStamp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return initial value in edit format, found in edit format option | def getEditInitDefault(self):
if self.initDefault in DateFormat.dateStampStrings:
return DateFormat.dateStampStrings[1]
return TextFormat.getEditInitDefault(self) | [
"def formatter(self):\n want_edit = str(self.ctype_box.currentText())\n default_value = self.data.get(want_edit, \"\")\n self.value_box.setText(default_value)",
"def getEditInitDefault(self):\n return self.formatEditText(self.initDefault)[0]",
"def value(self):\n if not self.f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return conditional comparison value with realtime adjustments, used for date and time types' 'now' value | def adjustedCompareValue(self, value):
if value.startswith('now'):
return repr(GenDate())
return value | [
"def adjustedCompareValue(self, value):\n if value.startswith('now'):\n return repr(GenTime())\n return value",
"def condition(self):\n HH = str(time.localtime().tm_hour)\n MM = str(time.localtime().tm_min)\n return eval(self._cond_str)",
"def get_state_by_time(pyth... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return conditional comparison value with realtime adjustments, used for date and time types' 'now' value | def adjustedCompareValue(self, value):
if value.startswith('now'):
return repr(GenTime())
return value | [
"def adjustedCompareValue(self, value):\n if value.startswith('now'):\n return repr(GenDate())\n return value",
"def condition(self):\n HH = str(time.localtime().tm_hour)\n MM = str(time.localtime().tm_min)\n return eval(self._cond_str)",
"def get_state_by_time(pyth... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return tuple of stored text from edited text and bool validity, using edit format option | def storedText(self, editText):
try:
return (repr(GenBoolean(editText)), True)
except GenBooleanError:
if editText in self.formatList:
return (editText, True)
return (editText, not editText and not self.isRequired) | [
"def storedText(self, editText):\n if editText in self.formatList:\n return (editText, True)\n return (editText, not editText and not self.isRequired)",
"def editText(self, item):\n storedText = item.data.get(self.name, '')\n result = self.formatEditText(storedText)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the next value for a new node, increment format if increment is True | def nextValue(self, increment=True):
try:
prefix, numText, suffix = UniqueIDFormat.formatRe.\
match(self.format).groups()
except AttributeError:
self.format = UniqueIDFormat.defaultFormat
return self.nextValue(increment)
v... | [
"def get_next(self): \n return self.nextval",
"def _calc_next(self):\n d = self.interval\n self.next = d + int(time.time() / d)*d",
"def next_node(self):\r\n # always increment to try and generate unique ids\r\n self.node_counter += 1\r\n # ... but also check nod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return formatted text, properly escaped and with a link to the picture if not in titleMode | def formatOutput(self, storedText, titleMode, internal=False):
if titleMode:
return TextFormat.formatOutput(self, storedText, titleMode,
internal)
paths = storedText.split('\n')
results = ['<img src="%s">' % escape(url, treedoc.escDict) for ... | [
"def image(self, src, title, text):\n src = escape_link(src)\n text = escape(text, quote=True)\n if title:\n title = escape(title, quote=True)\n html = '<img src=\"%s\" alt=\"%s\" title=\"%s\"' % (src, text, title)\n else:\n html = '<img src=\"%s\" alt=\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interpolates between two vectors that are nonzero and don't both lie on a line going through origin. First normalizes v2 to have the same norm as v1. Then interpolates between the two vectors on the hypersphere. | def interpolate_hypersphere(v1, v2, num_steps):
v1_norm = tf.norm(v1)
v2_norm = tf.norm(v2)
v2_normalized = v2 * (v1_norm / v2_norm)
vectors = []
for step in range(num_steps):
interpolated = v1 + (v2_normalized - v1) * step / (num_steps - 1)
interpolated_norm = tf.norm(interpolated)
... | [
"def intersectionOfTwoLines(p1, v1, p2, v2):\n # if we transform multiple points in one go\n if len(v1.shape) == 2:\n a1 = np.einsum('ij,ij->i', v1, v1)\n a2 = np.einsum('ij,ij->i', v1, v2)\n b1 = -np.einsum('ij,ij->i', v2, v1)\n b2 = -np.einsum('ij,ij->i', v2, v2)\n c1 = -n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a set of images, show an animation. | def animate(images):
images = np.array(images)
converted_images = np.clip(images * 255, 0, 255).astype(np.uint8)
imageio.mimsave('./animation.gif', converted_images)
return embed.embed_file('./animation.gif') | [
"def animate(self, images, delay=.25):\n for image in images:\n # Draw the image on the display buffer.\n self.set_image(image)\n\n # Draw the buffer to the display hardware.\n self.write_display()\n time.sleep(delay)",
"def display_frames_as_gif(frame... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract the session token from the secret_key field. | def extract_session_from_secret(secret_key, session_token):
if secret_key and '@@@' in secret_key and not session_token:
return secret_key.split('@@@')[0], secret_key.split('@@@')[1]
else:
return secret_key, session_token | [
"def get_token_by_session(self, session_id):\n LOG.debug(\"Get token for session id {}\".format(session_id))\n return self.sessions.get_secret(session_id)",
"def get_session(session_token: str):\n service_session_token= app.db.fetchone(\"\"\"SELECT * FROM service_session_token WHERE session_token... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing to do a scrap of consumed material. | def test_manufacturing_scrap(self):
# Update demo products
(self.product_4 | self.product_2).write({
'tracking': 'lot',
})
# Update Bill Of Material to remove product with phantom bom.
self.bom_3.bom_line_ids.filtered(lambda x: x.product_id == self.product_5).unlink... | [
"def test_extract_recipe_from_website(self):\n pass",
"def test_get_items_peas_get(self):\n pass",
"def test_JCB_VISUAL_MATERIALS( self ):\n driver = self.driver\n driver.get(self.base_url + \"/record=b5660654~S6\")\n driver.find_element_by_link_text(\"Request\").click()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This test checks a tracked manufactured product will go to location defined in putaway strategy when the production is recorded with product.produce wizard. | def test_putaway_after_manufacturing_3(self):
self.laptop.tracking = 'serial'
mo_laptop = self.new_mo_laptop()
serial = self.env['stock.production.lot'].create({'product_id': self.laptop.id, 'company_id': self.env.company.id})
mo_form = Form(mo_laptop)
mo_form.qty_producing = 1
... | [
"def test_generate_with_putaway(self):\n nbre_of_lines = 4\n shelf_location = self.env['stock.location'].create({\n 'name': 'shelf1',\n 'usage': 'internal',\n 'location_id': self.location_dest.id,\n })\n\n # Checks a first time without putaway...\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure a kit is split in the corrects quantity_done by components in case of an immediate transfer. | def test_kit_immediate_transfer(self):
picking = self.env['stock.picking'].create({
'location_id': self.test_supplier.id,
'location_dest_id': self.warehouse_1.wh_input_stock_loc_id.id,
'partner_id': self.test_partner.id,
'picking_type_id': self.env.ref('stock.pick... | [
"def test_flow_tracked_only_finished(self):\n self.finished_product.tracking = \"serial\"\n self.comp1_sn.tracking = \"none\"\n nb_finished_product = 3\n # Create a receipt picking from the subcontractor\n picking_form = Form(self.env['stock.picking'])\n picking_form.pickin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure a kit is split in the corrects product_qty by components in case of a planned transfer. | def test_kit_planned_transfer(self):
picking = self.env['stock.picking'].create({
'location_id': self.test_supplier.id,
'location_dest_id': self.warehouse_1.wh_input_stock_loc_id.id,
'partner_id': self.test_partner.id,
'picking_type_id': self.env.ref('stock.pickin... | [
"def _check_overprocessed_subcontract_qty(self):\n overprocessed_moves = self.env['stock.move']\n for move in self:\n if not move.is_subcontract:\n continue\n # Extra quantity is allowed when components do not need to be register\n if not move._has_track... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ability that deals damage to the target | def ability_1(self,target):
damage = (self.get_strength()+2)
target.receive_damage(damage) | [
"def ability_3(self,target):\r\n damage = (self.get_dexterity()+self.get_strength())\r\n target.receive_damage(damage)",
"def deal_damage(self, target):\n if hasattr(target, \"hp\"):\n dmg = random.randrange(self.atk + 1)\n target.take_damage(dmg)\n return dmg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ability that deals damage to the target | def ability_3(self,target):
damage = (self.get_dexterity()+self.get_strength())
target.receive_damage(damage) | [
"def ability_1(self,target):\r\n damage = (self.get_strength()+2)\r\n target.receive_damage(damage)",
"def deal_damage(self, target):\n if hasattr(target, \"hp\"):\n dmg = random.randrange(self.atk + 1)\n target.take_damage(dmg)\n return dmg",
"def on_deal_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the path of the ocamlmerlin binary." | def merlin_bin():
user_settings = sublime.load_settings("Merlin.sublime-settings")
merlin_path = user_settings.get('ocamlmerlin_path')
if merlin_path:
return merlin_path
# For Mac OS X, add the path for homebrew
if "/usr/local/bin" not in os.environ['PATH'].split(os.pathsep):
os.en... | [
"def get_bin_dir():\n return os.path.abspath(os.path.join(get_root_dir(), 'bin/'))",
"def binpath (self):\n return self._basepath + '.bin'",
"def BinaryPath(name):\n return os.path.join(OLDISIM_DIR, BINARY_BASE, name)",
"def dir_bin():\n return abspath('bin')",
"def get_golem_path():\r\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the current view is an OCaml source code. | def is_ocaml(view):
ocaml = 'source.ocaml'
mlfi = 'source.mlfi'
location = view.sel()[0].begin()
return view.match_selector(location, ocaml) or view.match_selector(location, mlfi) | [
"def test_non_js_source(self):\n self.view.set_syntax_file(\"Packages/Python/Python.tmLanguage\")\n\n actual = is_js_source(self.view)\n\n self.assertFalse(actual)",
"def set_code_viewer_is_source(*args):\n return _ida_kernwin.set_code_viewer_is_source(*args)",
"def is_python():\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute the given function if we are in an OCaml source code only. | def only_ocaml(func):
@functools.wraps(func)
def wrapper(self, view, *args, **kwargs):
if is_ocaml(view):
return func(self, view, *args, **kwargs)
return wrapper | [
"def ast_only_test(func):\n\n def impl(*args, **kwargs):\n if os.environ.get(\"ENABLE_FALL_BACK\", \"False\") == \"False\":\n func(*args, **kwargs)\n\n return impl",
"def is_function(f) -> bool:\n return hasattr(f, '__code__')",
"def codetest(source, functionname, args):\n from pyp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a position returned by Merlin to a Sublime text point. Sublime uses character positions and starts each file at line 0. | def merlin_pos(view, pos):
return view.text_point(pos['line'] - 1, pos['col']) | [
"def from_position(tu, file, line, column):\r\n return conf.lib.clang_getLocation(tu, file, line, column)",
"def point2pos(self, point):\n row = self._vim.eval('byte2line({})'.format(point))\n col = self._vim.eval('{} - line2byte({})'.format(point, row))\n return (int(row), int(col))",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
.get_recommendation_display() will return the correct value of the recommendation choice | def test_recommendation_value(self):
john_starks = Athlete(first_name="John", last_name="Starks", sport="NBA", recommendation="a")
self.assertEqual(john_starks.get_recommendation_display(), "Hire Joe IMMEDIATELY!") | [
"def display_recommendation(self, n=5):\n self.n = n # update the number of recommendations to display\n if len(self.recomm) == 0:\n print(\"Sorry, there is no matching recommendations.\")\n elif self.n < len(self.recomm): # display only the top n from the recommendation list\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. | def on_exchange_declareok(self, _unused_frame):
self._channel_ctrl.queue_declare(
'',
exclusive=True,
auto_delete=True,
callback=self.on_queue_declareok
) | [
"def on_exchange_declareok(self, unused_frame):\r\n LOGGER.info('Exchange declared')\r\n self.setup_queue(self.QUEUE)",
"def declare(self):\r\n self.backend.exchange_declare(exchange=self.exchange,\r\n type=self.exchange_type,\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get next report ID or False if not available | def next_id(self):
try:
return Report.objects.filter(id__gt=self.id).order_by("id").first().id
except Exception:
return False | [
"def get_next_report_id(self):\n max_report_id = 0\n for report in self.bug_reports:\n if report.report_id > max_report_id:\n max_report_id = report.report_id\n return max_report_id+1",
"def nextId(self):\r\n \r\n nextId = -1\r\n if self._wizard.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get previous report ID or False if not available | def previous_id(self):
try:
return Report.objects.filter(id__lt=self.id).order_by("-id").first().id
except Exception:
return False | [
"def next_id(self):\n try:\n return Report.objects.filter(id__gt=self.id).order_by(\"id\").first().id\n except Exception:\n return False",
"def get_report_id(self, reports):\n matching_reports = [\n report for report in reports if report.get('title') in [\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs HttpRequest from string containing an entire HTTP request | def deserialize(cls, data: bytes) -> HttpRequest:
try:
raw = data.decode("utf-8")
raw_headers, raw_body = raw.split("\r\n\r\n")
header_lines = raw_headers.split("\r\n")
method, path, protocol = header_lines[0].split()
headers = HttpRequest._parse_heade... | [
"def request_from_text(text):\n lines = text.splitlines()\n match = re.search('^([a-z]+) (.*) (http/[0-9]\\.[0-9])$', lines[0], re.I)\n method, path, version = match.groups()\n headers = {}\n for idx, line in enumerate(lines[1:], start=1):\n if not line:\n break\n hdr, val = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses headers to a dictionary from a list of strings | def _parse_headers(raw_headers: List[str]) -> Dict[str, str]:
headers: Dict[str, str] = {}
for header in raw_headers:
name = header[: header.find(":")].strip()
value = header[header.find(":") + 1 :].strip()
headers[name.lower()] = value
return headers | [
"def process_headers(self, listed_data):\n\t\treturn { val.rstrip().split(\": \")[0]: val.rstrip().split(\": \")[1] for val in listed_data }",
"def _parse_headers(headers):\n try:\n return dict(header.split(\":\") for header in headers)\n except:\n raise ValueError(\"Invalid he... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reemplaza la(s) ocurrencia(s) de tag en el archivo por nstr | def rep(self,tag,nstr):
tmp = []
for line in self.content:
if tag in line:
tmp.append(line.replace(tag,nstr))
else:
tmp.append(line)
self.content = tmp | [
"def addTagToFile(self, fi, tag):",
"def getTagsToFile(self, _file):",
"def __connectTagsToFile(self, tags, fid):",
"def count_tags(filename):\n tags = {}\n for element in get_element(osm_file, verify_tags = False):\n if element.tag not in tags.keys():\n tags[element.tag] = 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Salva los cambios al archivo especificado en newfile, o hace una copia del archivo original (filename+'~') y salva el contenido en "filename" | def saveFile(self,newfile=None):
if newfile == None:
shutil.move(self.filename,self.filename+'~')
self.handler = open(self.filename,'w')
else:
self.handler = open(newfile,'w')
self.handler.writelines(self.content)
self.handler.close() | [
"def overwrite_original(self) -> None:\n self._write_save_file(self._file_path, \"wb\")",
"def write_output_file(updated_file, file_path):\n orig_file = file_path + \".orig\"\n # remove an existion .orig file\n if os.path.isfile(orig_file):\n os.remove(orig_file)\n # rename the current f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
``summary'' is a systemgenerated summary. ``references'' is a list of humanmade reference summaries | def score_summary(self, summary, references, summary_id='A'):
try:
self._write_config(references, Doc(summary_id, summary))
output = self._run_rouge()
output = output.decode("utf-8")
return self._parse_output(output)
except CalledProcessError as e:
... | [
"def summary(self, summary):\n self._summary = summary",
"def summary(self, summary):\n\n self._summary = summary",
"def print_summary_and_genomes(summary, genome):\n for sample in summary:\n for ref in summary[sample]:\n if ref == \"metadata\":\n continue\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display unpublished Draft Entries | def drafts():
query = Entry.drafts().order_by(Entry.last_mod_date.desc())
return object_list('index.html', query) | [
"def drafts():\n pass",
"def published(self):\n return self.get_query_set().filter(\n status__in=BloggingSettings.PUBLISHED_ENTRY_STATES\n ).exclude(\n start_date__gt=datetime.now()\n )",
"def draft(self):\n action_unpublished.send(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create new blog Entry | def create():
if request.method == 'POST':
if request.form.get('title') and request.form.get('content'):
entry = Entry.create(
title = request.form.get('title'),
content = request.form.get('content'),
published = request.form.get('published') or Fa... | [
"def createNewBlogEntry(self): #$NON-NLS-1$\r\n atomdoc = self._createNewEntryDocument()\r\n self._initNewEntryDocument(atomdoc)\r\n return ZAtomNewBlogEntry(atomdoc)",
"def create(self, request):\n attrs = self.flatten_dict(request.POST)\n\n if self.exists(**attrs):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
a function converting csv output files from operational_sep_quantities to json files for observations | def obs_csv2json(input_file,output_file,example_path,instrument):
obs_path = Path(cfg.obs_path)
with open(example_path,'r') as e:
example = js.load(e)
#deleting unused categories
del(example['sep_forecast_submission']['forecasts'])
del(example['sep_forecast_submission']['... | [
"def parse_csv_data_to_json(input_file, output_file):\n with open(input_file) as f:\n # open the output file for writing\n with open(output_file, 'w') as myfile:\n\n # read in the csv\n input_content = csv.reader(f, delimiter=',')\n\n # skip the header and store it ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
choose the correct instrument to use for observations for a given date range. inputs must be date objects from the datetime module. used if there is no information about which instrument was primary. | def choose_inst(given_start_date,given_end_date): #INPUTS MUST BE DATE OBJECTS
inst_start_dates=[]
inst_end_dates=[]
good_instruments = []
good_end_dates = []
bad_inst = []
#extracting dates where instruments are active from csv file
inst_dates = pd.read_csv(ref_path / 'instrument... | [
"def choose_prime_inst(given_start_date,given_end_date):\r\n\r\n #extracting primary dates where instruments are active from csv file\r\n inst_prime_dates = pd.read_csv(ref_path / 'GOES_primary_assignments.csv', header=3)\r\n\r\n #figuring out which instrument is primary for given start date\r\n for d i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
choose the correct instrument to use for observations for a given date range based on the primary instrument for that time period. inputs must be date objects from the datetime module. | def choose_prime_inst(given_start_date,given_end_date):
#extracting primary dates where instruments are active from csv file
inst_prime_dates = pd.read_csv(ref_path / 'GOES_primary_assignments.csv', header=3)
#figuring out which instrument is primary for given start date
for d in range(len(inst_... | [
"def choose_inst(given_start_date,given_end_date): #INPUTS MUST BE DATE OBJECTS\r\n\r\n inst_start_dates=[]\r\n inst_end_dates=[]\r\n good_instruments = []\r\n good_end_dates = []\r\n bad_inst = []\r\n\r\n #extracting dates where instruments are active from csv file\r\n inst_dates = pd.read_csv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
will create JSON output files if there are two events (for each threshold) in one time window. Ie, if there are two >10MeV >10pfu events as well as two >100MeV >1pfu events, will create files for all four events, but if there are three >100MeV >1pfu events, will only generate JSON files for the first two. Second events... | def two_in_one(obs_file,et,subevent):
#in this function, the "original time window" talked about in the comments
#refers to the start and end times that were input to create the file obs_file,
#which will likely have been created using the database_extraction function
#opening first outp... | [
"def multi_event(st,et,instrument_chosen,subevent):\r\n print('checking for multiple events within given time window')\r\n \r\n #creating file for time window with first events for all thresholds\r\n out_name = Path(cfg.obs_path) / database_extraction(st,et,instrument_chosen,subevent)\r\n\r\n #creati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
all events in one time window (not just two) used if there is more than one event occurring within a short time period. will generate an output file for every event that occurs within a given time window not to be confused with many_events, which generates output given multiple time windows. Can create files for up to ... | def multi_event(st,et,instrument_chosen,subevent):
print('checking for multiple events within given time window')
#creating file for time window with first events for all thresholds
out_name = Path(cfg.obs_path) / database_extraction(st,et,instrument_chosen,subevent)
#creating files for all ... | [
"def write_events(events: list, calendar):\n for event in events:\n location = event[\"location\"]\n vevent_string = str()\n vevent_string += 'BEGIN:VEVENT\\n'\n vevent_string += 'DTSTAMP:20210904T194914Z\\n' # here we have to add a custom date\n vevent_string += f'DTSTART;TZI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given lists of peak fluxes for protons >10 MeV and >100 MeV, creates a boolean for whether or not each event is a subevent (doesn't cross a threshold) | def gen_subevent_bools(p_10,p_100):
#list of subevent booleans
subevent_bools = []
#extracting 10 MeV peak flux if it exists
for j in range(len(p_10)):
try:
p10 = float(p_10[j])
except ValueError:
p10 = 'nan'
#extracting 100 MeV pe... | [
"def filter_with_peaks(\n self,\n peak_list: list,\n both_peak_support: bool = False\n ) -> bool:\n\n start_time = time.time()\n\n num_peaks = len(peak_list)\n min_peak_value = peak_list[-1][PEAK_MAX_VALUE_INDEX]\n\n log.info(f\"Filtering {self.sample_name} {self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes in lists of start times and end times to create a list of time windows, and a list of whether or not an event is a subevent, and uses those lists to run functions that extract data from the GOES database. Each list must have the same length, and indices of lists must correspond (ie start_time[j] has an end time o... | def many_events(start_time,end_time,subevent_bools):
#running through for each event
for j in range(len(start_time)):
#start, end, and subevent bool for this event
st = start_time[j]
et = end_time[j]
subevent = bool(subevent_bools[j])
#che... | [
"def multi_event(st,et,instrument_chosen,subevent):\r\n print('checking for multiple events within given time window')\r\n \r\n #creating file for time window with first events for all thresholds\r\n out_name = Path(cfg.obs_path) / database_extraction(st,et,instrument_chosen,subevent)\r\n\r\n #creati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returning the sync mode | def get_sync_mode():
return sync_mode | [
"def isSync(self):\n return True",
"def synchronize_system_mode(self):\n\n return self._synchronize_system_mode",
"def sync(self):\n return self.query('C' + self.channel[-1] + ':SYNC?')",
"def lock_mode(self):\n return self._lock_mode",
"def is_sync(self):\n return self.co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checking the sync_mode based on the given configuration | def check_sync_mode():
global sync_mode
_description = ''
_modes = {
SyncMode.RECEIVER: '(REMOTE ➔ LOCAL)',
SyncMode.SENDER: '(LOCAL ➔ REMOTE)',
SyncMode.PROXY: '(REMOTE ➔ LOCAL ➔ REMOTE)',
SyncMode.DUMP_LOCAL: '(LOCAL, ONLY EXPORT)',
SyncMode.DUMP_REMOTE: '(REMOTE, ... | [
"def get_sync_mode():\n return sync_mode",
"def __check_mode(self):\n self.mode[\"auto_mode\"] = self.communications.get_mode()",
"def check_config_mode(self):\n return False",
"def is_sync(self):\n return self.command == Command.sync",
"def validate_sync_gateway_mode(mode):\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if given client is remote client | def is_remote(client):
if client == Client.ORIGIN:
return is_origin_remote()
elif client == Client.TARGET:
return is_target_remote()
elif client == Client.LOCAL:
return False
else:
return False | [
"def is_remote(self):\n pass",
"def isClientHost(self):\n return self.serverThread is not None",
"def is_local_client(self):\n return self.msg.is_local_client",
"def is_remote(self):\n return False",
"def allowed_client(self):\n ip = self.client_address[0]\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if target is remote client | def is_target_remote():
return sync_mode in (SyncMode.SENDER, SyncMode.PROXY, SyncMode.DUMP_REMOTE,
SyncMode.IMPORT_REMOTE, SyncMode.SYNC_REMOTE) | [
"def is_remote(client):\n if client == Client.ORIGIN:\n return is_origin_remote()\n elif client == Client.TARGET:\n return is_target_remote()\n elif client == Client.LOCAL:\n return False\n else:\n return False",
"def is_remote(self):\n pass",
"def is_remote(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if origin is remote client | def is_origin_remote():
return sync_mode in (SyncMode.RECEIVER, SyncMode.PROXY, SyncMode.DUMP_REMOTE,
SyncMode.IMPORT_REMOTE, SyncMode.SYNC_REMOTE) | [
"def is_remote(self):\n pass",
"def is_remote(client):\n if client == Client.ORIGIN:\n return is_origin_remote()\n elif client == Client.TARGET:\n return is_target_remote()\n elif client == Client.LOCAL:\n return False\n else:\n return False",
"def is_remote(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if sync mode is import | def is_import():
return sync_mode in (SyncMode.IMPORT_LOCAL, SyncMode.IMPORT_REMOTE) | [
"def check_sync_mode():\n global sync_mode\n _description = ''\n\n _modes = {\n SyncMode.RECEIVER: '(REMOTE ➔ LOCAL)',\n SyncMode.SENDER: '(LOCAL ➔ REMOTE)',\n SyncMode.PROXY: '(REMOTE ➔ LOCAL ➔ REMOTE)',\n SyncMode.DUMP_LOCAL: '(LOCAL, ONLY EXPORT)',\n SyncMode.DUMP_REMO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert valid court order. | def test_court_orders(session, test_status, expected_code, expected_msg):
business = factory_business('BC1234567')
filing = copy.deepcopy(COURT_ORDER_FILING_TEMPLATE)
del filing['filing']['courtOrder']['fileKey']
if test_status == 'FAIL':
del filing['filing']['courtOrder']['orderDetails']
... | [
"def test_validate_invalid_court_orders(invalid_court_order):\n registration_json = copy.deepcopy(REGISTRATION)\n registration_json['courtOrder'] = invalid_court_order\n legal_filing = {'registration': registration_json}\n\n is_valid, errors = validate(legal_filing, 'registration')\n\n if errors:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find a text label for an axis describing a provided CSV column. | def get_label(column):
for key, label in column_to_label.items():
if key in column:
return label | [
"def _label(self, column):\n # XXX\n return column",
"def getAxisLabel(self, dim=0):\n return self.__axis_labels__[dim]",
"def label(self, row: Dict[str, str]) -> str:\n\n return row['Annotation']",
"def getColLabel(self, i=':'):\n if i == ':':\n return self.colL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all possible values of a column in the pandas.DataFram list | def dfs_all_values(dfs, column):
values = []
# loop over all (pandas.DataFrame, str) pairs
for df in dfs:
values.extend(df[column].tolist())
# set() removes duplicates
# sorted() converts Set to List and sort the elements
return sorted(set(values)) | [
"def get_possible_matches(df, **columns):\n\n for col_name, col_value in columns.items():\n df = df.loc[df[col_name] == col_value]\n\n return df",
"def get_values(self, col) :\n\n if col not in self.cols :\n raise Exception('Column %s not in data' % col)\n\n select_sql = 'SEL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw multiple lines y(x) using data from the dfs list on the ax subplot. | def draw_plot(ax, dfs, legend, x, y, xscale, yaxis_max):
xticks = dfs_all_values(dfs, x)
# loop over all pandas.DataFrame objects
for df in dfs:
# setting the x-column as an index is required to draw the y-column
# as a function of x argument
df = df.set_index(x)
# plot line ... | [
"def plot(x, y, *dfs):\n ax = None\n for df in dfs:\n ax = df[[x, y]].set_index(x).plot(kind='line', ylim=(0, None), xlim=(0, None), ax=ax)",
"def update_plot(self,ax):\n for i,line in enumerate(self.lines):\n line.set_ydata(self.data[i].f)\n for line in self.lines: \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw a table of all data used to chart y(x) | def draw_table(ax, dfs, legend, x, y):
col_labels = dfs_all_values(dfs, x)
column_legend = []
cell_text = []
# loop over all pandas.DataFrame objects
for df in dfs:
# to allow query y(x) easily
df = df.set_index(x)
df_row = df[y]
# build a row with filled blanks '-'
... | [
"def table(self):\n\n param=self.x_param\n\n device=self.device\n\n base_params=device.get_params()\n\n data_tot=DataFrame()\n\n for i in range(len(param)):\n\n print_index=1\n\n for name in param.names:\n\n device._set_params(param(i))\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Going to a nonchunkadmin URL should be ok, and should also put the `_data_changed` parameter onto the URL. | def test_to_other_url(self):
user = User(username='test', is_staff=True, is_superuser=True,
is_active=True)
user.set_password('test')
user.full_clean()
user.save()
request = RequestFactory().get('/')
response_302 = HttpResponseRedirect(redirect_to='/ad... | [
"def test_return_admin_url(self):\n\t\tself.assertEqual(admin_handler.AdminHandler().return_admin_url(''), 'http://sport1_admin.app.endstand.de')\n\t\tself.assertEqual(admin_handler.AdminHandler().return_admin_url('ergebnisDienst'), 'http://master.dynamic.ergebnis-dienst.de')",
"def test_data_admin_page(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If `_autoclose` is in the URL, that + `_data_changed` should propagate to the next redirect URL for the purposes of our adminlinks JS. | def test_autoclose_chunkadmin(self):
user = User(username='test', is_staff=True, is_superuser=True,
is_active=True)
user.set_password('test')
user.full_clean()
user.save()
admin_instance = get_modeladmin(Iframe)
self.assertIsInstance(admin_instance, Re... | [
"def response_change(self, request, obj):\r\n \r\n # in these cases, the redirect is good\r\n if list(set(request.POST.keys()) & set([\"_addanother\", \"_saveasnew\", \"_continue\"])):\r\n return super(ServeeModelAdmin, self).response_change(request, obj)\r\n \r\n # we ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if continue editing is hit, it should go back to the parent URL, I think? | def test_continue_editing_parent_object(self):
user = User(username='test', is_staff=True, is_superuser=True,
is_active=True)
user.set_password('test')
user.full_clean()
user.save()
admin_instance = get_modeladmin(Iframe)
self.assertIsInstance(admin_in... | [
"def view_edit_no_id():\n return redirect(url_for('home.homepage'))",
"def test_redirect_from_edit_exists(self):\n response = self.client.get('/edit/', follow=True)\n self.assertEqual(response.status_code, 200)",
"def response_post_save_change(self, request, obj):\n return HttpResponseRe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate immediate (different by one mismatch) neighbours of the given genome pattern | def _generate_immediate_neighbours(pattern: str) -> list:
generated = []
for i in range(len(pattern)):
if pattern[i] == 'A':
generated.extend([pattern[:i] + c + pattern[i + 1:] for c in LIST_A])
elif pattern[i] == 'C':
generated.extend([pattern[:i] + c + pattern[i + 1:] f... | [
"def generate_neighbors_8_connect(current_cell, array_width):\n x_coordinate = current_cell / array_width\n y_coordinate = current_cell % array_width\n\n if current_cell == 0:\n west_neighbor = -1\n north_neighbor = -1\n north_west_neighbor = -1\n north_east_neighbor = -1\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether the given card matches this card | def is_match(self, card):
return self.suit == card.suit or self.value == card.value | [
"def _validate_card_match(self, chosen_card, active_card, active_suit):\n\t\treturn chosen_card.is_match(active_card) or chosen_card.suit == active_suit",
"def equals(self, card):\n ERROR = \"card '{}' is not a Card type\".format(card)\n assert isinstance(card, Card), ERROR\n\n if (self.getRa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensures that chosen_card is an acceptable match, given the active_card and active_suit | def _validate_card_match(self, chosen_card, active_card, active_suit):
return chosen_card.is_match(active_card) or chosen_card.suit == active_suit | [
"def set_chosen_card(self, allowed_cards, chosen_card):\n if self.action is not None:\n if self.action in allowed_cards:\n logger.info(f\"Successfully chose the card: {self.action}\")\n chosen_card = self.action\n else:\n logger.error(f\"{sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If test_mode is True, an image of `screen` is saved | def save_screen(screen):
if not video_mode: # Don't record video
return False
# Make global variables writeable
global current_frame
global path_checked
frames_directory = os.path.dirname(
os.path.dirname(
os.path.realpath(__file__))) + "\\frames\\"
if not path_check... | [
"def save_snapshot(mode='project'):\n p = viewport.get_model_panel()\n cam_name = cmds.modelEditor(p, query=True, camera=True).replace(':', '_')\n curr_file_name = cmds.file(query=True, sceneName=True, shortName=True)\n nice_file_name = '{0:%Y%m%d_%H%M%S}_{1:s}_{2:s}'.format(datetime.datetime.now(),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> find_good_recipes(9, 10) '5158916779' >>> find_good_recipes(5, 10) '0124515891' >>> find_good_recipes(18, 10) '9251071085' >>> find_good_recipes(2018, 10) '5941429882' | def find_good_recipes(improvement_num, count):
recipes = [3, 7]
elf1 = 0
elf2 = 1
while len(recipes) <= improvement_num + count:
elf1_value = recipes[elf1]
elf2_value = recipes[elf2]
recipe_sum = elf1_value + elf2_value
if recipe_sum > 9:
recipe_string = f... | [
"def test_get_similar_recipes(self):\n pass",
"def test_get_random_recipes(self):\n pass",
"def search_recipe(ingredients):\n\n params = '+'.join(ingredients.split())\n url_search = SEARCH_URL.format(params)\n response = req.get(url_search)\n\n return response.content",
"def extract_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |