query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Takes a DOI json string and returns a string of authors in Chicago style. | def make_citation_authors(res):
if "author" in res.keys():
first_author = res['author'][0]['family'] + ", " + res['author'][0]['given']
last_author = res['author'][-1]['given'] + " " + res['author'][-1]['family']
middle_authors = ", ".join(" ".join([x['given'], x['family']]) for x in res['author'][1:-1])
... | [
"def read_authors(filename):\n with Path(filename).open() as file:\n info = json.load(file)\n authors = []\n for author in info['creators']:\n name = ' '.join(author['name'].split(',')[::-1]).strip()\n authors.append(name)\n return ', '.join(authors)",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a DOI query and returns a string citation key. | def make_citation_key(res):
year = str(make_year(res))
try:
last_names = [x['family'] for x in res['author']]
except KeyError as e:
last_names = ["Unknown"]
if len(last_names) >= 3:
key = last_names[0].capitalize() + "ETAL" + year
else:
key = "".join(last_names) + year
return clean_txt(key... | [
"def getDOIFromCitation(citation):\n try:\n if \".org/\" in citation:\n DOI = citation.split(\".org/\")[1]\n elif citationContainsDOI(citation):\n DOI = citation.split(\"doi:\")[1]\n DOI = DOI.replace(\"]\", \"\")\n elif citation == \"unknown\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
UK Residential Building Classification using NISMOD API | def building_classification(user_settings, LAD_Code_to_be_processed, year):
# API call - get buildings
buildingPolys, buildingAttributes, i = get_buildings(user_settings, year, LAD_Code_to_be_processed)
print(i, " buildings loaded successfully")
print("Pre-processing OAs...")
print("")
... | [
"def main():\n # Still trying to work through understanding yang models\n # url string to issue GET request\n #url = \"https://{h}/restconf/data/ietf-interfaces:interfaces\".format(h=HOST)\n #url = \"https://{h}/restconf/data/Cisco-IOS-XE-native:native/interface?\".format(h=HOST)\n # running config\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
"Calculate communities using the louvain algorithm and assign them as property to the graphs node. if two graphs are given, also assign one graph's communities to the other's. | def assign_louvain_communities(
reddit_graph: nx.Graph,
wiki_graph: nx.Graph = None,
reddit_edge_weight: str = "count",
others_threshold: int = 2,
louvain_resolution_reddit: float = 1,
) -> Union[nx.Graph, Tuple[nx.Graph, nx.Graph]]:
reddit_dendrogram = community.generate_dendrogram(
red... | [
"def assign_communities(graph):\n communities = nx.algorithms.community\\\n .greedy_modularity_communities(nx.Graph(graph))\n for node in graph.nodes:\n graph.nodes[node]['community'] = [i for i,c in enumerate(communities)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a graph and wikipedia data, assign a new attribute to the nodes that represent the root category of that node on wikipedia. | def assign_root_categories(
graph: nx.Graph,
wiki_data: Dict[str, List],
mapping: Dict[str, List[str]],
name: str,
):
inverse_mapping = {}
for category, subcategories in mapping.items():
for subcategory in subcategories:
inverse_mapping[subcategory.lower()] = category.lower()... | [
"def add_root_categories():\n\n \"\"\"\n Define weight for each root category.\n we use this number to set how many products we will scrape \n from each root category's sub categories in scrape_all() function.\n \"\"\"\n weight_list = [1, \n 0.5,\n 0.05,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch content from url from internet. | def fetch(url):
content = requests.get(url).text
if "Error" in content:
raise ValueError(f"Cannot read from: {url}")
return content | [
"def FetchUrlContent(url):\n content = memcache.get(url)\n if content:\n return content\n\n request = urlfetch.fetch(url)\n\n if request.status_code == 200:\n content = request.content\n memcache.add(url, content, 60 * 60)\n return content\n\n raise LookupError('Unable to fetch URL. Response code: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return text selected by current text cursor | def get_selected_text(self):
return self.selectedText() | [
"def textUnderCursor(self):\n tc = self.textCursor()\n tc.select(QtGui.QTextCursor.WordUnderCursor)\n return tc.selectedText()",
"def capture_highlighted_text(self, event):\n highlighted_by_cursor = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)\n self.text_selected.set(highlighted_by... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return address label text | def get_label(self):
return _("Address:") | [
"def address_title(self):\n\t\tlocator = self._locator.ADDRESS_TITLE\n\t\treturn self.get_text_property(locator)",
"def addr_text(self):\n if isinstance(self.addr, str):\n return '.%s' % self.addr\n elif isinstance(self.addr, int):\n return '%s[%s]' % (self.name, self.addr)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Go to home page | def go_home(self):
if self.home_url is not None:
self.set_url(self.home_url) | [
"def goto_home(self):\n self.press_home()\n self.press_home()",
"def go_home(self):\n self.screen.home_screen()",
"def _home(self, op, context):\n self.page = \"HOME\"\n return {'FINISHED'}",
"def homepage():\n return redirect('index.html')",
"def goHome():\n\t#Go to po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert text address into QUrl object | def text_to_url(self, text):
return QUrl(text) | [
"def url(text):\n return (\n E.a(\"link\", href=text, target='_blank')\n if text.startswith('http')\n else text\n )",
"def extract_real_link(self, text):\n if text.startswith('https://www.google.com/url?'):\n return parse_qs(urlparse(text).query)['url'][0]\n\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load URL from combo box first item | def url_combo_activated(self, valid):
text = to_text_string(self.url_combo.currentText())
self.go_to(self.text_to_url(text)) | [
"def url_changed(self, url):\r\n self.url_combo.add_text(self.url_to_text(url))",
"def on_urlCombo_currentIndexChanged(self, text):\n url = self.__normalizeUrl(text)\n if url != self.url:\n self.url = url\n self.repoTree.clear()\n self.__listRepo(url)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displayed URL has changed > updating URL combo box | def url_changed(self, url):
self.url_combo.add_text(self.url_to_text(url)) | [
"def url_combo_activated(self, valid):\r\n text = to_text_string(self.url_combo.currentText())\r\n self.go_to(self.text_to_url(text))",
"def on_urlCombo_currentIndexChanged(self, text):\n url = self.__normalizeUrl(text)\n if url != self.url:\n self.url = url\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test AudioWithTargetDataset when the input manifest has a list of audio files in the target key. | def test_audio_to_target_dataset_with_target_list(self):
# Data setup
random_seed = 42
sample_rate = 16000
num_examples = 25
data_num_channels = {
'input_signal': 4,
'target_signal': 2,
}
data_min_duration = 2.0
data_max_duration = ... | [
"def test_audio_to_target_dataset_for_inference(self):\n # Data setup\n random_seed = 42\n sample_rate = 16000\n num_examples = 25\n data_num_channels = {\n 'input_signal': 4,\n }\n data_min_duration = 2.0\n data_max_duration = 8.0\n data_key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test AudioWithTargetDataset when target_key is not set, i.e., it is `None`. This is the case, e.g., when running inference, and a target is not available. | def test_audio_to_target_dataset_for_inference(self):
# Data setup
random_seed = 42
sample_rate = 16000
num_examples = 25
data_num_channels = {
'input_signal': 4,
}
data_min_duration = 2.0
data_max_duration = 8.0
data_key = {
... | [
"def test_audio_to_target_dataset_with_target_list(self):\n # Data setup\n random_seed = 42\n sample_rate = 16000\n num_examples = 25\n data_num_channels = {\n 'input_signal': 4,\n 'target_signal': 2,\n }\n data_min_duration = 2.0\n data_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test AudioWithTargetWithReferenceDataset in different configurations. 1) reference synchronized with input and target 2) reference not synchronized | def test_audio_to_target_with_reference_dataset(self):
# Data setup
random_seed = 42
sample_rate = 16000
num_examples = 25
data_num_channels = {
'input_signal': 4,
'target_signal': 2,
'reference_signal': 1,
}
data_min_duration =... | [
"def test_audio_to_target_dataset_with_target_list(self):\n # Data setup\n random_seed = 42\n sample_rate = 16000\n num_examples = 25\n data_num_channels = {\n 'input_signal': 4,\n 'target_signal': 2,\n }\n data_min_duration = 2.0\n data_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test caching of manifest and audio files. | def test_cache_datastore_manifests(self, cache_audio: bool):
# Data setup
random_seed = 42
sample_rate = 16000
num_examples = 10
num_manifests = 2
data_duration = 1.0
# Generate random signals
_rng = np.random.default_rng(seed=random_seed)
# Inpu... | [
"def test_cache_file_operations(self):\n\n print(\"Downloading with overwrite=True\")\n qnm.cached.download_data(overwrite=True)\n print(\"Clearing disk cache but not tarball\")\n qnm.cached._clear_disk_cache(delete_tarball=False)\n print(\"Decompressing tarball\")\n qnm.ca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Combine Zebra, ospfd and bpgd configs into an integrated FRR config file | def integrate_frr_config(
device, output_dir: str, zebra_config: str, ospfd_config: str, bgpd_config: str
) -> None:
filename = os.path.join(output_dir, f"{device.hostname}_frr.conf")
config = "\n".join([zebra_config, ospfd_config, bgpd_config])
write_config_to_file(filename=filename, config=config) | [
"def WriteConfigs(self):\n print 'writeconfigs!!'\n ip4configs = {}\n ip6configs = {}\n for i in range(1, 5):\n ip4configs[i] = []\n ip6configs[i] = []\n dmz4 = []\n dmz6 = ''\n for (idx, mapping) in self.PortMappingList.iteritems():\n precedence = mapping.Precedence()\n ip4... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check for required and recommended dependencies. | def check_dependencies():
required_found = True
recommended_found = True
print 'Checking dependencies ...\n'
print 'Required dependencies:'
try:
import Image
assert Image.VERSION >= '1.1.5'
print ' Python Imaging Library ....... OK'
except ImportError:
print ' ... | [
"def checkRequiredDependencies(self):\n \n # skip dependency check for downloading only\n if( self.downloadOnly ):\n return\n\n # hard dependencies\n for req in self.reqmodules:\n if( self.parent.module(req) == None ):\n # check if there is an auto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for the installed gnome version. | def check_gnome_version():
(stdin, stdout) = os.popen2("gnome-session --version")
version = stdout.read().split()[1]
if version[0] == '3':
return "gnome3"
elif version[0] == '2':
return "gnome2"
else:
return None | [
"def have_updated_gnupg():\n gnupg_version = find_installed_version('gnupg')\n return Version(gnupg_version) >= Version('2.1')",
"def check_glibver(reqver_text):\n\treturn check_pkgcfg_ver(reqver_text, 'glib-2.0')",
"def check_gn(default=\"gn\"):\n executable = os.getenv(\"GN\", default)\n return ch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor layout type of the window layout (string) editVisibilities list of flags giving the visibilities of the various parts for the 'edit' view profile (list of boolean) debugVisibilities list of flags giving the visibilities of the various parts for the 'debug' view profile (list of boolean) parent parent widget... | def __init__(self, layout, editVisibilities, debugVisibilities,
parent=None):
super(ViewProfileDialog, self).__init__(parent)
self.__layout = layout
if self.__layout == "Toolboxes":
self.ui = Ui_ViewProfileToolboxesDialog()
elif self.__layout == "Sid... | [
"def create_layout( self ):\n\n # highlight all of our widgets so we can debug layouts.\n # XXX: debugging support.\n self.setStyleSheet( \"border: 1px solid black\" )\n\n editing_layout = QGridLayout()\n editing_layout.addWidget( QLabel( \"Art Record ID:\" ),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public method to retrieve the visibilities configuration. tuple of two lists giving the visibilities of the various parts (two lists of boolean) | def getVisibilities(self):
if self.__layout in ["Toolboxes", "Sidebars"]:
return (
# edit profile
[
self.ui.epltCheckBox.isChecked(),
self.ui.ephtCheckBox.isChecked(),
self.ui.eprtCheckBox.isChecked(),
... | [
"def visibilities(self):\n return self._visibilities",
"def get_visibilities(loc):\r\n if loc == \"1\":\r\n # SU\r\n r = requests.get(\"http://146.232.222.105/api/v1/imaging/vis\")\r\n else:\r\n # NZ\r\n r = requests.get(\"https://tart.elec.ac.nz/signal/api/v1/imaging/vis\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Launch training of the model with a set of hyperparameters in parent_dir/job_name | def launch_training_job(parent_dir, data_dir, job_name, params):
# Create a new folder in parent_dir with unique_name "job_name"
model_dir = os.path.join(parent_dir, job_name)
if not os.path.exists(model_dir):
os.makedirs(model_dir)
# Write parameters in json file
json_path = os.path.join(m... | [
"def launch_training_job(parent_dir, job_name, params):\r\n # Create a new folder in parent_dir with unique_name \"job_name\"\r\n model_dir = os.path.join(parent_dir, job_name)\r\n if not os.path.exists(model_dir):\r\n os.makedirs(model_dir)\r\n\r\n # Write parameters in json file\r\n json_pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select specified Credential using Credential Name | def selectCredential(self, credentialName):
try:
utility.execLog("Reading Credentials Table...")
tableName = self.CredentialsObjects('credentialsTable')
getRows = "//table[@id='%s']//tbody//tr" % tableName
# Get No. of Rows i.e. No. of Credentials defined
... | [
"def find_by_user_name(cls,name):\n\n for user_name in cls.credential_list:\n if Credential.user_name == name:\n return credential",
"def fetch_credential(self, credential=None, profile=None):\n pass",
"def find_credential(account_Name):\n return Credentials.search_cre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a mock for the Popen class that allows easy testing of device methods that use Popen. | def generateStandardMock(monkeypatch, return_value_output, return_value_error, return_code, type="gpt"):
mock_popen = mock.MagicMock()
mock_popen.communicate.return_value = (return_value_output, return_value_error)
mock_popen.returncode = return_code
def popen_constructor(*args, **kargs):
return... | [
"def mock_gitlab_subprocess(monkeypatch):\n mock_subprocess = mock.Mock()\n monkeypatch.setattr(\"libgitlab.subprocess\", mock_subprocess)\n return mock_subprocess",
"def setUp(self):\n # Mocking popen\n self.popen_patcher = patch(\"pyconnectomist.wrappers.subprocess.Popen\")\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Crop video frames generated by faceit. These contain a topbottom display of both the original and the fake. We only want the fake, which is on the bottom. frame A frame of an image, represented as a numpy 2D array | def crop_frame(frame):
(h,w,c) = frame.shape
return frame[int(h/2):h, 0:w] | [
"def crop_image(self, frame):\n (height, width, depth) = frame.shape\n if self.FLIP:\n # frame = frame[:160, width // 2 - int(Algo.FRAME_SIZE[1]*3/8): width // 2 + int(Algo.FRAME_SIZE[1]*3/8)]\n cropped = frame[:160, width // 2 - 240: width // 2 + 240]\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
frame_path Path of frames extracted from video out_path Destination directory face_path Path to a single image of a face. The face acts as a filter in the extraction process | def extract_faces(frame_path, out_path, face_path, processes=1):
if os.path.exists(out_path):
msg = '[extract_faces] Skipping extraction since faces already exist at {}'
print(msg.format(out_path))
return
from faceoff.faceswap_api import FaceSwapInterface
os.makedirs(out_path)
print('[extract_face... | [
"def write_face_samples(model, output_path, invid):\n \n if not os.path.isdir(output_path) :\n os.mkdir(output_path)\n \n video = mmcv.VideoReader(invid)\n for frame_ix, frame in enumerate(video):\n frame_name = f\"{output_path}webcam_{frame_ix}_0.jpg\"\n if os.path.isfile(frame_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send emails to given addresses with author and title. | def send_emails(emails, author, title):
subject = 'New post by %s' % author.capitalize()
message = '%s wrote a new post with the title: %s' % (author.capitalize(), title)
print('Sending emails to ', emails)
send_mails_count = send_mail(
subject=subject,
message=message,
from_emai... | [
"def send_publishers_authors_email(subject, template_name, context=None):\n\n if context is None:\n context = {}\n\n qry = Q(groups__name='Publishers') | Q(groups__name='Editors')\n\n emails = auth_models.User.objects.filter(qry, is_active=True).distinct().values('email')\n to = [e['email'] for e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new FileSystemStorageManager. | def __init__(
self, storage_path: str, block_size: Tuple[int, int, int], **kwargs
) -> None:
self.name = "FilesystemStorageManager"
if "next_layer" in kwargs:
self._next = kwargs["next_layer"]
self.is_terminal = False
else:
self.is_terminal = True
... | [
"def new_instance(self):\n base_dir = self.fshelper.base_dir\n s = self.__storage.new_instance()\n res = BlobStorage(base_dir, s)\n return res",
"def _CreateStorageFile(self):\n return sqlite_file.SQLiteStorageFile(storage_type=self._storage_type)",
"def _CreateStorageFile(self):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads file.kv for given file.py. | def load_kv_from_py(f):
filename = os.path.basename(os.path.splitext(f)[0])
Builder.load_file(
os.path.join(
os.path.dirname(os.path.abspath(f)),
filename + '.kv'
)
) | [
"def load_kv_from(kv_name):\n from kivy.lang import Builder\n\n kv_file = join(APP_PATH, kv_name)\n return Builder.load_file(kv_file)",
"def load_device_key(self, filename):\n pass",
"def load(self, file=None):\n if file:\n self.files.append({'file': file, 'exists': '', 'loaded... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Android runtime storage permission check. | def check_write_permission():
if platform != "android":
return True
from android.permissions import Permission, check_permission
permission = Permission.WRITE_EXTERNAL_STORAGE
return check_permission(permission) | [
"def check_request_write_permission():\n had_permission = check_write_permission()\n if not had_permission:\n from android.permissions import Permission, request_permission\n permission = Permission.WRITE_EXTERNAL_STORAGE\n request_permission(permission)\n return had_permission",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overloads the StringIO.__init__() makes it possible to hook a callback for write operations. | def __init__(self, initial_value='', newline='\n', callback_write=None):
self.callback_write = callback_write
super(StringIOCBWrite, self).__init__(initial_value, newline) | [
"def write(self, s):\n super(StringIOCBWrite, self).write(s)\n if self.callback_write is not None:\n self.callback_write(s)",
"def __init__(self):\n self.__io_str = StringIO()",
"def write(self, s):\n super().write(s)\n if self.callback_write is not None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls the StringIO.write() method then the callback_write with given string parameter. | def write(self, s):
super(StringIOCBWrite, self).write(s)
if self.callback_write is not None:
self.callback_write(s) | [
"def write(self, s):\n super().write(s)\n if self.callback_write is not None:\n self.callback_write(s)",
"def write( chunk, callback=None ):",
"def write(self, data, callback=None):\r\n assert isinstance(data, bytes_type)\r\n self._check_closed()\r\n # We use bool(_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dispatches dismiss event for all dialogs. | def dismiss_all_dialogs(cls):
# keeps a local copy since we're altering them as we iterate
dialogs = cls.dialogs[:]
for dialog in dialogs:
dialog.dispatch('on_dismiss') | [
"def closeEvent( self, event ):\n self.ui_mdiArea.closeAllSubWindows()\n event.accept()",
"def dismiss(self) -> None:\n self.driver.execute(Command.W3C_DISMISS_ALERT)",
"def dismiss(self):\n self._get_backend().dismiss_alarm()",
"def DialogClose_clicked_cb(self, data=None):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a dialog from given title and content. Adds it to the dialogs track list. | def create_dialog_content_helper(cls, title, content):
# TODO
dialog = MDDialog(
title=title,
content=content,
size_hint=(.8, None),
height=dp(250),
auto_dismiss=False)
dialog.... | [
"def create_dialog(cls, title, body):\n dialog = cls.create_dialog_helper(title, body)\n dialog.add_action_button(\n \"Dismiss\",\n action=lambda *x: dialog.dismiss())\n return dialog",
"def create_dialog_helper(cls, title, body):\n content = MDLabel(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a dialog from given title and body. Adds it to the dialogs track list. | def create_dialog_helper(cls, title, body):
content = MDLabel(
font_style='Body1',
theme_text_color='Secondary',
text=body,
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size')... | [
"def create_dialog(cls, title, body):\n dialog = cls.create_dialog_helper(title, body)\n dialog.add_action_button(\n \"Dismiss\",\n action=lambda *x: dialog.dismiss())\n return dialog",
"def create_dialog_content_helper(cls, title, content):\n # TODO\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a dialog from given title and body. Adds it to the dialogs track list. Appends dismiss action. | def create_dialog(cls, title, body):
dialog = cls.create_dialog_helper(title, body)
dialog.add_action_button(
"Dismiss",
action=lambda *x: dialog.dismiss())
return dialog | [
"def create_dialog_content_helper(cls, title, content):\n # TODO\n dialog = MDDialog(\n title=title,\n content=content,\n size_hint=(.8, None),\n height=dp(250),\n auto_dismiss=False)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Graphing multiple choice questions | def graph_multiple_choice(question_type, question, data_frame, path):
if (question_type in ["radio", "dropdown"]):
# Get this question's data
column_data = data_frame[question["column-name"]].astype('str')
new_labels = []
new_counts = []
for option in question["choices"]:
... | [
"def generate_questions(self):",
"def prompt_user():\n \n Q1= input(\"What type of plot output? (Enter #)\"+\"\\n\"+\"\\n\"+\"1.Countplot\"+\"\\n\"+\"2.Scatterplot\"+\"\\n\"+\"3.Boxplot\"+\"\\n\"+\"4.Simple Linear Regression Model\"+\"\\n\"+\"5.Multiple Linear Regression Model\"+\"\\n\")\n question(data,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prettyprint an XML string | def xml_pretty(xml_string):
return xml_string # xml.dom.minidom.parseString(xml_string).toprettyxml() | [
"def prettify(self, xmlstr):\n \n reparsed = minidom.parseString(xmlstr)\n return reparsed.toprettyxml(indent=\" \")",
"def pretty_print_xml(xml_string):\n import xml.dom.minidom\n xdoc = xml.dom.minidom.parseString(xml_string)\n return xdoc.toprettyxml()",
"def prettify(self):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /api/users/{encoded_user_id}/api_key Creates a new API key for specified user. | def api_key( self, trans, user_id, **kwd ):
user = self.get_user( trans, user_id )
key = self.create_api_key( trans, user )
return key | [
"def create_apikey(request, user_id):\r\n user = get_object_or_404(model.User, pk=user_id)\r\n model.ApiKey.generate(owner=user, user=request.user)\r\n\r\n return redirect(\"manage_user_edit\", user_id=user_id)",
"def create_api_key(sender, **kwargs):\r\n if kwargs.get('created') is True:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update( self, trans, id, payload, kwd ) PUT /api/users/{id} updates the values for the item with the given ``id`` | def update( self, trans, id, payload, **kwd ):
current_user = trans.user
user_to_update = self.user_manager.by_id( self.decode_id( id ) )
# only allow updating other users if they're admin
editing_someone_else = current_user != user_to_update
is_admin = trans.api_inherit_admin o... | [
"def put(self, user_id):\r\n return update_user(request, user_id)",
"def UpdateUser(self):\n data_dict = self.GetPayload()\n self.UpdateModel(self.GetUser(), data_dict)",
"def put(self, id):\n payload = marshal(api.payload, invite_user)\n taskroom_service.invite_user(id, payload['emai... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns data for an anonymous user, truncated to only usage and quota_percent | def anon_user_api_value( self, trans ):
usage = trans.app.quota_agent.get_usage( trans )
percent = trans.app.quota_agent.get_percent( trans=trans, usage=usage )
return {'total_disk_usage': int( usage ),
'nice_total_disk_usage': util.nice_size( usage ),
'quota_perc... | [
"def getAnonymizedUserData(self):\n\t\turl = \"https://habitica.com/api/v3/user/anonymized\"\n\t\treturn(getUrl(url, self.credentials))",
"def user_data(self, access_token, *args, **kwargs):\n return self.get_json(\n \"https://www.googleapis.com/oauth2/v3/userinfo\",\n headers={\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the ServiceManager from the running OpenOffice.org. Then retain it in the global variable goServiceManager for future use. This is similar to the GetProcessServiceManager() in OOo Basic. | def getServiceManager( cHost="localhost", cPort="8100" ):
global goServiceManager
if not goServiceManager:
# Get the uno component context from the PyUNO runtime
oLocalContext = uno.getComponentContext()
# Create the UnoUrlResolver on the Python side.
oLocalResolver = oLocalConte... | [
"def getServiceManager( cHost=\"localhost\", cPort=\"2002\" ):\n global goServiceManager\n global pythonloader\n if not goServiceManager:\n # Get the uno component context from the PyUNO runtime\n oLocalContext = uno.getComponentContext()\n # Create the UnoUrlResolver on the Python sid... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An easy way to obtain the Desktop object from a running OOo. | def getDesktop():
global StarDesktop
if StarDesktop == None:
StarDesktop = createUnoService( "com.sun.star.frame.Desktop" )
return StarDesktop | [
"def get_desktop():\n key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders')#利用系统的链表\n return winreg.QueryValueEx(key, \"Desktop\")[0] #返回的是Unicode类型数据",
"def get_desktop_session():\n return get_profile()._get_desktop_session()",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a UNO struct and return it. Similar to the function of the same name in OOo Basic. | def createUnoStruct( cTypeName ):
oCoreReflection = getCoreReflection()
# Get the IDL class for the type name
oXIdlClass = oCoreReflection.forName( cTypeName )
# Create the struct.
oReturnValue, oStruct = oXIdlClass.createObject( None )
return oStruct | [
"def xc_struct(name):\n return XCStruct(name, DEFS[name])",
"def createNodeStruct(_session, _segment, _const):\n return createNode(_session, _segment, _const, \"struct\")",
"def struct(element_tys, name=''): # not packed\r\n context = api.llvm.getGlobalContext()\r\n is_packed = False\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a com.sun.star.beans.PropertyValue struct and return it. | def makePropertyValue( cName=None, uValue=None, nHandle=None, nState=None ):
oPropertyValue = createUnoStruct( "com.sun.star.beans.PropertyValue" )
if cName != None:
oPropertyValue.Name = cName
if uValue != None:
oPropertyValue.Value = uValue
if nHandle != None:
oPropertyValue.H... | [
"def _makeProperty( key, value ):\n property = PropertyValue()\n property.Name = key\n property.Value = value\n return property",
"def toProperty(value):",
"def create_cloud_property(self, value, immutable):\n return {\n \"value\": value,\n \"immutable\":... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a com.sun.star.awt.Point struct. | def makePoint( nX, nY ):
oPoint = createUnoStruct( "com.sun.star.awt.Point" )
oPoint.X = nX
oPoint.Y = nY
return oPoint | [
"def create_point(x_crd, y_crd):\n\n Point = namedtuple(\"Point\", \"x_crd y_crd\")\n return Point(x_crd, y_crd)",
"def new(self, x, y):\r\n\t\treturn Point(x,y,type=self.type)",
"def point(self):\n return collections.namedtuple(self.name, [self.x, self.y, self.units])",
"def point(self,coordinat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a com.sun.star.awt.Size struct. | def makeSize( nWidth, nHeight ):
oSize = createUnoStruct( "com.sun.star.awt.Size" )
oSize.Width = nWidth
oSize.Height = nHeight
return oSize | [
"def calcsize(fmt: str) -> int:\n ...",
"def setBoxsize(length,width,height):\n return length,width,height",
"def GetSizeCX(self):\n ...",
"def __init__(self, size):\n self.__size = size # This will be the height and width",
"def _get_size(self, choices=[]):\n if IS_LINUX and cho... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a com.sun.star.awt.Rectangle struct. | def makeRectangle( nX, nY, nWidth, nHeight ):
oRect = createUnoStruct( "com.sun.star.awt.Rectangle" )
oRect.X = nX
oRect.Y = nY
oRect.Width = nWidth
oRect.Height = nHeight
return oRect | [
"def create_rectangle(self, *args, **kw):\n return self._create('rectangle', args, kw)",
"def RectPP(*args, **kwargs):\n val = _core_.new_RectPP(*args, **kwargs)\n return val",
"def RectS(*args, **kwargs):\n val = _core_.new_RectS(*args, **kwargs)\n return val",
"def create_rectangle(width,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup and return a style from the document. | def getStyle( oDrawDoc, cStyleFamily, cStyleName ):
return oDrawDoc.getStyleFamilies().getByName( cStyleFamily ).getByName( cStyleName ) | [
"def lookup_style(name):\n rv = STYLES.get(name, 'default')\n if rv is None:\n return get_style_by_name(name)\n return rv",
"def lookup(self, style_, option):\n return self.style.lookup(style_, option)",
"def get_or_add_style(document, style_name, style_type):\n # `get_by_id` returns d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a byte array. | def encode_byte_array(value: bytes) -> bytes:
return bytes([]) if isinstance(value, type(None)) else value | [
"def encode_byte_array(byte_arr):\n enc_string = base64.b64encode(bytes(byte_arr))\n return enc_string",
"def encode_array(input_array, codec, param):\n return add_header(codec_dict[codec].encode(input_array, param), codec, len(input_array), param)",
"def base64_encode_array(inArray):\n return base6... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a CL value. | def encode_cl_value(entity: CLValue) -> bytes:
return encode_u8_array(encode(entity)) + \
encode_cl_type(entity.cl_type) | [
"def encode(value: CLValue) -> bytes:\n encoder = ENCODERS[value.cl_type.typeof]\n if value.cl_type.typeof in {CLTypeKey.LIST, CLTypeKey.OPTION}:\n return encoder(\n value.parsed,\n ENCODERS[value.cl_type.inner_type.typeof]\n )\n else:\n return encoder(value.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a CL type definition. | def encode_cl_type(entity: CLType) -> bytes:
def encode_byte_array():
return bytes([entity.typeof.value]) + encode_u32(entity.size)
def encode_list():
raise NotImplementedError()
def encode_map():
raise NotImplementedError()
def encode_option():
return bytes([entity.ty... | [
"def encode_cl_type(entity: CLType) -> bytes:\n def encode_byte_array():\n return bytes([entity.typeof.value]) + encode_u32(entity.size)\n\n def encode_list():\n raise NotImplementedError()\n\n def encode_map():\n raise NotImplementedError()\n\n def encode_option():\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a signed 32 bit integer. | def encode_i32(value: int) -> bytes:
return int_to_le_bytes(value, NUMERIC_CONSTRAINTS[CLTypeKey.I32].LENGTH, True) | [
"def encode32(x):\n while x < 0:\n x = x + 2**32 # Convert 2's complement negative numbers to unsigned\n assert((x >> 32) == 0) # Must be a 32bit quantity\n x = pack(x, 32, 'little', False) # Convert to little endian\n\n s = \"\"\n for b in x:\n s += '{:02x}'.format(b) # Convert l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a signed 64 bit integer. | def encode_i64(value: int) -> bytes:
return int_to_le_bytes(value, NUMERIC_CONSTRAINTS[CLTypeKey.I64].LENGTH, True) | [
"def encode_u64(value: int) -> bytes:\n return int_to_le_bytes(value, NUMERIC_CONSTRAINTS[CLTypeKey.U64].LENGTH, False)",
"def writeInt64(self, *args):\n self.writeInt(8, *args)",
"def EncryptInt64(self, plaintext, r_value=None):\n if not isinstance(plaintext, int) and not isinstance(plaintext, lon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a list of values. | def encode_list(value: list, inner_encoder: typing.Callable) -> bytes:
return encode_vector_of_t(list(map(inner_encoder, value))) | [
"def encode_list(value):\n\tret = []\n\tfor val in value:\n\t\tret.append(encode(val))\n\treturn ret",
"def _encode_list(source: list) -> bytes:\n result_data = b\"l\"\n\n for item in source:\n result_data += encode(item)\n\n return result_data + b\"e\"",
"def encode_map(value: list) -> bytes:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a map of keys to associated values. | def encode_map(value: list) -> bytes:
raise NotImplementedError() | [
"def encode_dict(value):\n\tret = {}\n\tfor k in value:\n\t\tret[k] = encode(value[k])\n\treturn ret",
"def _encode_dict(source: dict) -> bytes:\n result_data = b\"d\"\n\n for key, value in source.items():\n result_data += encode(key) + encode(value)\n\n return result_data + b\"e\"",
"def recode... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes an optional CL value. | def encode_option(value: object, inner_encoder: typing.Callable) -> bytes:
return bytes([0] if value is None else [1]) + inner_encoder(value) | [
"def encode(value: CLValue) -> bytes:\n encoder = ENCODERS[value.cl_type.typeof]\n if value.cl_type.typeof in {CLTypeKey.LIST, CLTypeKey.OPTION}:\n return encoder(\n value.parsed,\n ENCODERS[value.cl_type.inner_type.typeof]\n )\n else:\n return encoder(value.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a public key. | def encode_public_key(value: PublicKey) -> bytes:
return bytes([value.algo.value]) + value.pbk | [
"def encode_public_key(key):\r\n return key.publickey().exportKey(format=\"DER\")",
"def EncodeKey(pub_key: Union[bytes, IPublicKey],\n **kwargs: Any) -> str:",
"def export_public_key(self):\r\n return self.public_key.encode('hex')",
"def encrypt_key(self, key, public_key):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a smart contract execution result. | def encode_result(value: object) -> bytes:
raise NotImplementedError() | [
"def send_result(result, encode=None):\n # encode result if requested\n if encode == 'json':\n result = json.dumps(result)\n elif not encode is None:\n raise Exception('No such encoder: %s' % encode)\n \n # send \"result\" IPC message to manager\n AMQP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a 1ary tuple of CL values. | def encode_tuple1(value: tuple) -> bytes:
raise NotImplementedError() | [
"def encode_tuple3(value: tuple) -> bytes:\n raise NotImplementedError()",
"def pack_tuple(self, values):\n assert isinstance(values, (tuple, list))\n cardinality = [struct_L.pack(len(values))]\n packed_items = [self.pack_field(v) for v in values]\n return b''.join(itertools.chain(c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a 2ary tuple of CL values. | def encode_tuple2(value: tuple) -> bytes:
raise NotImplementedError() | [
"def encode_tuple3(value: tuple) -> bytes:\n raise NotImplementedError()",
"def encode_tuple1(value: tuple) -> bytes:\n raise NotImplementedError()",
"def pack_tuple(self, values):\n assert isinstance(values, (tuple, list))\n cardinality = [struct_L.pack(len(values))]\n packed_items =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a 3ary tuple of CL values. | def encode_tuple3(value: tuple) -> bytes:
raise NotImplementedError() | [
"def encode_tuple2(value: tuple) -> bytes:\n raise NotImplementedError()",
"def pack_tuple(self, values):\n assert isinstance(values, (tuple, list))\n cardinality = [struct_L.pack(len(values))]\n packed_items = [self.pack_field(v) for v in values]\n return b''.join(itertools.chain(c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes an unsigned 8 bit integer. | def encode_u8(value: int) -> bytes:
return int_to_le_bytes(value, NUMERIC_CONSTRAINTS[CLTypeKey.U8].LENGTH, False) | [
"def put_uint8(self, value):\n if (not isinstance(value, int)) or (value < 0 or value > 255):\n raise ValueError(\"Invalid uint8: %s\" % value)\n self.bytes.extend(struct.pack('!B', value))",
"def Write_uInt8(self,Address,Register,uInt8):\n self.Transaction(chr(Address)+chr(Register)+struct.pack... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes an array of unsigned 8 bit integers. | def encode_u8_array(value: typing.List[int]) -> bytes:
return encode_u32(len(value)) + bytes(value) | [
"def encode(cls, data):\n t, img = data\n # Cast double time into eight 8-bit integers\n#\t\tta=np.array(binary_cast([t],'d','hhhh'))\n ta = np.array(binary_cast([t], 'd', 'BBBBBBBB'))\n # Cast w,h 16-bit unsigned integers into two unsigned 8-bit integers\n cp = cls.compress(img)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes an unsigned 32 bit integer. | def encode_u32(value: int) -> bytes:
return int_to_le_bytes(value, NUMERIC_CONSTRAINTS[CLTypeKey.U32].LENGTH, False) | [
"def put_uint32(self, value):\n if (not isinstance(value, int)) or (value < 0 or value > 2 ** 32 - 1):\n raise ValueError(\"Invalid uint32: %s\" % value)\n self.bytes.extend(struct.pack('!L', value))",
"def encode32(x):\n while x < 0:\n x = x + 2**32 # Convert 2's complement negative numbe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes an unsigned 64 bit integer. | def encode_u64(value: int) -> bytes:
return int_to_le_bytes(value, NUMERIC_CONSTRAINTS[CLTypeKey.U64].LENGTH, False) | [
"def encode_i64(value: int) -> bytes:\n return int_to_le_bytes(value, NUMERIC_CONSTRAINTS[CLTypeKey.I64].LENGTH, True)",
"def pack_ssh_uint64(i):\n if not isinstance(i, int):\n raise TypeError(\"Must be an int\")\n elif i.bit_length() > 64:\n raise ValueError(\"Must be a 64bit value.\")\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes an unsigned 128 bit integer. | def encode_u128(value: int) -> bytes:
for type_key in (CLTypeKey.U8, CLTypeKey.U32, CLTypeKey.U64, CLTypeKey.U128):
if is_within_range(type_key, value):
break
else:
raise ValueError("Invalid U128: max size exceeded")
as_bytes = int_to_le_bytes_trimmed(value, NUMERIC_CONSTRAINTS[... | [
"def toUInt128(self): # real signature unknown; restored from __doc__\n pass",
"def write_uleb128(num: int) -> bytearray:\n if num == 0:\n return bytearray(b'\\x00')\n\n ret = bytearray()\n length = 0\n\n while num > 0:\n ret.append(num & 0b01111111)\n num >>= 7\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes an unsigned 256 bit integer. | def encode_u256(value: int) -> bytes:
for type_key in (CLTypeKey.U8, CLTypeKey.U32, CLTypeKey.U64, CLTypeKey.U128, CLTypeKey.U256):
if is_within_range(type_key, value):
break
else:
raise ValueError("Invalid U256: max size exceeded")
as_bytes = int_to_le_bytes_trimmed(value, ... | [
"def encode_unsigned_varint(value, appender):\n while value > 0x1F:\n pos = (value & 0x1F) | 0x20\n appender(ENCODING_TABLE[pos])\n value >>= 5\n appender(ENCODING_TABLE[value])",
"def IntEncode(int_val: int) -> bytes:\n return ed25519_lib.int_encode(int_val)",
"def encode_int(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes an unsigned 512 bit integer. | def encode_u512(value: int):
for type_key in (CLTypeKey.U8, CLTypeKey.U32, CLTypeKey.U64, CLTypeKey.U128, CLTypeKey.U256, CLTypeKey.U512):
if is_within_range(type_key, value):
break
else:
raise ValueError("Invalid U512: max size exceeded")
as_bytes = int_to_le_bytes_trimmed(valu... | [
"def write_uleb128(num: int) -> bytearray:\n if num == 0:\n return bytearray(b'\\x00')\n\n ret = bytearray()\n length = 0\n\n while num > 0:\n ret.append(num & 0b01111111)\n num >>= 7\n if num != 0:\n ret[length] |= 0b10000000\n length += 1\n\n return ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes an unforgeable reference. | def encode_uref(value: UnforgeableReference):
return encode_byte_array(
value.address + bytes([value.access_rights.value])
) | [
"def serialized(self):\n return self.reference().Encode()",
"def referent_to_bytes(referent):\n return pickle.dumps({\n 'left': referent.left_ref.address,\n 'key': referent.key,\n 'value': referent.value_ref.address,\n 'right': referent.right_ref.address,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes an unbound vector. | def encode_vector_of_t(value: list):
return encode_u32(len(value)) + bytes([i for j in value for i in j]) | [
"def encode_vector(v_dec, L = 6, m = 3):\n T = np.arange(m**L).reshape(tuple([m for i in range(L)]))\n return T[tuple(v_dec)]",
"def Vector():",
"def store_vector(self, vec_id, vector):\n pass",
"def write(self, *args):\n return _yarp.VectorBase_write(self, *args)",
"def set(self, incomi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a CL value as an array of bytes. | def encode(value: CLValue) -> bytes:
encoder = ENCODERS[value.cl_type.typeof]
if value.cl_type.typeof in {CLTypeKey.LIST, CLTypeKey.OPTION}:
return encoder(
value.parsed,
ENCODERS[value.cl_type.inner_type.typeof]
)
else:
return encoder(value.parsed) | [
"def encode_cl_value(entity: CLValue) -> bytes:\n return encode_u8_array(encode(entity)) + \\\n encode_cl_type(entity.cl_type)",
"def encode_byte_array(value: bytes) -> bytes:\n return bytes([]) if isinstance(value, type(None)) else value",
"def encode_u8_array(value: typing.List[int]) -> bytes:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scan the table for pokemon entries. | def do_scan(self, arg):
results = self._table.scan()
for item in results["Items"]:
self._print(_pretty(item)) | [
"def do_query(self, pokemon):\n results = self._table.query(\n Select=\"ALL_ATTRIBUTES\",\n KeyConditionExpression=\"Pokemon = :pokemon AND #index > :index\",\n ExpressionAttributeNames={\n \"#index\": \"Index\",\n },\n ExpressionAttribute... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query for a pokemon. | def do_query(self, pokemon):
results = self._table.query(
Select="ALL_ATTRIBUTES",
KeyConditionExpression="Pokemon = :pokemon AND #index > :index",
ExpressionAttributeNames={
"#index": "Index",
},
ExpressionAttributeValues={
... | [
"def handlePokemonRequest(self, query):\r\n\r\n\t\t## Exceptions, they do seem to love non-conforming pokemon\r\n\t\tif query[0] == 'deoxys':\r\n\t\t\tquery[0] = 'deoxys-normal'\r\n\t\telif query[0] == 'keldeo':\r\n\t\t\tquery[0] = 'keldeo-ordinary'\r\n\t\telif query[0] == 'oricorio':\r\n\t\t\tquery[0] = 'oricorio-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Activate/use this frame buffer. | def activate(self):
# Send command
self._glir.command('FRAMEBUFFER', self._id, True)
# Associate canvas now
canvas = get_current_canvas()
if canvas is not None:
canvas.context.glir.associate(self.glir) | [
"def __enter__(self):\n gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.fbo)",
"def _activate(self):\n\n log.debug(\"GPU: Activating program (id=%d)\" % self._id)\n gl.glUseProgram(self.handle)\n\n for uniform in self._uniforms.values():\n if uniform.active:\n un... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop using this frame buffer, the previous framebuffer will be made active. | def deactivate(self):
self._glir.command('FRAMEBUFFER', self._id, False) | [
"def stop(self):\n self._mmio.write(0x00, 0x00011080)\n while self.running:\n pass\n for i in range(len(self._frames)):\n self._frames[i] = None\n if hasattr(self, '_cache'):\n self._cache.clear()",
"def stop(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The shape of the Texture/RenderBuffer attached to this FrameBuffer | def shape(self):
if self.color_buffer is not None:
return self.color_buffer.shape[:2] # in case its a texture
if self.depth_buffer is not None:
return self.depth_buffer.shape[:2]
if self.stencil_buffer is not None:
return self.stencil_buffer.shape[:2]
... | [
"def get_framebuffer_shape(self):\n return self.frame_buffer.shape",
"def get_shape():\n return _buffer_width, _buffer_height",
"def frame_shape(self):\n pass",
"def get_buffer_shape(self):\n\n return self.buf.shape",
"def shape(self):\n return self.width, self.height, self.nu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resize all attached buffers with the given shape | def resize(self, shape):
# Check
if not (isinstance(shape, tuple) and len(shape) == 2):
raise ValueError('RenderBuffer shape must be a 2-element tuple')
# Resize our buffers
for buf in (self.color_buffer, self.depth_buffer, self.stencil_buffer):
if buf is None:
... | [
"def resizeBuffers(self):\n for i, buffer in enumerate(self.buffers):\n (mul, div, align) = self.sizes[i]\n (xsize, ysize) = self.getScaledSize(mul, div, align)\n buffer.setSize(xsize, ysize)",
"def resize(self, shape):\n # As an inplace operation, this requires impl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and set alist of lists of the selected height >>> create_map(4) >>> len(STATUS['game_grid']) 16 | def create_map(grid_size):
STATUS['game_grid'] = [] # Could be a tuple?
STATUS['grid_size'] = grid_size
x_coord = 1
y_coord = 1
grid_size_counter = grid_size * grid_size
while grid_size_counter:
STATUS['game_grid'].append([x_coord, y_coord])
x_coord += 1
if x_coord == gr... | [
"def regenerate_heightmap(self):\n\n for x in range(16):\n for z in range(16):\n column = x * 16 + z\n for y in range(255, -1, -1):\n if self.get_block((x, y, z)):\n break\n\n self.heightmap[column] = y",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the locations dict. | def get_locations():
return STATUS['locations'] | [
"def get(self):\r\n return {\"locations\": list(map(lambda x: x.json(), Location.query.all()))}",
"def locations(self):\n if \"locations\" in self.state:\n return self.state[\"locations\"]\n else:\n return []",
"def locations(self):\n return self._locations",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomly set the locations of the weapon and the monster | def set_locations():
STATUS['locations']['monster'][0] = generate_random_coord(STATUS['grid_size'])
STATUS['locations']['monster'][1] = generate_random_coord(STATUS['grid_size'])
STATUS['locations']['weapon'][0] = generate_random_coord(STATUS['grid_size'])
STATUS['locations']['weapon'][1] = generate_ran... | [
"def init_locations():\n player, door, monster = sample(CELLS, k=3)\n\n return player, door, monster",
"def put_item_random(self, x, y):\n r = int(random() * 10)\n if 3 < r and r <= 6:\n self.put_fireitem(x, y)\n elif 6 < r and r <= 9:\n self.put_bombitem(x, y)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collect the player's choice of dungeon size. | def get_dungeon_size():
size = input("Choose the size of the dungeon... (4 - 24)\n>")
size = int(size)
while size < 4 or size > 24:
print("Pick a number between four and 24.")
size = input("Choose the size of the dungeon... (4 - 24)\n>")
size = int(size)
return size | [
"def get_dungeon_size(self):\n return self._dungeon_size",
"def shirt_size():\n return random.choice(get_dictionary('shirt_sizes')).strip()",
"async def getPlayersPerRoom(self, ctx):\n size = await self._players_per_room(ctx.guild)\n await ctx.send(\"Combines should have no more than {0}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the player has touched the monster and either killed it, been hurt or lost the game >>> STATUS['locations']['player'] = [3, 4] >>> STATUS['locations']['monster'] = [3, 4] >>> STATUS['weapon'] = 'unarmed' >>> STATUS['hp'] = 10 >>> monster_check() 'The monster caught you! You barely manage to escape...' | def monster_check():
player = get_locations()['player']
monster = get_locations()['monster']
if player == monster:
if STATUS['weapon'] == 'armed':
print("You killed the monster with the sword!")
play_again()
else:
if STATUS['hp'] > 0:
STATU... | [
"def weapon_check():\n if get_locations()['player'] == get_locations()['weapon']:\n STATUS['weapon'] = 'armed'\n STATUS['locations']['weapon'] = None\n print(\"You found the weapon! Now go and kill the monster!\")",
"def check_battle_status(settings, player, monster, grid, game_log, crits)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the player has found the weapon >>> STATUS['locations']['player'] = [3, 4] >>> STATUS['locations']['weapon'] = [3, 4] >>> weapon_check() You found the weapon! Now go and kill the monster! | def weapon_check():
if get_locations()['player'] == get_locations()['weapon']:
STATUS['weapon'] = 'armed'
STATUS['locations']['weapon'] = None
print("You found the weapon! Now go and kill the monster!") | [
"def player_hit(self, player: Player, weapon: Weapon):\n status = self.players[player].status\n if weapon.damage == 3: self.players[player].status = 'dead'\n\n if weapon.damage == 2:\n if status != 'healthy': self.players[player].status = 'dead'\n else: self.players[player... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert the actual move keys into legible text >>> moves = ['W', 'A', 'D'] >>> parse_moves(moves) ['UP', 'LEFT', 'RIGHT'] | def parse_moves(moves):
possible_moves = []
for move in moves:
if move == 'W':
possible_moves.append('UP')
elif move == 'D':
possible_moves.append('RIGHT')
elif move == 'S':
possible_moves.append('DOWN')
elif move == 'A':
possible_m... | [
"def legal_moves():\n\tlegal_moves = (\"r\", \"p\", \"s\")\n\treturn legal_moves",
"def set_moves(self, moves: str) -> None:\n\n self.moves = list(moves.lower())",
"def get_move(moves):\n pass",
"def getmovevalues(moves):\n values = \" \" * 9\n for move in moves:\n index = movetoind... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the Roemer timing delay about the Solar System Barycentre at the position the Earth, given a set of ecliptic coordinates for a given pulsar. | def roemer_delay(epoch, ecl_latitude, ecl_longitude, ephemeris='de432s'):
# before computing anythin, set the ephemeris context to be value
# supplied at the function call.
solar_system_ephemeris.set(ephemeris)
time = Time(epoch, format='mjd')
# now comoute the required position vectors.
r_ea... | [
"def parallax_delay(epoch, ecl_latitude, ecl_longitude, distance, ephemeris='de432s'):\n\n # before computing anythin, set the ephemeris context to be value \n # supplied at the function call.\n solar_system_ephemeris.set(ephemeris)\n time = Time(epoch, format='mjd')\n distance *= u.kpc\n\n # now ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the annualparallax timing delay for the Earth, given a set of ecliptic coordinates and distance measure. | def parallax_delay(epoch, ecl_latitude, ecl_longitude, distance, ephemeris='de432s'):
# before computing anythin, set the ephemeris context to be value
# supplied at the function call.
solar_system_ephemeris.set(ephemeris)
time = Time(epoch, format='mjd')
distance *= u.kpc
# now comoute the r... | [
"def roemer_delay(epoch, ecl_latitude, ecl_longitude, ephemeris='de432s'):\n\n # before computing anythin, set the ephemeris context to be value \n # supplied at the function call.\n solar_system_ephemeris.set(ephemeris)\n time = Time(epoch, format='mjd')\n\n # now comoute the required position vecto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Générer la liste des noms de blocs d'un template | def _get_block_names(template):
nodelist = template.template.nodelist
extendlist = nodelist.get_nodes_by_type(ExtendsNode)
if len(extendlist) > 0:
for block in extendlist[0].blocks:
yield block
parent_template = get_template(extendlist[0].parent_name.resol... | [
"def list():\n print(\"Templates: \\n\")\n for template in templates:\n print(\"\\t{} - {}\".format(template,\n templates[template]))",
"def _custom_template_names(self, template):\n splitted = template.rsplit('/', 1)\n name = 'custom_' + splitted[-1]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renvoyer si des tags HTML existent dans le template | def _find_html_tags(template, tags, find_all=True):
nodelist = template.template.nodelist
extendlist = nodelist.get_nodes_by_type(ExtendsNode)
textlist = nodelist.get_nodes_by_type(TextNode)
if len(extendlist) > 0:
parent_template = get_template(extendlist[0].parent_name.reso... | [
"def has_tags_in_content(self):\n\t\treturn self.get_content() and re_tag.search(self.get_content())",
"def is_tag():\n return False",
"def __is_known_tag(self, html, pos):\n tag = self.__extract_html_tag(html, pos)\n return ((tag in cf.TAGS_BREAKS_LINE) or (tag in cf.TAGS_FORMAT_TEXT) or\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert value or signal from binary encoding to gray encoding | def binToGray(sigOrVal) -> RtlSignalBase:
return (sigOrVal >> 1) ^ sigOrVal
#width = sigOrVal._dtype.bit_length()
#return Concat(sigOrVal[width - 1],
# sigOrVal[width - 1:0] ^ sigOrVal[width:1]) | [
"def binary_to_gray(self, num):\n return num ^ (num >> 1)",
"def togray(self,value):\n (red,green,blue) = self.unpack_value(value)\n \n gray = []\n for i in xrange(1024):\n graypx = (0.299*float(red[i]) + 0.587*float(green[i]) +\n 0.114*float(blue[i]))/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates a GMM from a dataset | def gmm(X, k):
mix = sklearn.mixture.GaussianMixture(n_components=k).fit(X)
pi = mix.weights_
m = mix.means_
S = mix.covariances_
clss = mix.predict(X)
bic = mix.bic(X)
return pi, m, S, clss, bic | [
"def my_GMM(X,K):\n\tmain_data = X[:,:-1].astype(float)\n\tground_truth = X[:,-1]\n\tgmm = mixture.GMM(n_components=K)\n\tpredicted_labels = gmm.fit_predict(main_data)\n\t# Metric calculation\n\tground_mapping = {}\n\tmodified_ground_mapping = []\n\tcounter = 0.0\n\tfor x in ground_truth:\n\t\tif x in ground_mappin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tests that only assignment clauses can be added to queries | def test_add_assignment_type_checking(self):
stmt = AssignmentStatement('table', [])
with self.assertRaises(StatementException):
stmt.add_assignment_clause('x=5') | [
"def test_add_assignment_type_checking(self):\r\n stmt = AssignmentStatement('table', [])\r\n with self.assertRaises(StatementException):\r\n stmt.add_assignment_clause('x=5')",
"def test_partial_update_creation(self):\r\n ctx = {}\r\n col = columns.Set(columns.Integer, db_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes a Time Weighted Risk parcel. Normalizes the timestamps and returns the TWR parcel. | def twr(begin_ts, ts, current_ts):
begin_diff = ts - begin_ts
diff = current_ts - begin_ts
if diff == 0:
normalized = 1
else:
normalized = Decimal(begin_diff) / Decimal(diff)
twr = 1 / (1 + Decimal.exp(Decimal(-12) * normalized + Decimal(2) + ((1 - Metric... | [
"def compute_weights(self, time_scale=300):\n\n # Assert that times are offset seconds\n self.time_stamps_to_offset_seconds()\n\n # Compute weights from time differences\n weights = np.zeros((self.n_science, self.n_sky))\n for ii in range(self.n_science):\n delta_t = se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the TWR sum from a list. By receiving a list, computes the TWR sum, by giving the begin timestamp and the most current timestamp. | def list_twr(seq, begin_ts, current_ts):
twr_sum = 0
for ts in seq:
twr_sum += Metrics.twr(begin_ts, ts, current_ts)
return twr_sum | [
"def timeseries_list_sum(data, series_list, field_spec):\n return TimeSeries.timeseries_list_reduce(data, series_list, Event.sum, field_spec)",
"def sum_list(input_list: List[float]) -> float:\n return sum(input_list)",
"def weightsum(xiinlist,wgtlist):\n if len(xiinlist) < 1:\n return None\n try... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the defect probability for every child | def compute_defect_probability(self):
self.defect_prob = self.defect_probability()
for file_analytics in self.files_analytics.values():
file_analytics.compute_defect_probability() | [
"def calc_marginal_probabilities(self, clade):\n if clade.is_terminal():\n return\n else:\n clade.prob[:] = np.log(clade.down_message)\n for child in clade.clades:\n clade.prob += np.log(child.up_message)\n\n # normalize and continue for all c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts repository analytics to a dict. It traverses child analytics to convert and adds some information useful for the Sunburst chart. | def to_dict(self):
children = [f_metrics.to_dict(f_path) for f_path, f_metrics in self.files_analytics.items()]
metrics = {
"name": "root",
"children": children
}
return metrics | [
"def analyze(self):\n analytics = RepositoryAnalytics()\n\n for commit in self.repository.commits:\n\n # Repository Granularity\n self.update_analytics(analytics, commit)\n\n # File Granularity\n parent_analytics_dict = analytics.files_analytics\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if key is a recognised bound name or percentage | def is_valid_descriptor(key):
return key in Bounds.standard_bound_names or Bounds.parse_pct(key) is not None | [
"def _check_key_name(cls, name):\n return (isinstance(name, basestring) and\n re.match('^[A-Za-z][A-Za-z0-9_]*$', name) and\n not hasattr(cls, name))",
"def _get_one_bound(self, param_name):\n return getattr(self, '__' + param_name + '_bounds')",
"def check(self, name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function gets the maximum number from the user and generates a list from 2 to that maximum number | def list_nums():
max_num = int(input("What is the maximum number you would like to use?"))
num_list = []
for x in range(2, max_num + 1):
num_list.append(x)
return num_list | [
"def generate_n_with_max(num_users, max_num):\n return list(range(1, num_users, num_users//max_num))[:max_num]",
"def makeList(max):\n masterList = []\n for x in range(2, max):\n masterList.append(x)\n return masterList",
"def find_greatest_number(incoming_list: list):\n return max(incomin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function loops through the list from 2 to the maximum number and finds the prime numbers and eliminates the numbers that are not prime numbers (multiples of the prime numbers). | def prime_list(num_list):
primes = []
while len(num_list) > 0:
num = num_list[0]
primes.append(num_list[0])
for x in num_list:
if x % num == 0:
num_list.remove(x)
return primes | [
"def all_primes(num):\n cand_list = list(range(3, num+1))\n prime_list = [2,]\n for j in prime_list:\n for i in cand_list:\n if i % j == 0:\n cand_list.pop(cand_list.index(i))\n if cand_list:\n prime_list.append(cand_list[0])\n return prime_list",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes a monit configuration file for a daemonized service. | def create_daemon_config(watch, start_cmd, stop_cmd, pidfile, max_memory=None):
with open(TEMPLATE_LOCATION) as template:
output = template.read()
output = output.format(
process_name=watch, match_clause='PIDFILE "{}"'.format(pidfile),
group=watch, start_line=start_cmd, stop_line=stop_cmd)
if m... | [
"def generate_config_systemd_uwsgi():\n config = configparser.ConfigParser()\n # disable converts option names to lower case\n config.optionxform = str\n config['Unit'] = {\n 'Description': '{} uwsgi daemon'.format(CONFIG['project_name'])\n }\n config['Service'] = {\n 'WorkingDirecto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |