query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Constructs the LR(1) sets of items.
def LR1_ItemSets(self): # The root item is the one representing the entire language. # Since the grammar is in canonical form, it's a Choice over a # single sequence. root_item = self.MakeItem(LANGUAGE, self.rules[LANGUAGE][0],0) # An ItemSet can be found by any of the items in...
[ "def generateItemsets(self,lElts):\n lList = []\n\n lenElt=len(lElts) \n j= 0 \n while j < lenElt:\n lList.append(lElts[j:j+self.maxSeqLength])\n j+=1\n# j+=self.maxSeqLength\n return lList", "def construct(self):\n\n newSet = {}\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Will compare running instances to purchased reservations across all EC2 regions for all of the accounts supplied.
def reserved_compare(options): running_instances = defaultdict(dict) reserved_purchases = defaultdict(dict) regions = boto.ec2.regions() good_regions = [r for r in regions if r.name not in ['us-gov-west-1', 'cn-north-1']] for region in good_re...
[ "def get_all_reservations(config):\n reservations = []\n region_list = regions(aws_access_key_id=config.keys.api,\n aws_secret_access_key=config.keys.secret)\n for region in region_list:\n _logger.info(\"Searching %s\", region)\n cnx = region.connect(aws_access_key_id=config.keys.api,\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether or not this MPCFramework supports the given game
def supports_game(cls, game: Game) -> bool: return game in cls.SUPPORTED_GAMES
[ "def is_support(mode: int) -> bool:\n return mode in supported_modes\n pass", "def detectGameConsole(self):\r\n return self.detectSonyPlaystation() \\\r\n or self.detectNintendo() \\\r\n or self.detectXbox()", "def platform_supported(self):\n return platform.system().lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method that will be called to prepare input for an MPCFramework. This function takes `self.input_file` (given as a CSV) and converts it as necessary into a usable format for the framework.
async def prepare_input(self) -> Status: with open(self.input_file) as fin: reader = csv.DictReader(fin) fieldnames = reader.fieldnames if fieldnames is None: raise ValueError("fieldnames is None from csv reader") for col in self.game.input_column...
[ "def loadCSV(input_file):", "def set_input_csv(self):\n if len(self[\"input_csv\"]) > 1:\n raise Exception(\"You must only specify *one* unified CSV file!\")\n self.csv_path = self[\"input_csv\"][0]\n print(\"Using input file\", self.csv_path)", "def createInputFile(self):\r\n\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Abstract method that is called to actually run the MPC program and get its results. Results are returned as a map of metrics to their values. For example, if a framework writes output data to a CSV, this method
async def run_mpc(self) -> Dict[str, Dict[Metric, int]]: pass
[ "def compute_metrics(self, results: list) -> dict:", "def getResults(self):\n\n\t\t# Basically: self.output = self.formatResultsAs{{self.outputFormat}}\n\t\tif self.outputFormat == 'text':\n\t\t\tself.output = self.formatResultsAsText()\n\t\telif self.outputFormat == 'csv':\n\t\t\tself.output = self.formatResults...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns predefined, constant max rows per partition
def get_max_rows_per_partition() -> int: pass
[ "def max_partition(self, schema, table_name, field=None, filter_map=None):\n raise Exception(\"TODO IMPLEMENT\")", "def largest_part_size():\n return usb_part_size(largest_partition())", "def max_partition(\n table, schema=\"default\", field=None, filter_map=None, metastore_conn_id=\"metastore_defa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A list to a single node linked list
def lstToLinkedList(lst): if not lst: return LinkedList = Node(lst[0]) LinkedList.next = lstToLinkedList(lst[1:]) return LinkedList
[ "def construct_linked_list(lst):\n lst = [ListNode(x) for x in lst]\n for i in xrange(1, len(lst)):\n lst[i - 1].next = lst[i]\n return lst[0]", "def create_linked_list(input_list):\n head=None\n for value in input_list:\n if head is None:\n head=Node(value)\n else:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save dicom images and images with masks on top of the corresponding images. All files will will be saved under main_dir by creating a new folder for contour type and then by creating a folder for each patient separately.
def save_images(all_patients, contour_type='i_contour', main_dir='final_data/images/'): # create folder for contour_type dirname = main_dir + f'{contour_type}/' os.makedirs(dirname, exist_ok=True) for patient in all_patients: # create patient folders for saving dirname ...
[ "def apply_contour():\n for i in os.listdir(pic):\n file, ext = os.path.splitext(i)\n im = Image.open(pic + \"/\" + i)\n im.filter(ImageFilter.CONTOUR)\n im.save(file + \"_contour\" + \".JPEG\")\n im.close()", "def save_imgs(self):\n print(\"Saving the images with requ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new JSON based on the return parameters specified by user. If no return parameters specified, still runs through to clean any URL values, converts URLs to their respective values with clean_value() function.
def clean_json(json, return_params): cleaned_json = [] for element in json: new_element = {} for key in element: if (return_params is None) or (key in return_params): value = element[key] new_element[key] = clean_value(value, key) cleaned_json...
[ "def gen_output(json_dct, *args):\n keys_to_add = ('job_title', 'location', 'date', 'company', 'num_stars')\n for arg, key in zip(args, keys_to_add): \n if arg: \n json_dct[key] = arg\n\n return json_dct", "def convert_list(self, return_list, request):\n assert hasattr(return_lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filters any elements out of JSON who's parameters are not within range specified.
def filter_json(json, param, param_range): filtered_json = [] for element in json: if element[param]: try: value = int(element[param]) if param_range[0] <= value <= param_range[1]: filtered_json.append(element) except: ...
[ "def pop_upper_lim(post_filter):\n lim = int(os.environ['RANGE_UPPER_LIMIT'])\n for field, limits in post_filter.items():\n if field.startswith('year') or field.startswith('date'):\n continue\n if 'lte' in limits and int(limits['lte']) >= lim:\n post_filter[field].pop('lte'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Precompute the polynomial hash values of all the substring starting from the first letter.
def _precompute_substrings(self, p: int) -> List[int]: hash_vals: List[int] = [0] for i in range(len(self._s)): val = (hash_vals[i] * self.X + ord(self._s[i])) % p hash_vals.append(val) return hash_vals
[ "def _compute_polyhashes(self, string):\n # Setting hashing cache\n length = len(string)\n forward = [0]*(length + 1)\n backward = [0]*(length + 1)\n poly = [1]*(length + 1)\n # Computing hashes\n c0 = ord('a')\n for i in range(length):\n c = ord(st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the value of Xl mod p for l = [0, len(s)]
def _precompute_xl(self, p: int) -> List[int]: res = [1] val = 1 for _ in range(len(self._s)): val = (val * self.X) % p res.append(val) return res
[ "def modp(n: int, p: int):\n#[SOLUTION]\n ret = 1\n for i in range(n):\n ret = (2 * ret) % p\n return ret", "def restexpmn(x, p, n) :\n\tresultat = p\n\tcompteur = 1\n\ti = 1\n\twhile resultat != 1 : \n\t\tresultat = resultat / 2\n\t\tcompteur = compteur * 2\n\t\ti = i + 1\n\tresultat = [0] * (i)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
N should be an int specifying what size window Ngram to use. Default is 2 (bigram). features should be an integer specifying how many features of the len(alph)^N features to use to build each profile. Default is 676 (26^2). extended_alphabet should be a boolean value specifying whether to build profiles using only alph...
def __init__(self, N=2, features=0, extended_alphabet=False): self.alph += (string.punctuation + ' ') if extended_alphabet else '' self.N = N self.features = features if features != 0 else len(self.alph)**N
[ "def _profile(self, text):\n prof = zeros(len(self.alph)**self.N)\n ngs = ngrams(text, self.N)\n for tup in ngs:\n loc = 0\n for i in range(len(tup)):\n loc += (len(self.alph)**i) * self.alph.index(tup[i])\n prof[loc] += 1\n return prof", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleans the text into a form that works for processing by removing tabs and linefeeds, and punctuation is extended_alphabet = False, along with making the text uniformly lowercase and transforming it into asciicompatible characters.
def _clean(self, text): if len(self.alph) == 26: text = sub('[\n\t ' + string.punctuation + ']+?', '', text) else: text = sub('[\n\t]+?', '', text) text = text.lower() text = text.encode('ascii', 'ignore').decode() return text
[ "def normalization(text):\n\n accepted_alphabet = [char for char in string.ascii_lowercase] + [\" \"]\n\n # convert all uppercase to lowercase\n text = text.lower()\n\n # remove punctuations\n new_text = \"\"\n for c in text:\n if c in accepted_alphabet:\n new_text += c\n\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates the author profiles, which are vectors of size len(alph)^N.
def _profile(self, text): prof = zeros(len(self.alph)**self.N) ngs = ngrams(text, self.N) for tup in ngs: loc = 0 for i in range(len(tup)): loc += (len(self.alph)**i) * self.alph.index(tup[i]) prof[loc] += 1 return prof
[ "def generate_author():\n return author_surnames[random.randint(0, len(author_surnames) - 1)] + \" \" + author_lastnames[random.randint(0, len(author_surnames) - 1)]", "def generate_id_for_authors():\n counter = 1\n for book in books:\n for author in books[book]:\n if not author in auth...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reduces features to ones with largest variance. If "features" is not specified in instantiation, same as original profile.
def _reduceFeatures(self): # Adds up all profiles corresponding to each author, # then compiles into a matrix of these "group" profiles. group_profiles = {auth : zeros(len(self.alph)**self.N) for auth in set(self.train_data[1])} for i in range(len(self.train_data[1])): group_...
[ "def prune_features(self):\n # select top features\n self.top_features = sorted(self.feature_weight, key = self.feature_weight.get, reverse = True)[:self.prune_threshold]\n # transform instances\n self.train = self.train[:, self.top_features]\n self.test = self.test[:, self.top_fe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Train the model based on the training_data. training_data should be a dictionary whose keys are strings corresponding to an author's name, and whose values are lists of texts written by that author.
def train(self, training_data, chunk_size=100): # For some reason, for the SVM to work, the keys need to be in alphabetical order training_data = {k : training_data[k] for k in sorted(training_data)} # Compile all author texts into one large text to then be broken down for auth in train...
[ "def train(self, corpus):\n # TODO: Train on each word\n pass", "def train(self, texts):\n texts = [text[1].split() for text in texts]\n self.dictionary = corpora.Dictionary(texts)\n doc_term_matrix = [self.dictionary.doc2bow(doc) for doc in texts]\n self.model = gensim.models.Ld...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the list devices endpoint WIFI3452
def test_gwservice_listdevices(self, setup_controller): resp = setup_controller.request("gw", "devices", "GET", None, None) body = resp.url + "," + str(resp.status_code) + ',' + resp.text allure.attach(name="gw list devices", body=body) if resp.status_code != 200: assert Fals...
[ "def test_get_devices(self):\n pass", "def list_devices():\r\n return sd.query_devices()", "def test_verify_list_of_devices_in_my_network():", "def test_get_devices1(self):\n pass", "def test_device_list(self):\n url = reverse(\"dcim-api:device-list\")\n self.add_permissions(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes detections with lower object confidence score than 'conf_thres' and performs NonMaximum Suppression to further filter detections.
def non_max_suppression(prediction, conf_thres=0.5, nms_thres=0.4): # From (center x, center y, width, height) to (x1, y1, x2, y2) prediction[..., :4] = change_box_order(prediction[..., :4], order="xywh2xyxy") output = [None for _ in range(len(prediction))] for image_i, image_pred in enumerate(predicti...
[ "def non_max_suppression(prediction, conf_thres=0.5, nms_thres=0.4):\n # From center(xywh) to corner(xyxy)\n prediction[..., :4] = xywh2xyxy(prediction[..., :4])\n\n output = [None for _ in range(len(prediction))]\n\n for image_i, image_pred in enumerate(prediction):\n\n # Filter out confidence s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
L{BaseLogFile.shouldRotate} is abstract and must be implemented by subclass.
def test_abstractShouldRotate(self): log = logfile.BaseLogFile(self.name, self.dir) self.addCleanup(log.close) self.assertRaises(NotImplementedError, log.shouldRotate)
[ "def test_rotation(self):\n log = RiggedDailyLogFile(self.name, self.dir)\n self.addCleanup(log.close)\n days = [(self.path + \".\" + log.suffix(day * 86400)) for day in range(3)]\n\n # test automatic rotation\n log._clock = 0.0 # 1970/01/01 00:00.00\n log.write(\"123\")\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Various tests for log readers. First of all, log readers can get logs by number and read what was written to those log files. Getting nonexistent log files raises C{ValueError}. Using anything other than an integer index raises C{TypeError}. As logs get older, their log numbers increase.
def test_logReader(self): log = logfile.LogFile(self.name, self.dir) self.addCleanup(log.close) log.write("abc\n") log.write("def\n") log.rotate() log.write("ghi\n") log.flush() # check reading logs self.assertEqual(log.listLogs(), [1]) wi...
[ "def test_listLogsIgnoresZeroSuffixedFiles(self):\n log = logfile.LogFile(self.name, self.dir)\n self.addCleanup(log.close)\n\n for i in range(0, 3):\n with open(\"{}.{}\".format(log.path, i), \"w\") as fp:\n fp.write(\"123\")\n\n self.assertEqual([1, 2], log.li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
L{LogReader.readLines} supports reading no line.
def test_LogReaderReadsZeroLine(self): # We don't need any content, just a file path that can be opened. with open(self.path, "w"): pass reader = logfile.LogReader(self.path) self.addCleanup(reader.close) self.assertEqual([], reader.readLines(0))
[ "def _consume_blanklines(self):\n while True:\n line = self.reader.readline()\n if len(line) == 0:\n return None\n\n if line.rstrip() == '':\n self.offset = self.fh.tell() - self.reader.rem_length()\n continue\n\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the fromFullPath method.
def test_fromFullPath(self): log1 = logfile.LogFile(self.name, self.dir, 10, defaultMode=0o777) self.addCleanup(log1.close) log2 = logfile.LogFile.fromFullPath(self.path, 10, defaultMode=0o777) self.addCleanup(log2.close) self.assertEqual(log1.name, log2.name) self.assert...
[ "def test_fromFullPath(self):\n log1 = logfile.LogFile(self.name, self.dir, 10, defaultMode=0777)\n log2 = logfile.LogFile.fromFullPath(self.path, 10, defaultMode=0777)\n self.assertEquals(log1.name, log2.name)\n self.assertEquals(os.path.abspath(log1.path), log2.path)\n self.asse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test specifying the permissions used on the log file.
def test_specifiedPermissions(self): log1 = logfile.LogFile(self.name, self.dir, defaultMode=0o066) self.addCleanup(log1.close) mode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE]) if runtime.platform.isWindows(): # The only thing we can get here is global read-only ...
[ "def test_specifiedPermissions(self):\n log1 = logfile.LogFile(self.name, self.dir, defaultMode=0066)\n mode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE])\n if runtime.platform.isWindows():\n # The only thing we can get here is global read-only\n self.assertEquals(mode,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
L{logfile.LogFile.reopen} allows to rename the currently used file and make L{logfile.LogFile} create a new file.
def test_reopen(self): with contextlib.closing(logfile.LogFile(self.name, self.dir)) as log1: log1.write("hello1") savePath = os.path.join(self.dir, "save.log") os.rename(self.path, savePath) log1.reopen() log1.write("hello2") with open(self.p...
[ "def test_reopen(self):\n log1 = logfile.LogFile(self.name, self.dir)\n log1.write(\"hello1\")\n savePath = os.path.join(self.dir, \"save.log\")\n os.rename(self.path, savePath)\n log1.reopen()\n log1.write(\"hello2\")\n log1.close()\n\n f = open(self.path, \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Specifying an invalid directory to L{LogFile} raises C{IOError}.
def test_nonExistentDir(self): e = self.assertRaises( IOError, logfile.LogFile, self.name, "this_dir_does_not_exist" ) self.assertEqual(e.errno, errno.ENOENT)
[ "def test_log_to_file_when_dir_does_not_exist(self):\n XKNX(log_directory=\"/xknx/is/fun\")\n\n assert not os.path.isfile(\"/xknx/is/fun/xknx.log\")", "def test_bad_log_dir():\n with pytest.warns(LoggerWarning):\n log_file = '/abc/log.log'\n logger = init_logger(__name__, log_file=l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opening a L{LogFile} which can be read and write but whose mode can't be changed doesn't trigger an error.
def test_cantChangeFileMode(self): if runtime.platform.isWindows(): name, directory = "NUL", "" expectedPath = "NUL" else: name, directory = "null", "/dev" expectedPath = "/dev/null" log = logfile.LogFile(name, directory, defaultMode=0o555) ...
[ "def open_log(self, mode='a') -> None:\n if self.log_name:\n self.log_file = open(self.log_name, mode)", "def open_log(fn):\n\n global log_file\n if fn is not None:\n d = os.path.dirname(fn)\n if d != \"\":\n makedirs(d)\n log_file = open(fn, \"a+\")", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
L{LogFile.listLogs} doesn't choke if it encounters a file with an unexpected name.
def test_listLogsWithBadlyNamedFiles(self): log = logfile.LogFile(self.name, self.dir) self.addCleanup(log.close) with open("{}.1".format(log.path), "w") as fp: fp.write("123") with open("{}.bad-file".format(log.path), "w") as fp: fp.write("123") self.as...
[ "def test_listLogsIgnoresZeroSuffixedFiles(self):\n log = logfile.LogFile(self.name, self.dir)\n self.addCleanup(log.close)\n\n for i in range(0, 3):\n with open(\"{}.{}\".format(log.path, i), \"w\") as fp:\n fp.write(\"123\")\n\n self.assertEqual([1, 2], log.li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
L{LogFile.listLogs} ignores log files which rotated suffix is 0.
def test_listLogsIgnoresZeroSuffixedFiles(self): log = logfile.LogFile(self.name, self.dir) self.addCleanup(log.close) for i in range(0, 3): with open("{}.{}".format(log.path, i), "w") as fp: fp.write("123") self.assertEqual([1, 2], log.listLogs())
[ "def rotated_logs():\n # Ubuntu 9.04\n # /var/log/dmesg.0\n # /var/log/dmesg.1.gz\n # Fedora 10\n # /var/log/messages-20090118\n globpaths = ('/var/log/*.[0-9]',\n '/var/log/*/*.[0-9]',\n '/var/log/*.gz',\n '/var/log/*/*gz',\n '/var/l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Daily log files rotate daily.
def test_rotation(self): log = RiggedDailyLogFile(self.name, self.dir) self.addCleanup(log.close) days = [(self.path + "." + log.suffix(day * 86400)) for day in range(3)] # test automatic rotation log._clock = 0.0 # 1970/01/01 00:00.00 log.write("123") log._cloc...
[ "def test_daily_rotate(self): \n ##############################\n # 最新ファイルをローテーション\n ##############################\n yesterday = date.today() - timedelta(1)\n recentFileFullPath = self.__testDir + os.path.sep + self.__fileName\n\n self.addRecentFile(recentFileFullPath, \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test retrieving log files with L{DailyLogFile.getLog}.
def test_getLog(self): data = ["1\n", "2\n", "3\n"] log = RiggedDailyLogFile(self.name, self.dir) self.addCleanup(log.close) for d in data: log.write(d) log.flush() # This returns the current log file. r = log.getLog(0.0) self.addCleanup(r.clo...
[ "def test_create_logs():\n Log.debug(\"Test debug message\")\n Log.info(\"Test info message\")\n Log.warning(\"Test warning message\")\n Log.error(\"Test error message\")\n\n assert len(get_log_files()) == 5", "def test_logs(self):\n # Purge all logs\n log_dir = self.test_config['LOG_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
L{DailyLogFile.rotate} doesn't do anything if they new log file already exists on the disk.
def test_rotateAlreadyExists(self): log = RiggedDailyLogFile(self.name, self.dir) self.addCleanup(log.close) # Build a new file with the same name as the file which would be created # if the log file is to be rotated. newFilePath = "{}.{}".format(log.path, log.suffix(log.lastDat...
[ "def rotate(self):\n\n newpath = \"%s.%s\" % (self.logpath, self.suffix(self.lastDate))\n if os.path.exists(newpath):\n log.info(\"Cannot rotate log file to '{path}' because it already exists.\", path=newpath)\n return\n self.accessLog(\"Log closed - rotating: [%s].\" % (d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
L{DailyLogFile.rotate} doesn't do anything if the directory containing the log files can't be written to.
def test_rotatePermissionDirectoryNotOk(self): log = logfile.DailyLogFile(self.name, self.dir) self.addCleanup(log.close) os.chmod(log.directory, 0o444) # Restore permissions so tests can be cleaned up. self.addCleanup(os.chmod, log.directory, 0o755) previousFile = log._...
[ "def rotate(self):\n\n newpath = \"%s.%s\" % (self.logpath, self.suffix(self.lastDate))\n if os.path.exists(newpath):\n log.info(\"Cannot rotate log file to '{path}' because it already exists.\", path=newpath)\n return\n self.accessLog(\"Log closed - rotating: [%s].\" % (d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
L{DailyLogFile.rotate} doesn't do anything if the log file can't be written to.
def test_rotatePermissionFileNotOk(self): log = logfile.DailyLogFile(self.name, self.dir) self.addCleanup(log.close) os.chmod(log.path, 0o444) previousFile = log._file log.rotate() self.assertEqual(previousFile, log._file)
[ "def rotate(self):\n\n newpath = \"%s.%s\" % (self.logpath, self.suffix(self.lastDate))\n if os.path.exists(newpath):\n log.info(\"Cannot rotate log file to '{path}' because it already exists.\", path=newpath)\n return\n self.accessLog(\"Log closed - rotating: [%s].\" % (d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that L{DailyLogFile.toDate} converts its timestamp argument to a time tuple (year, month, day).
def test_toDate(self): log = logfile.DailyLogFile(self.name, self.dir) self.addCleanup(log.close) timestamp = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, 0)) self.assertEqual((2000, 1, 1), log.toDate(timestamp))
[ "def test_toDateUsesArgumentsToMakeADate(self):\n log = logfile.DailyLogFile(self.name, self.dir)\n self.addCleanup(log.close)\n\n date = (2014, 10, 22)\n seconds = time.mktime(date + (0,) * 6)\n\n logDate = log.toDate(seconds)\n self.assertEqual(date, logDate)", "def tes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that L{DailyLogFile.toDate} returns today's date by default. By mocking L{time.localtime}, we ensure that L{DailyLogFile.toDate} returns the first 3 values of L{time.localtime} which is the current date. Note that we don't compare the real result of L{DailyLogFile.toDate} to the real current date, as there's a sli...
def test_toDateDefaultToday(self): def mock_localtime(*args): self.assertEqual((), args) return list(range(0, 9)) log = logfile.DailyLogFile(self.name, self.dir) self.addCleanup(log.close) self.patch(time, "localtime", mock_localtime) logDate = log.toDa...
[ "def test_toDate(self):\n log = logfile.DailyLogFile(self.name, self.dir)\n self.addCleanup(log.close)\n\n timestamp = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, 0))\n self.assertEqual((2000, 1, 1), log.toDate(timestamp))", "def test_toDateUsesArgumentsToMakeADate(self):\n log = lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that L{DailyLogFile.toDate} uses its arguments to create a new date.
def test_toDateUsesArgumentsToMakeADate(self): log = logfile.DailyLogFile(self.name, self.dir) self.addCleanup(log.close) date = (2014, 10, 22) seconds = time.mktime(date + (0,) * 6) logDate = log.toDate(seconds) self.assertEqual(date, logDate)
[ "def test_toDate(self):\n log = logfile.DailyLogFile(self.name, self.dir)\n self.addCleanup(log.close)\n\n timestamp = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, 0))\n self.assertEqual((2000, 1, 1), log.toDate(timestamp))", "def test_toDateDefaultToday(self):\n\n def mock_localtime...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test extension_level parameter of Extended Isolation Forest. The extension_level=0 means Isolation Forest's behaviour. This test is testing the known Isolation Forest's behaviour of 'Ghost clusters' which Extended Isolation Forest mitigates. The overall variance in anomaly score of EIF should be lower than anomaly scor...
def extended_isolation_forest_extension_level_smoke(): seed = 0xBEEF double_blob = make_blobs(centers=[[10, 0], [0, 10]], cluster_std=[1, 1], random_state=seed, n_samples=500, n_features=2)[0] train = h2o.H2OFrame(double_blob) anomalies = h2o.H2OFrame([[0, 0], [10, 10]]) #...
[ "def test_alert_definition_get_escalation_level_operator(self):\n pass", "def test_alert_definition_get_escalation_level_integration(self):\n pass", "def test_alert_definition_get_escalation_level(self):\n pass", "def test_impurity_function():\r\n data=[[1,2,3,4,0],[2,3,4,6,0],[3,5,6,7...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Buy the required quantity Y of X
def Buy(self, X, Y): if self.money - (int(Y) * self.price[X][0] * (1 + self.taxe)) < 0: raise TradeError("Not Enough Money") self.share[X] += int(Y) self.money -= int(Y) * self.price[X][0] * (1 + self.taxe) print(f"BUY:{str(int(Y))}:{str(X)}", flush = True)
[ "def _buy(self, units=1):\n self.quantity -= units", "def buy(self, stock, amount):\n self.orders[stock] += amount", "def buy(self, price, volume):\r\n self.order(\"bid\", price, volume)", "def buy(user_id, ticker, amount, price):\r\n pass", "def create_buy_order(self, pair, quantity...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the value of all money and all share converted into money
def GetSpeculated(self): return self.money + sum([self.share[i] * self.price[i][0] * (1 + self.taxe) for i in self.price])
[ "def getCurrencies():", "def _get_val(self):\n try:\n return self.assets_owned.dot(self.asset_prices) + self.USD\n except TypeError:\n print('TypeError calculating account value.')\n print('Assets owned: ' + str(self.assets_owned))\n print('Asset prices: '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw Bollinger Bands for little value
def DrawBands(self, count): value = self.little[0] mobile_average = float(sum([float(self.little[i]) for i in range(len(self.little))])) / float(self.period) standard_derivation = sqrt(sum([pow(self.little[i] - mobile_average, 2) for i in range(len(self.little))]) / self....
[ "def plot_bollinger(df,w,k):\r\n\tBB=bollinger(df,w,k)\r\n\tfig = plt.figure()\r\n\tax1 = fig.add_subplot(111)\r\n\tBB[[\"Input\",\"BBUP\",\"BBDOWN\"]].plot(ax=ax1,figsize=(13,9))\r\n\tax1.fill_between(df.index,BB[\"BBUP\"],BB[\"BBDOWN\"],facecolor='red', alpha=0.4)", "def bbands(self):\n sub = self.data[[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reverse list recursively in place
def reverse_list_recursively_in_place(list1, first = 0, last = -1): while first <= len(list1) // 2 - 1: #midpoint #switch first and last indexes new_last_item = list1[0] new_first_item = list1[-1] list1[0] = new_first_item list1[-1] = new_last_item # print(...
[ "def reverse(lst):\r\n lst.reverse()\r\n return lst", "def reverse_recursive(lst):\n if len(lst) == 1: return lst\n else: return lst[-1:] + reverse_recursive(lst[0:-1])\n \n \"\"\"i = []\n while len(lst) > 0:\n i.append(lst[-1])\n lst = lst[0:-1]\n return i\n \"\"\"", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the item map.
def load_item_map(cache_file): with open(cache_file, 'rb') as f: full_item_map = pickle.load(f) return full_item_map
[ "def loadMap(self, map):\n self.map = map", "def loadObjectMaps(self):\n path = os.path.join(self.dir,settings['mosh.modInfos.objectMaps'])\n if os.path.exists(path):\n self.objectMaps = compat.uncpickle(open(path,'rb'))\n else:\n self.objectMaps = {}", "def loa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method calculated the amount to be invoices for the noninvoiced waybills till yesterday for the respective client 1. Creates a new document in the Kinko collection with a unique number, the summed amount, remittance date, and its type (rem/inv) 2. It updates all the packages for respective waybills with a unique k...
def get_invoice(self): # Check if unclosed invoice for the client exists old_inv = connection.Kinko.find_one({'cl': self.cl, 'tid': None, 'typ': TYPE_MAP[self.tab_type]}) inv_num = None # If it does, update its values and update packages ...
[ "def get_remittance(self):\n\n #kinko dict to be updated in Kinko Collection.\n kdict = {\n \"amt\": 0.0,\n \"cl\": unicode(self.cl),\n \"dt\": datetime.datetime.today(),\n \"typ\": TYPE_MAP[self.tab_type],\n \"range\": {\"lt\": self.q_dict[\"cs.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method calculated the amount to be remitted for the nonremiited waybills till yesterday for the respective client 1. Creates a new document in the Kinko collection with a unique number, the summed amount, remittance date, and its type (rem/inv) 2. It updates all the packages for respective waybills with a unique k...
def get_remittance(self): #kinko dict to be updated in Kinko Collection. kdict = { "amt": 0.0, "cl": unicode(self.cl), "dt": datetime.datetime.today(), "typ": TYPE_MAP[self.tab_type], "range": {"lt": self.q_dict["cs.sd"].get("$lt", None), ...
[ "def get_invoice(self):\n\n # Check if unclosed invoice for the client exists\n old_inv = connection.Kinko.find_one({'cl': self.cl, 'tid': None,\n 'typ': TYPE_MAP[self.tab_type]})\n\n inv_num = None\n # If it does, update its values and update ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From an array of int, return a list of molecules in string smile format
def int_to_smile(self, array): all_smi = [] for seq in array: new_mol = [self.indices_token[int(x)] for x in seq] all_smi.append(''.join(new_mol).replace(self.pad_char, '')) return all_smi
[ "def reaction_smiles(self):\n reactants = \".\".join(reactant.smiles for reactant in self.reactants[self.index])\n return \"%s>>%s\" % (reactants, self.mol.smiles)", "def smiles(self) -> List[str]:\n return [d.smiles for d in self.data]", "def smiles_strings_to_nx(smiles_list):\n for smi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do some sanitization of input values, primarily to handle universal Mac builds.
def sanitize(info): if "processor" in info and info["processor"] == "universal-x86-x86_64": # If we're running on OS X 10.6 or newer, assume 64-bit if release[:4] >= "10.6": # Note this is a string comparison info["processor"] = "x86_64" info["bits"] = 64 else: ...
[ "def _sanitise(*args):\n\n ## see TODO file, tag :cleanup:sanitise:\n\n def _check_option(arg, value):\n \"\"\"Check that a single ``arg`` is an allowed option.\n\n If it is allowed, quote out any escape characters in ``value``, and\n add the pair to :ivar:`sanitised`. Otherwise, drop the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the formatted string for the given message and level
def __get_formatted(message, level): if USE_COLOR and LEVELS[level] > 0: return __termcode(LEVELS[level]) + "[" + level + "] " + message + __termcode(0) else: return "[" + level + "] " + message
[ "def to_str(level):\n return {\n MsgLevel.Debug: translate(\"Message\", \"DEBUG\"),\n MsgLevel.Info: translate(\"Message\", \"INFO\"),\n MsgLevel.Warn: translate(\"Message\", \"WARNING\"),\n MsgLevel.Error: translate(\"Message\", \"ERROR\"),\n }[level]", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define abstract properties for both python 2 and 3.
def abstractproperty(func): if sys.version_info > (3, 3): return property(abc.abstractmethod(func)) return abc.abstractproperty(func)
[ "def property(self, p_int): # real signature unknown; restored from __doc__\n pass", "def py2to3(cls):\n if hasattr(cls, '__unicode__'):\n cls.__str__ = lambda self: self.__unicode__()\n if hasattr(cls, '__nonzero__'):\n cls.__bool__ = lambda self: self.__nonzero__()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call function func with the given arguments and measure its runtime. The runtime will be added to the given attribute of target where argument is a `.` separated string of arguments.
def measure_time(target, attribute, func, *args, **kwargs): attributes = attribute.split(".") attribute = attributes.pop() target = reduce(getattr, attributes, target) start = timer() try: return func(*args, **kwargs) finally: value = getattr(target, attribute) setattr(ta...
[ "def calculateRunTime(function, *args):\n startTime = time.time()\n result = function(*args)\n return time.time() - startTime, result", "def _meta_func(args):\n time_start = time.time()\n\n func, data = args\n result = func(data)\n\n time_delta = time.time() - time_start\n return result, t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to time function calls for propagator statistics. The runtime will be added to the given attribute of the class where argument is a `.` separated string of arguments.
def measure_time_decorator(attribute): def wrapper(func): # pylint: disable=missing-docstring return lambda self, *args, **kwargs: measure_time(self, attribute, func, self, *args, **kwargs) return wrapper
[ "def measure_time(target, attribute, func, *args, **kwargs):\n attributes = attribute.split(\".\")\n attribute = attributes.pop()\n target = reduce(getattr, attributes, target)\n start = timer()\n try:\n return func(*args, **kwargs)\n finally:\n value = getattr(target, attribute)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove each element from `rng` for which `pred` evaluates to true by swapping them to the end of the sequence. The function returns the number of elements retained.
def remove_if(rng, pred): j = 0 for i, x in enumerate(rng): if pred(x): continue if i != j: rng[i], rng[j] = rng[j], rng[i] j += 1 return j
[ "def drop_while(arr, pred):\n return list(dropwhile(pred, arr))", "def dropwhile(pred, iterable):\n return Iter(itertools.dropwhile(pred, iterable))", "def remove(pred):\n def _remove_xducer(step):\n def _remove_step(r=Missing, x=Missing):\n if r is Missing: return step()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add `x` to the container if it is not yet contained in it. Returns true if the element has been inserted.
def add(self, x): if x not in self: self._seen.add(x) self._list.append(x) return True return False
[ "def insert(self, x):\n res = False\n i = 0\n while i < self.m:\n idx = self.doublehash(x, i)\n if self.slots[idx] == x:\n return False\n if self.slots[idx] == None or self.slots[idx] == DELETED:\n self.slots[idx] = x\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls `add` for each element in sequence `i`.
def extend(self, i): for x in i: self.add(x)
[ "def add (self, s) :\n for x in s :\n self.n += 1\n self.sum_x += x\n self.sum_xx += x * x", "def add(self, i: int, v: int) -> None:\n while i < self.size:\n self.tree[i] += v\n i += self._lsb(i)", "def add(self, i, w):\n x = i + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a shallow copy the interval set.
def copy(self): return IntervalSet(self)
[ "def copy(self):\n return Interval(self.start, self.end)", "def copy(self) -> 'RangeSet':\n return RangeSet(self)", "def copy(self, no_overlap=None, no_contiguous=None):\n if no_overlap is None:\n no_overlap = self.no_overlap\n if no_contiguous is None:\n no_con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enumerate values in interval set.
def enum(self): for l, u in self: for i in range(l, u): yield i
[ "def __iter__(self):\n return iter(self.intervals)", "def __getitem__(self, i):\n return self.__intervals[i]", "def Intervals(self, numbins):\n if numbins < 1:\n return []\n intervals = [self.start]\n for _ in range(1, numbins):\n intervals.append(intervals[-1] * self.exponent)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use this decorator to indicate that a method should be processed on a separate thread.
def process_in_thread(method): def decorator(*args, **kwargs): t = Thread(target=method, args=args, kwargs=kwargs) t.daemon = True t.start() return decorator
[ "async def _wrap_in_thread(self, method):\n # Not going through event_loop.run_in_executor, because this thread may never\n # terminate.\n threading.Thread(target=method).start()", "def add_thread_method(self, name, method):\n self._thread_methods[name]=lambda *args,**kwargs: self.call...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates child files down to self.max_depth, or until each file is smaller than self.tree.max_count. Parent files are removed, unless self.tree.remove = False
def generate_tree(self, max_depth = None): if max_depth is None: max_depth = self.tree.max_depth else: max_depth -= 1 if max_depth == 0: return self.generate_children() if self.tree.remove: os.unlink(self.source_filename) ...
[ "def __walk_tree(self):\n for root, dirnames, files in os.walk(self.path, topdown=True):\n self.dirCount += 1\n # Create a tuple with the file size, the file name and the files inode (for tracking hard links).\n files = [\n (os.lstat(os.path.join(root, fi)).st_size, os.path.join(root, fi), os...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate tiles for all levels, assuming the tree has been generated using generate_tree() first.
def generate_tiles(self): if self.children: for child in self.children: child.generate_tiles() print "Generating tile for %s using child tiles" % self.bbox self.generate_tile_from_child_tiles() else: print "Generating tile for %s using sour...
[ "def generate_levels(self):\r\n level = (self.root,)\r\n while level:\r\n yield level\r\n level = tuple(child for node in level for child in node.children)", "def generate_treemap(self, rect):\n treemap_lst = []\n remainder = 0\n subtrees = self._subtrees\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SerieSwitch.from_dict_to_list('hello {m}', m=['m', 'M'], R=['R', 'L']})
def from_kwargs_to_list(txt, *args, **kwargs): # beware: 'txt' not in kwargs if args: raise ValueError('No args') return SerieSwitch.from_dict_to_list(txt, kwargs)
[ "def letters_to_vars(st: Iterable, d: dict) -> List:\n return [d[s] for s in st]", "def test_to_args_list(device):\n gate_dict = {\n \"Sgate\": [0.0],\n \"loops\": {\n 0: {\"Rgate\": [1.0], \"BSgate\": [2.0]},\n 1: {\"Rgate\": [3.0], \"BSgate\": [4.0]},\n 2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
name="a | c | d & a | d & e", tags=['d', 'a'] > True
def match(self, name, tags): or_exprs, tags = self.get_compiled(name, tags) # or_exprs = [{'a'}, {'c'}, {'d', 'a'}, {'d', 'e'}] return any(and_expr <= tags for and_expr in or_exprs)
[ "def is_tagged(self,tag_name,element):\n return (tag_name in self.tag2elements.keys()) and (element in self.tag2elements[tag_name])", "def test_parse_restricted_tags():\n invalid_tags = {'*', '**', '***', 'a*', '*a', 'a*a*', '*a*a', '*aa*', 'a**a', '}'}\n combined_tags = valid_tags | invalid_tags\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns all xml comment[name] that match for a student for that qid matricule="123456", qid="2" > ["a", "notb", "notd"] given and 'a' and 'c' were ticked on the copy
def make_tags(self, faq, matricule, qid) -> list: # for that matricule, find out which comments are ticked (eg. A, C) proj, sid = next((proj, proj.Matricule(matricule).to('AmcStudentId')) for proj in self.projects_by_serie.values() if...
[ "def extract_MSQs(line):\n \n tokens = sent_tokenize(line)\n questions = []\n \n for i in range(len(tokens)):\n if tokens[i].endswith('?'):\n q1 = tokens[i] # find first question\n sep = 0 # counter for separation between end of q1 and start q2\n for j in ran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Méthode qui modifie la couleur du texte pour la couleur donné en argument.
def modifier_couleur(self, couleur_texte): self['foreground'] = couleur_texte
[ "def cesar2(texte, decalage):", "def cesar(texte, decalage):", "def refang(self, text: str):", "def __init__(self, cuvant):\n self.__cuvant = cuvant\n self.__text = self.__get_definitie()", "def Text(self) -> str:", "def set_text(self):\n pass", "def get_text():", "def __init__(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Méthode qui modifie la couleur des chiffres selon leur valeur.
def couleur_chiffre (self, chiffre): if chiffre == 0 : self.modifier_couleur('black') elif chiffre == 1 : self.modifier_couleur('green') elif chiffre == 2 : self.modifier_couleur('blue') elif chiffre == 3 : self.modifier_couleur('o...
[ "def getCouleur(self):\r\n return ['pique', 'coeur', 'carreau', 'trefle' ][self.Couleur - 1] # Rectifié\r", "def set_value(plateau, lig, col, val):\r\n assert check_room(plateau, lig, col), \"Erreur: les coordonnées de la tuile sont invalides.\"\r\n assert val >= 0, \"Erreur, la valeur à affecter do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempt to decode the op_return value (if there is one) as a UTF8 string.
def message(self): if self.op_return is None: return None return bytearray.fromhex(self.op_return).decode('utf-8')
[ "def decode_op_return(op_return_hex):\n return binascii.unhexlify(op_return_hex[4:])", "def OperationReturnValue_toString(*args):\n return _libsbml.OperationReturnValue_toString(*args)", "def _get_unicode_value(value: Union[Text, bytes]) -> Text:\n decoded_value = stats_util.maybe_get_utf8(value)\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot the top 16 images (index 0~15) of self.x for visualization.
def show(self): r = 4 f, axarr = plt.subplots(r, r, figsize=(8,8)) counter = 0 for i in range(r): for j in range(r): temp = self.x[counter,:] counter += 1 img = self.x[counter,...
[ "def plot_first_digit(self, ):\n self.plotter.plot_image(self.X_train[0].reshape(28, 28))", "def plot_range(self):\n for i in range(100, 109):\n plt.subplot(330 + (i + 1))\n plt.imshow(self.X_train[i].reshape(28, 28), cmap=plt.get_cmap('gray'))\n plt.title(chr(self.m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate self.x by the values given in shift.
def translate(self, shift_height, shift_width): # TODO: Implement the translate function. Remember to record the value of the number of pixels translated. # Note: You may wonder what values to append to the edge after the translation. Here, use rolling instead. For # example, if you translate 3...
[ "def translateX(shift: float) -> Callable:\n return lambda img: TF.affine(img, 0, (shift * img.size[0], 0), 1, 0)", "def shift_by(self, xshift):\n return Waveform(self.xvec + xshift, self.yvec, self.xtol, order=self.order, ext=self.ext)", "def GridShift(X,xshift,Lx):\n X=X+xshift\n IndexUp=n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rotate self.x by the angles (in degree) given.
def rotate(self, angle=0.0): # TODO: Implement the rotate function. Remember to record the value of # rotation degree. self.rotDegree = angle self.x = rotate(self.x, angle = angle, axes=(0, 1), reshape=False, output=None, order=3, mode='constant', cval=0.0, prefilte...
[ "def rotate_x(self, angle: float):\n self.vertices = list(\n Matrix44.x_rotate(angle).transform_vertices(self.vertices)\n )\n return self", "def rotate_x(self, angle):\n angle *= np.pi / 180\n return self.transform(np.matrix([[1, 0, 0],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flip self.x according to the mode specified
def flip(self, mode='h'): # TODO: Implement the flip function. Remember to record the boolean values is_horizontal_flip and # is_vertical_flip. if mode == 'h': self.is_horizontal_flip = True self.x = np.flipud(self.x) elif mode == 'v': self.is_vertical...
[ "def set_flipped(self, x, y):\n self.pieces[x + (y * self.width)].set_flipped()", "def flipX(self, val=None):\n\t\tif val:\n\t\t\tself.flip['x'] = val\n\t\telse:\n\t\t\tif self.flip['x']:\n\t\t\t\tself.flip['x'] = False\n\t\t\telse:\n\t\t\t\tself.flip['x'] = True\n\t\tself.flipTexture()\n\t\treturn self.fl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assumes other is an intSet Returns a new intSet containing elements that appear in both sets.
def intersect(self, other): # Initialize a new intSet commonValueSet = intSet() # Go through the values in this set for val in self.vals: # Check if each value is a member of the other set if other.member(val): commonValueSet.insert(val) ...
[ "def union(self, other_set):\n \n # copying the this set element to new_set\n new_set = Set(self.table.keys()) \n\n # now adds the other_set elements to the new set if not exist \n for elem in other_set: \n new_set.add(elem) \n\n return new_set", "def inter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MotherNaming(s[,pref=None]) > string return the CaMeLeD s. If prefix is not None, return pref+CaMeLeD.
def MotherNaming(s, pref=None): l=s.split("_") l=["%s%s" % (i[0].upper(),i[1:]) for i in l] return (pref or "") + "".join(l)
[ "def mhc_allele_group_protein_naming(mhc):\n if '-' in mhc and ':' in mhc:\n split_mhc = mhc.split('-')\n mhc_correct_name = split_mhc[0]\n\n # Shorten all allele segment names\n for name_segment in split_mhc[1:]:\n mhc_correct_name = mhc_correct_name + '-' + ':'.join(name_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If we decorate a view function with jsonify, we wrap our success message around it and return the jsonified data. If we catch a werkzeug HTTPException, we pull the status code out of it, and return the response with the found code.
def jsonify(func): @functools.wraps(func) def convert(*args, **kwargs): success = True code = 200 # default status code - success! try: result = func(*args, **kwargs) if isinstance(result, BaseResponse): return result except exc.H...
[ "def json_view(func):\n @wraps(func)\n def _inner(*args, **kwargs):\n ret = func(*args, **kwargs)\n\n if isinstance(ret, HttpResponse):\n return ret\n\n status_code = 200\n\n if isinstance(ret, tuple) and len(ret) == 2:\n ret, status_code = ret\n\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handle the signature of the directive
def handle_signature(self, sig, signode): raise NotImplementedError
[ "def handle_signature(self, sig, signode):\n\n sig_match = rust_arg_re.match(sig.strip())\n print(\"sig\", sig)\n name = sig_match.group(\"var\")\n typ = sig_match.group(\"type\")\n\n signode += addnodes.desc_name(name, name)\n signode += nodes.Text(': ', ': ')\n sig...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handle the signature of the directive
def handle_signature(self, sig, signode): sig_match = rust_arg_re.match(sig.strip()) print("sig", sig) name = sig_match.group("var") typ = sig_match.group("type") signode += addnodes.desc_name(name, name) signode += nodes.Text(': ', ': ') signode += self._build_...
[ "def handle_signature(self, sig, signode):\n raise NotImplementedError", "def document_custom_signature(section, name, method, include=..., exclude=...):\n ...", "def document_model_driven_signature(\n section, name, operation_model, include=..., exclude=...\n):\n ...", "def handle(self, direc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generator function to convert a PIL image to 16bit 565 RGB bytes.
def image_to_data(image): pixels = image.convert('RGB').load() width, height = image.size for y in range(height): for x in range(width): r,g,b = pixels[(x,y)] color = rgb(r, g, b) yield (color >> 8) & 0xFF yield color & ...
[ "def as565(im):\n (r,g,b) = [np.array(c).astype(np.uint16) for c in im.split()]\n def s(x, n):\n return x * (2 ** n - 1) / 255\n return (s(b, 5) << 11) | (s(g, 6) << 5) | s(r, 5)", "def imTo16bit(im):\n assert im.min() >= 0, \"Images must contain only non-negative values\"\n return np.clip(i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the display buffer or provided image to the hardware. If no image parameter is provided the display buffer will be written to the hardware. If an image is provided, it should be RGB format and the same dimensions as the display hardware.
def display(self, image=None): # By default write the internal buffer to the display. if image is None: image = self.buffer # Set address bounds to entire display. self.setAddress() # Convert image to array of 16bit 565 RGB data bytes. # Unfortunate that this ...
[ "def write(self, image):\n raise NotImplementedError()", "def write(self, image, **kwargs):\n return", "def set_image(self, image):\n imwidth, imheight = image.size\n if imwidth != 8 or imheight != 16:\n raise ValueError('Image must be an 8x16 pixels in size.')\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the image buffer to the specified RGB color (default black).
def clear(self, color=(0,0,0)): width, height = self.buffer.size self.buffer.putdata([color]*(width*height))
[ "def clear(self, *args):\n\n black = (0, 0, 0) # default\n\n if len(args) == 0:\n colour = black\n elif len(args) == 1:\n colour = args[0]\n elif len(args) == 3:\n colour = args\n else:\n raise ValueError('Pixel arguments must be given ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a PIL ImageDraw instance for 2D drawing on the image buffer.
def draw(self): return ImageDraw.Draw(self.buffer)
[ "def Draw(im, mode=None):\r\n # try:\r\n # return im.getdraw(mode)\r\n # except AttributeError:\r\n # return ImageDraw(im, mode)\r\n return ImageDraw(im)", "def Create2D(self, p_int, p_int_1, p_int_2, vtkPixelBufferObject, bool):\n ...", "def create_2d(cls, name, w, h, component_fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Path to the AGASC directory. This returns the ``AGASC_DIR`` environment variable if defined, otherwise ``$SKA/data/agasc``.
def default_agasc_dir(): if 'AGASC_DIR' in os.environ: out = Path(os.environ['AGASC_DIR']) else: out = Path(os.environ['SKA'], 'data', 'agasc') return out
[ "def _get_awg_directory(self):\n return os.path.join(self._awgModule.get('awgModule/directory')['directory'][0], 'awg')", "def getapache_srcdir():\n return os.getenv(\"APACHESRC\")", "def get_apk_path():\n ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\"))\n # pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Default main AGASC file ``agasc_dir() / miniagasc.h5``.
def default_agasc_file(): return str(default_agasc_dir() / 'miniagasc.h5')
[ "def default_agasc_dir():\n if 'AGASC_DIR' in os.environ:\n out = Path(os.environ['AGASC_DIR'])\n else:\n out = Path(os.environ['SKA'], 'data', 'agasc')\n return out", "def hdf5_all_data(base='/usr/lib/python2.5/site-packages/MAPdata'):\n for dirname, dirs, fnames in os.walk(base):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In all the commotion, you realize that you forgot to seat yourself. At this point, you're pretty apathetic toward the whole thing, and your happiness wouldn't really go up or down regardless of who you sit next to. You assume everyone else would be just as ambivalent about sitting next to you, too. So, add yourself to ...
def part_2(rules: Rules) -> int: rules_with_myself = add_myself(rules) happiness, _ = max(generate_arrangements(rules_with_myself)) print(f"part 2: optimal arrangement (including myself) brings {happiness} happiness") return happiness
[ "def rules(self):\n\n\t\tprint(\"*There will be 15 questions that are arranged by difficulty.\")\n\t\tprint(\"*Simplier questions go first and are worth less.\")\n\t\tprint(\"*Every question will have four answer choices, of which only one is correct.\")\n\t\tprint(\"*Answering the hardest, 15th question, will make...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows the list of loginattempts by time.
def list_user_login(request): return render(request, "tracking/listUserLog.html", { "userlogs": list(UserLogin.objects.order_by('-Timestamp')), })
[ "def show_login_attempts(self):\n print(f\"You have made {attempts} login attempts\")", "def get_login_attempts(self):\n print(f\"User {self.last_name} tried login attempt(s) on {self.login_attempts} occasions\")", "def read_login_attempts(self):\n\t\tprint(\"Login attempts: \" + str(self.login_at...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called by form while it submitting
def form_submit(self, request: http.Request): self._on_form_submit(request)
[ "def submit(self):\n pass", "def submitClicked(self):\n pass", "def form_submit(self):\n return self.form.validate_on_submit()", "def submitted(self):\n self.status_changed()", "def on_form_submit(self, submit_callback):\n self._submit_callback = submit_callback", "def o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set UID of the widget
def uid(self, value): self._uid = value
[ "def uid(self, uid: int):\n\n self._uid = uid", "def uid(self, uid):\n\n self._uid = uid", "def set_user_id(uid):\n local.user_id = uid", "def set_id(self, uid):\n self.nccl_id = uid\n return self.nccl_id", "def write_uid(self, uid):\n uid = int(uid)\n\n self.ipc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get placeholder of the widget
def placeholder(self): return self._placeholder
[ "def placeholder(boundfield, value):\r\n boundfield.field.widget.attrs[\"placeholder\"] = value\r\n return boundfield", "def get_widget(self):\n\t\treturn None", "def get_embedding_placeholder(self):\n return self.embedding_layer.get_embedding_placeholder()", "def get_placeholder_by_name(self, na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get has_messages property of the widget
def has_messages(self) -> bool: return self._has_messages
[ "def check_message(self):\n logger.debug('check_message: %s', bool(self.get('message')))\n return bool(self.get('message'))", "def has_messages(self, value: bool):\n self._has_messages = value", "def get_visible(self):\n return Message(self._visible)", "def has_queued_messa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set has_messages property of the widget
def has_messages(self, value: bool): self._has_messages = value
[ "def has_messages(self) -> bool:\n return self._has_messages", "def set_valid(self):\n self.set_icon(None)\n self.is_valid = True\n self.message = \"\"\n\n if self.message_field:\n self.message_field.setVisible(False)", "def flag_messages(self, org, messages):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set has_success property of the widget
def has_success(self, value: bool): self._has_success = value
[ "def success(self, success):\n self._success = success", "def is_success(self, is_success):\n\n self._is_success = is_success", "def showTestSuccess(self, test):\n #self._setTestButtonColor(test.id(), self.SUCCESS_COLOR)\n self.test_buttons[test.id()].setState('success')\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get has_warning property of the widget
def has_warning(self) -> bool: return self._has_warning
[ "def has_warning(self):\n return self._has_warning", "def has_warnings_active(self) -> bool:", "def has_validation_warning(self):\n return self._validation_paragraph('warning').present", "def _warning_settings():\n return warnings.showwarning.__name__ == \"_showwarning\"", "def has_warn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set has_warning property of the widget
def has_warning(self, value: bool): self._has_warning = value
[ "def flag_warnings(self):\n if not self._warning_status:\n self._warning_status = True", "def has_warning(self):\n return self._has_warning", "def has_warning(self) -> bool:\n return self._has_warning", "def set_warning(warningTxt):\r\n if not core.does_item_exist(\"Warning#...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set has_error property of the widget
def has_error(self, value: bool): self._has_error = value
[ "def flag_error(self):\n self.error = True\n return", "def has_error(self, has_error):\n\n self._has_error = has_error", "def mark_error(self):\r\n self.status = ERROR", "def on_error(self, instance_text_field, error: bool) -> None:\n\n if error:\n Clock.schedule_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set help string of the widget
def help(self, value: str): self._help = value
[ "def set_help(self, help_text):\n self.__help_str = help_text", "def SetHelpText(*args, **kwargs):\n return _core_.Window_SetHelpText(*args, **kwargs)", "def help_text(self, help_text):\n self._help_text = help_text", "def set_help(self):\n self.view.set_footer(\n urwid....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get child widget by uid
def get_child(self, uid: str): if not self.has_child(uid): raise RuntimeError("Widget '{}' doesn't contain child '{}'.".format(self.uid, uid)) for w in self._children: if w.uid == uid: return w
[ "def get_widget(self, name):\n return self.builder.get_object(name)", "def get_widget(self, name):\n return self.params[name].widget", "def get_widget(self):\n\t\treturn None", "def get_widget(self, name):\n for page in self.pages:\n widgets = page.widgets\n if name ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add single validation rule
def add_rule(self, rule: validation.rule.Rule): self._rules.append(rule) return self
[ "def add_validation_rules(self, runner):\n return", "def add_check(self, rule):\n\n self.rules.append(rule)\n return self", "def addRule(self, *args):\n return _libsbml.Model_addRule(self, *args)", "def add_rule(self, rule):\n self.rules.append(rule)", "def add_rule(self, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate the widget's rules
def validate(self): for rule in self.get_rules(): rule.validate(self.get_val())
[ "def validator(self):\n pass", "def validate(self):\n\n errors = list()\n for widget in self._get_plugin_widgets():\n widget_errors = widget.validate()\n if widget_errors:\n errors.extend(widget_errors)\n\n if errors:\n message_title = \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate a string into plural form.
def t_plural(cls, partial_msg_id: str, num: int = 2) -> str: return lang.t_plural(cls.resolve_msg_id(partial_msg_id), num)
[ "def plural_from_name(name):\n return label_from_name(name) + u's'", "def pluralize(word):\n word = toUtf8(word)\n if inflect_engine:\n return inflect_engine.plural(word)\n \n all_upper = EXPR_UPPERCASE.match(word) != None\n \n # go through the different plural expressions, searching f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gives the fibonacci number at max_num in the sequence, starting at 0.
def fibonacci(max_num): # base case if max_num <= 1: return 1 else: # moving toward base case # calling itself recursively return fibonacci(max_num - 1) + fibonacci(max_num - 2)
[ "def fibonacci_sequence(max):\n term = fibonacci_term(0)\n f = []\n i = 1\n while term < max:\n f.append(term)\n term = fibonacci_term(i)\n i += 1\n return f", "def fib(max_num):\n first, second = 0, 1\n while first < max_num:\n print first,\n first, second ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a base 10 number to a given base up to 16 and returns the result as a string.
def convert_base(num, to_base): digits = '0123456789ABCDEF' result = '' if num < to_base: return digits[num] else: result += convert_base(num/to_base, to_base) + str(digits[num % to_base]) return result
[ "def _dec2base(n, base):\r\n if n < 0 or base < 2 or base > 36:\r\n return \"\"\r\n s = \"\"\r\n while True:\r\n r = n % base\r\n s = digits[r] + s\r\n n = n // base\r\n if n == 0:\r\n break\r\n return s", "def encode(number, base):\n # Handle up to bas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot diagram on the server (plotly)
def plot_graph(self, dataset): data = self.data diagrams = [] for time_stamp, data_tag in dataset: data_x, data_y = [], [] for item in data: data_x.append(item[time_stamp]) data_y.append(item[data_tag]) diagrams.append(Scatter(...
[ "def plot_graph(self) -> None:", "def create_plot(df):\n fig = px.scatter(df, x=\"Date\", y='Airport',\n size=\"Arrivals\", color=\"Arrivals\",\n hover_name=\"Airport\", size_max=60, template='plotly_white')\n fig.update_layout(legend_title_text='Arrivals')\n fig.u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get stack secrets from AWS Secrets Manager
def get_secrets(session, secret_id): secretsmanager = session.client('secretsmanager') secrets = json.loads(secretsmanager.get_secret_value(SecretId=secret_id)['SecretString']) formatted_secrets = [] for (key, value) in secrets.items(): skipped_secrets = [ # cloudformation doesn't need these, so...
[ "def _get_secrets():\n # get encrypted secrets\n storage_client = storage.Client()\n bucket = storage_client.bucket('dotufp-sm')\n blob = bucket.blob('vaqmr-secrets.v2.json.encrypted')\n ciphertext = blob.download_as_string()\n\n # decrypt secrets\n kms_client = kms_v1.KeyManagementServiceClien...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }