query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Calculates the deltas for an output layer.
def calcDeltaOutputLayer(self, Target): return self.prevZ*(1.0-self.prevZ)*(self.prevZ-Target)
[ "def compute_delta_output_layer(self, output_net, target, loss):\n output_layer = self.layers[-1]\n af_derivatives = [neuron.activation_function_derivative() for neuron in output_layer.neurons[:-1]]\n error_derivatives = loss.derivative(target, output_net)\n delta_outputLayer = np.multip...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the deltas for this layer as a hidden layer.
def calcDeltaHiddenLayer(self, WeightedDelta): return self.prevZ*(1.0-self.prevZ)*(WeightedDelta)
[ "def compute_delta_hidden_layer(self, delta_next_layer, currentLayerIndex):\n # delta_layer vector\n delta_layer = np.empty(shape=(len(self.layers[currentLayerIndex].neurons)-1))\n for h in range(len(self.layers[currentLayerIndex].neurons)-1):\n downstream = self.layers[currentLayerI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
As the dict has_key >>> y = Yaco() >>> y['a'] = 1 >>> y.b.c = 2 >>> assert(y.has_key('a')) >>> assert(y.b.has_key('c')) >>> assert(y.has_key('b.c'))
def has_key(self, key): if '.' in key: first, second = key.split('.', 1) return self[first].has_key(second) else: return key in self.keys()
[ "def __hasattr__(self,key):\n\t\tif key in self.__dict__:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False", "def has(self, key):\n return False", "def has_deep_key(obj, key):\n\tif isinstance(key, str):\n\t\tkey = key.split('.')\n\t\t\n\tlast_obj = obj\n\tfor v in key:\n\t\tif not last_obj.has_key(v):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
as getattr, expect for when there is a '.' in the key. it is possible to ask for yacoobject[''] this is a form of leaf loading but means, give me the root. So checking for that
def __getitem__(self, key): #print( key) if key == '': return self if not isinstance(key, str): return self.__getattr__(key) elif not '.' in key: return self.__getattr__(key) else: k1, k2 = key.split('.', 1) return se...
[ "def test_get_object_nested_dotted(basic_object, basic_object_value):\n acc = Accessor(getter=\"value.key.key\")\n assert acc.get(basic_object) == \"value\"", "def __getitem__(self, key):\n key_split = key.split('.')\n current = self\n for k in key_split:\n current = getattr(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
as setattr, except for when there is a dot in the key
def __setitem__(self, key, value): if not '.' in key: return self.__setattr__(key, value) else: k1, k2 = key.split('.', 1) self.__getattr__(k1)[k2] = value
[ "def __setitem__(self, key, value):\n if not isinstance(key, str):\n raise ValueError(f\"{key} is not a string type\")\n self._set_nested(self, key.split('.'), value)", "def assign(self, key, value):\n key_split = key.split('.')\n cur_dict = self\n for k in key_split[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively parse a list & replace all dicts with Yaco objects
def _list_parser(self, old_list): for i, item in enumerate(old_list): if isinstance(item, dict): old_list[i] = Yaco(item) elif isinstance(item, list): old_list[i] = self._list_parser(item) else: pass return old_list
[ "def _populate_attributes(self, obj, traverse_list=True):\n for key, value in obj.__dict__.items():\n if isinstance(value, dict):\n obj.__dict__[key] = self._reconstruct_object(value)\n elif isinstance(value, list):\n obj.__dict__[key] = [self._reconstruct_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load this dict from_file Note it can load the file into a leaf, instead of the root of this Yaco structure. Note the leaf variable is a string, but may contain dots (which are automatically interpreted) >>> import tempfile >>> tf = tempfile.NamedTemporaryFile(delete=True) >>> tf.close()
def load(self, from_file, leaf=None): from_file = os.path.expanduser( os.path.abspath(os.path.expanduser(from_file))) if sys.version_info[0] == 2: with codecs.open(from_file, encoding='utf-8') as F: data = yaml.load(F.read()) else: with open(fr...
[ "def load_from_file(self, file_path: str = None) -> None:\n import json\n if not file_path:\n import os\n file_path = os.path.join(os.getcwd(), 'tree.json')\n with open(file_path, 'r') as file:\n self.tree = json.loads(file.read())", "def load_file(file_path: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare & parse data for export >>> y = Yaco() >>> y.a = 1 >>> y.b = 2 >>> y._c = 3 >>> assert(y._c == 3) >>> d = y.get_data() >>> assert('a' in d) >>> assert('b' in d) >>> assert(not 'c' in d) >>> y._private = ['b'] >>> d = y.get_data() >>> assert('a' in d) >>> assert(not 'b' in d) >>> assert(not '_c' in d)
def get_data(self): data = {} _priv = self.get('_private', []) def check_data(v): if isinstance(v, Yaco): v = v.get_data() elif isinstance(v, list): v = [check_data(x) for x in v] return v for k in list(self.keys()): ...
[ "def prepare_data(self):", "def prepare_data(self, *args, **kwargs):\n return {}", "def load_data(self) -> None:", "def load_data(self, data):\n\n self.id = data[\"id\"]\n self.type = data[\"type\"]\n self.name = data[\"name\"]\n self.short = data[\"short\"]\n self.am...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function moves 2 disks from from_rod to to_rod with the help of mid_rod
def _move_disks(from_rod, to_rod, mid_rod, number_of_disks): if number_of_disks <= 2: # Actually this is not needed. _move_one_step(from_rod, mid_rod) _move_one_step(from_rod, to_rod) _move_one_step(mid_rod, to_rod) print("from_rod: %s", from_rod.arr) ...
[ "def turn_disks(self, board, place1, place2):\n delta = self.create_delta((place1, place2), \"DARK\") #board.board[place1[0]][place1[1]].name)\n current_place = self.sum_2_places(place1, delta)\n while current_place != place2:\n self.turn_disk(board, current_place)\n curre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Generate a simple cubic lattice matching the shape of the provided tempate
def cubic_template(template, spacing=1, connectivity=6, node_prefix='node', edge_prefix='edge'): template = np.atleast_3d(template).astype(bool) # Generate a full cubic network temp = cubic(shape=template.shape, spacing=spacing, connectivity=connectivity, ...
[ "def make_supercell(coords, lattice, size, min_size=-5) -> np.ndarray:\n a, b, c = lattice\n\n xyz_periodic_copies = []\n xyz_periodic_copies.append(coords)\n min_range = -3 # we aren't going in the minimum direction too much, so can make this small\n max_range = 20 # make this large enough, but can ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fonction permettant, pour un catalogue, de créer les balises du teiHeader. Elle récupère des valeurs textuelles signalées dans les gabarits du dossier variables
def creation_header(): tei_header = ET.Element("teiHeader") fileDesc = ET.SubElement(tei_header, "fileDesc") titleStmt = ET.SubElement(fileDesc, "titleStmt") title = ET.SubElement(titleStmt, "title") editor_metadata = ET.SubElement(titleStmt, "editor", role="metadata") persName_editor_metadata...
[ "def _make_header(self):\n header = fits.Header()\n header[\"COMP\"] = (\"Galactic supernova remnants (SNRs)\",\n \"Emission component\")\n header[\"UNIT\"] = (\"Kelvin\", \"Map unit\")\n header[\"CREATOR\"] = (__name__, \"File creator\")\n # TODO:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a new CATVehicle environment. CATVehicle doesnt use controller_manager, therefore we wont reset the controllers in the standard fashion. For the moment we wont reset them.
def __init__(self): rospy.logdebug("Start CATVehicle_ENV INIT...") self.controllers_list = [] self.publishers_array = [] self.robot_name_space = "" self.reset_controls = False # We launch the init function of the Parent Class robot_gaz...
[ "def initialize_scene(self):\n if Time.now() - self.initial_time > 0.45 and self.should_initialize:\n self.should_initialize = False\n self.background_particle_controller = BackgroundParticlesController()\n self.player_controller = PlayerController()\n self.obstacl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that all the publishers are working
def _check_publishers_connection(self): rate = rospy.Rate(10) # 10hz; HOW DOES THIS WORK FOR CATVEHICLE/ self._check_cmd_vel_pub() rospy.logdebug("All Publishers READY")
[ "def _check_all_publishers_ready(self):\n #rospy.logdebug(\"CHECK ALL PUBLISHERS CONNECTION:\")\n self._check_publisher_ready(self._publish_cmd_vel.name,\n self._publish_cmd_vel)\n self._check_publisher_ready(self._publish_takeoff.name,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It will move the car based on the linear and angular speeds given. (no) It will wait untill those twists are achived reading from the odometry topic.
def move_car(self, linear_speed, angular_speed, epsilon=0.05, update_rate=10, min_laser_distance=-1): cmd_vel_value = Twist() # Describes linear motion and angular motion of robot cmd_vel_value.linear.x = linear_speed cmd_vel_value.angular.z = angular_speed rospy.logwarn("CATVehicle Base...
[ "def drive(self, distance, linear_speed):\n\n #Save position\n initPoseX = self.px\n initPoseY = self.py\n\n correction = -.012\n\n #Start driving\n self.send_speed(linear_speed,correction)\n\n #Threshold to stop driving, in meters\n THRESHOLD = .005\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It states based on the laser scan if the robot has crashed or not. Crashed means that the minimum laser reading is lower than the min_laser_distance value given. If min_laser_distance == 1, it returns always false, because its the way to deactivate this check.
def has_crashed(self, min_distance): robot_has_crashed = False dist = self.distsb.data if (dist <= min_distance): rospy.logwarn("CATVehicle HAS CRASHED >>> item = " + str(dist)+" < "+str(min_distance)) robot_has_crashed = True return robot_has_crashed
[ "def __is_terminal(self, reward):\n\n # Initialize the terminal signals to false\n done = 0\n exit_cond = 0\n\n # Find readings that are below the set minimum. If there are multiple readings below the threshold, a crash\n # likely occurred and the episode should end\n # pri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all local extremum indexes. The output extremum_indexes will hold the locations in y which hold the extremums, it will also be sorted from biggest extremum of y to smallest extremum of y. This function considers a localmaximum to be a point which is either bigger then both its neighbours or bigger then or and equa...
def my_local_extremum(y, min_or_max, do_plot=True): if min_or_max == 'max': y_prime = y elif min_or_max == 'min': y_prime = -y else: sys.exit("You must declare what min_or_max of extremums you're looking for, max or min!") dy = np.diff(y_prime) indicator = np.diff(np.sign(dy...
[ "def local_max(x, threshold=1e-5):\n maxima = np.r_[True, x[1:] > x[:-1]] & np.r_[x[:-1] > x[1:] , True]\n # select all local maxima above the threshold\n maxima_f = maxima & np.r_[x > threshold , True][:-1]\n peak_indices = np.where(maxima_f==True)[0]\n return np.array(peak_indices)", "def find_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset all motor bounds to default. It writes directly to the .Experiment file
def reset_bounds_to_default(self) -> None: self.write_to_experiment_file(self.DEFAULT_BOUNDS, is_motor_bounds=True)
[ "def setAllZero(self):\n self.robot.set_joint([0,0,0,0,0])\n self.robot.save_config()", "def soft_reset(self) -> None:\n data = self.build_current_file(\n self.experiment_file_dict[\"simulated\"],\n self.experiment_file_dict[\"kafka_topic\"],\n self.experiment...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to print the current bounds
def list_bounds(self) -> None: print("") print( "Mu = {}".format(self.experiment_file_dict["motors"]["mu"]["bounds"]) ) print( "Eta = {}".format(self.experiment_file_dict["motors"]["eta"]["bounds"]) ) print( "Chi = {}".f...
[ "def print(self):\n\n raise NotImplementedError(\"Printing of BoundsList is not ready yet\")", "def print_input_indicator_bounds(self):\n \n txt = \"\\* (%d, %d) *\\\\\\n\" % (self.x, self.y)\n for i in sorted(self.input_fanout_bounds):\n txt += \"f_%d_%d_%d <= %d\\n\" %...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if the sentence has less than `min_len` number of words
def is_short_sentence(s:str, min_len=8) -> str: return len(s.split(' ')) < min_len
[ "def check_word_length(word: str, min_length: int, max_length: int)\\\n -> bool:\n return min_length <= len(StringManipulation.\n strip_special_chars(word)) <= max_length", "def _is_len_ok(self):\r\n if len(self._WORD)<=MAX_LEN: return True\r\n else:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if the sentence passes the MIN_LINE_LENGTH configuration Redefine this function with desired helper functions, returning true if you want to keep the line
def filter_line(line:str) -> bool: fails = is_short_sentence(line, MIN_LINE_LENGTH) return not fails
[ "def is_line_long_enought(line):\n\n return len(line.split()) >= LONG_LINE_THRESHOLD", "def _CheckLineLength(self, last_token, state):\n # Start from the last token so that we have the flag object attached to\n # and DOC_FLAG tokens.\n line_number = last_token.line_number\n token = last_token\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From a chunk of characters, decide whether to return the processed characters or Nothing. If the input is the empty string "", raise StopIteration
def read_outcomes(chars:str) -> Union[str, None]: if chars == '': raise StopIteration line = process_line(chars) if filter_line(line): return line return None
[ "def consume_str_until(it: Iterator[str], stop: str) -> None:\n while next(it) != stop:\n pass\n return", "def _parse_till_unescaped_char(stream, chars):\n rv = \"\"\n while True:\n escaped = False\n for c in chars:\n if EscapeCharToken.starts_here(stream, c):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract `n` chars from opened file `f`
def get_chars(n:int, f) -> Union[str, None]: chars = f.read(n) return read_outcomes(chars)
[ "def extract_chars(infile, n=10000):\n reader = partial(get_chars, n)\n return read_on(reader, infile)", "def chars(count):\n\n global offset\n\n bytes=midifile[offset:offset+count]\n offset+=count\n return bytes", "def read_nchars(string, n=1):\n return string[:n]", "def string_from_char...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read from an open file `f` according to the function `reader`
def read_on(reader, f): while True: try: line = reader(f) except StopIteration: break if line is not None: yield line
[ "def read_file(\n file_path: Union[str, pathlib.Path],\n reader_name: Optional[str] = None,\n **reader_args: Any,\n) -> Reader:\n with open(file_path, mode=\"rb\") as input_stream:\n return read_stream(input_stream, reader_name)", "def fileReader(self,f):\n\n for line in f:\n yield line...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract `n` characters in batches from opened `infile`
def extract_chars(infile, n=10000): reader = partial(get_chars, n) return read_on(reader, infile)
[ "def chunks(input, n):\n for i in range(0, len(input), n):\n yield input[i:i + n]", "def chunk_it( filepath, nr_chunks ) :\n \n file = open(filepath, \"r\")\n sample_text = file.readlines()\n \n import math\n line_length = math.ceil(len(sample_text) / nr_chunks)\n\n line_chunks = []...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract sentences from a file into a new file indicated by `outfname`.
def extract_sentences_to_file(infile, outfname:str): out = open(outfname, 'x') linegen = extract_lines(infile) for line in linegen: out.write(line + "\n") out.close()
[ "def extract(infile, outfile):\n lines = infile.readlines()\n sentences = []\n cur_sentence = []\n for idx, line in enumerate(lines):\n line = line.strip()\n if not line:\n # if we're currently reading a sentence, append it to the list\n if cur_sentence:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main function for creating the outdir and saving the processed sentences to that file
def main(infile, outdir): outfname = Path(infile).stem + '.txt' outdir = Path(outdir) outdir.mkdir(parents=True, exist_ok=True) outfile = outdir / outfname out_path = extract_sentences_to_file(infile, outfile) return out_path
[ "def write_file(tweets):\n with open((folderlink + \"markov_sentences.txt\"), \"w\") as text_file:\n for tweet in tweets:\n text_file.write (tweet + '\\n')\n with file ((folderlink + \"markov_sentences.txt\"), 'r') as f:\n text = f.read()\n text_model = markovify.NewlineText(text)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of possible diagnosis, if any, given a list of symptoms. For example, if german measles has the symptoms 'runny nose', 'fever', 'headache' and 'rash', the system will return a list containing a dict with the diagnosis. symptoms = ['runnynose', 'fever', 'headache', 'rash'] doctor = Doctor('medical') resul...
def diagnose(self, symptoms, age_group=None): prolog = Prolog() if age_group is not None: prolog.assertz('age_group(patient,%s)' % age_group) for symptom in symptoms: prolog.assertz('symptom(patient,%s)' % symptom) prolog.consult(self.prolog_file) return list(prolog.query('hypothesis...
[ "def diagnose(self, symptoms):\r\n\r\n def check_symptom(node):\r\n \"\"\"Recursive function that check on every node if the patient have\r\n this symptom and return the illness which corresponds to these\r\n symptoms \"\"\"\r\n\r\n if not node.positive_child:\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convenience wrapper around diagnose that returns only one result. If no results are found, this returns None.
def diagnose_one(self, symptoms, age_group=None): try: return self.diagnose(symptoms, age_group=age_group)[0] except IndexError: return None
[ "def check_response(self):\n if self.SIMULATION == True:\n return \"Simulation without instrument\", self.get_measurements()\n elif self.SIMULATION == False: \n try: \n response = self.inst.query(\"*IDN?\")\n #print(f\"[INFO] Instrument response to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
classpaddleslim.nas.RLNAS(key, configs, use_gpu=False, server_addr=("", 8881), is_server=True, is_sync=False, save_controller=None, load_controller=None, kwargs)
def test_RLNAS1(self): port = 8773 # config = [('MobileNetV2BlockSpace', {'block_mask': [0]})] config = [("ResNetBlockSpace2", {"block_mask": [0]})] rlnas = RLNAS( key="lstm", configs=config, server_addr=("", port), is_sync=False, ...
[ "def train_nasnetmobile():\n\n # load data\n training_sets = load_augmented_dataset()\n\n # build models\n model_nas = build_nasnet()\n\n baseWeights_t = model_nas.get_weights()\n\n # NOTE: You can still leave this alone if you've only downloaded the fully augmented set.\n for training_set in t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if this is a channel (for the benefit of tempalates)
def is_channel(self): return True
[ "def single_channel():\n return True", "def isInChannelBox(self):\n \n pass", "def is_channel(channel):\n return channel.startswith('#')", "def is_channel(self, channel_name):\n if ',' in channel_name or ' ' in channel_name:\n return False\n\n if len(channel_name) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates tags or increments tag counts as neccesary.
def _add_tags(self): if self.version != 'live': return tags = [t.strip() for t in self.tags_text.split(',')] tags = list(set(tags)) for tag_name in tags: tag_slug = slugify(tag_name) if tag_slug: try: tag = Tag.ob...
[ "def add_tag(tag, tag_count):\n if tag in tag_count:\n tag_count[tag] += 1\n else:\n tag_count[tag] = 1", "def tag_updater(self, tags):\n for tag in tags:\n #check if the tag exists\n exists = False\n tag = self.tags.find_one({'TagName': tag})\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns maximum number of guests you can satisfy
def max_guests(appetite: list[int], cake: list[int]) -> int: guest_count = 0 appetite_index = len(appetite) - 1 cake_index = len(cake) - 1 while appetite_index >= 0 and cake_index >= 0: appetite_size = appetite[appetite_index] cake_size = cake[cake_index] if cake_size >= appet...
[ "def guestCount(self):\n return len( self.guests )", "def getMaxTaskCount():", "def max_individuals(self) -> int:\n return self.group_size.upper * self.groups_allowed", "def maximum_number_of_machines(self) -> int:\n return pulumi.get(self, \"maximum_number_of_machines\")", "def get_num...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes and returns the [calculated] value on the given model instance.
def __get__(self, model_instance, model_class): if model_instance is None: return self return self.calc_fn(model_instance)
[ "def calcModel(self):\n pass", "def evaluate(self, *args, **kwargs):\n\n \n return self.model.evaluate( *args, **kwargs)", "def dynamic_model(self, input_val: float) -> float:\n pass", "def get_value(self):\n self.update_value()\n return self.value * self.calibration", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
run_net(inputs, parameter) Parameters = [R, p_inE/I, f_in, f_EE, f_EI, f_IE, f_II, tau_ex, tau_inh]
def run_net(inputs, **parameter): #---- set numpy random state for each run---- np.random.set_state(np_state) # -----parameter setting------- n_ex = 1600 n_inh = int(n_ex/4) n_input = MNIST_shape[1]*coding_n n_read = n_ex+n_inh R = parameter['R'] f_in = parameter['f_in'] f_EE ...
[ "def run_net(inputs, **parameter):\n\n # ---- set numpy random state for each run----\n np.random.set_state(np_state)\n\n # -----parameter setting-------\n n_ex = 1600\n n_inh = int(n_ex / 4)\n n_input = MNIST_shape[1] * coding_n\n n_read = n_ex + n_inh\n\n R = parameter['R']\n f_in = par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method return Djangolike formset dictionary using the model's description.
def get_model_as_formset(self, client_id): # Basement formset = { 'form-TOTAL_FORMS': str(len(self.storage)), 'form-INITIAL_FORMS': u'0', } # Fill the formset for record_index, record in enumerate(self.storage): prefix = 'form-%i' % record_...
[ "def get_formset(self):\n result = generic_inlineformset_factory(\n self.inline_model, **self.get_factory_kwargs()\n )\n return result", "def get_formset(self, request, obj=None, **kwargs):\n if self.declared_fieldsets:\n fields = flatten_fieldsets(self.declared_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert a record into the model. Parameter 'card' has an information obtained from UI dialogs.
def insert_new(self, card): handlers = { 'flyer': (self.prepare_flyer, 'card_ordinary'), 'test': (self.prepare_proxy('test'), 'card_ordinary'), 'once': (self.prepare_proxy('once'), 'card_ordinary'), 'abonement': (self.prepare_abonement, 'card_ordinary'), ...
[ "def insert_card(self, card):\r\n self.cards.insert(0, card)", "def add_card(card_data):\n print(\"Adding new card\")\n card = Card(name=card_data[\"name\"],\n hero=card_data[\"playerClass\"],\n img_url=card_data[\"img\"],\n dbfId=card_data[\"dbfId\"],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load mock file that simulates an API response.
def load_mock_response(file_name): with open('test_data/' + file_name, mode='r') as f: return json.loads(f.read())
[ "def load_mock_response(file_name: str) -> str:\n with open(f'test_data/{file_name}', encoding='utf-8') as mock_file:\n return mock_file.read()", "def load_mock_response(file_name: str) -> str:\n with open(f'test_data/{file_name}', mode='r', encoding='utf-8') as mock_file:\n return mock_file.r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all tools of the given type, this could be used for reporting available tools.
def get_all_tools(project, user_paths, tool_type='synthesis'): if tool_type == 'synthesis': registry = synthesis_tool_class_registry elif tool_type == 'simulation': registry = simulation_tool_class_registry else: log.error( 'Invalid tool type specified: {0}'.format(tool_t...
[ "def get_tools(self):\n return []", "def get_tools(self):\r\n\t\tlogger.debug(\"Getting the tools\")\r\n\t\t\r\n\t\treturn db.get_items('tools')", "def list(cls):\n tools = []\n _tool_names = cls._api_get_tools()\n for tool_name in _tool_names:\n _result = cls._api_get_too...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force the quantity to always be a decimal
def quantity(self, value): self._quantity = Decimal(value)
[ "def qty_or_zero(self) -> Decimal:", "def is_qty_decimal(self):\n return self._is_qty_decimal", "def with_qty(self, qty: Decimal) -> \"Price\":", "def qty_or_none(self) -> Optional[Decimal]:", "def with_qty(self, qty: Decimal) -> \"Money\":", "def format_quantity(self, quantity):\n precision...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force the price to always be a decimal
def price(self, value): self._price = Decimal(value)
[ "def decimal_price(self):\n return self._decimal_price", "def decimal_price(self, decimal_price):\n\n self._decimal_price = decimal_price", "def ask_price(self):\n return try_(Decimal, self.ask_price_, default_=Decimal(\"9\" * 32))", "def force_decimal(amount):\n if not isinstance(amou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force the transaction_date to always be a date
def transaction_date(self, value): if value: self._transaction_date = ( parse(value).date() if isinstance(value, type_check) else value )
[ "def settlement_date(self, value):\n if value:\n self._settlement_date = (\n parse(value).date() if isinstance(value, type_check) else value\n )", "def transaction_date(self, transaction_date):\n if self._configuration.client_side_validation and transaction_date ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force the settlement_date to always be a date
def settlement_date(self, value): if value: self._settlement_date = ( parse(value).date() if isinstance(value, type_check) else value )
[ "def settlement_date(self) -> datetime.date:\n return self.__settlement_date", "def transaction_date(self, value):\n if value:\n self._transaction_date = (\n parse(value).date() if isinstance(value, type_check) else value\n )", "def date_assign(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force the execution_time to always be a datetime
def execution_time(self, value): if value: self._execution_time = ( parse(value) if isinstance(value, type_check) else value )
[ "def execution_time(self, execution_time):\n if execution_time is None:\n raise ValueError(\"Invalid value for `execution_time`, must not be `None`\")\n\n self._execution_time = execution_time", "def execution_time(self, execution_time):\n self._execution_time = execution_time", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The total effect of the net_affecting charges (note affect vs effect here). Currently this is single currency only (AMAAS110). Cast to Decimal in case the result is zero (no net_affecting charges).
def charges_net_effect(self): return Decimal( sum( [ charge.charge_value for charge in self.charges.values() if charge.net_affecting ] ) )
[ "def total_change(self) -> float:\n return sum([value * number for value, number in self._change.items()])", "def total(self):\n total_price = self.get_total_amount()\n discounts = self.get_total_discount()\n\n return total_price - discounts", "def discount_amount(self):\r\n c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sendet mithilfe von Pushsafer eine Nachricht
def send_push_nachricht(message: str, pushsafer_code: str, title: str = "Termin Verfuegbar!"): # all device = "a" # Alarm icon = 2 # Buzzer sound = 8 # 3mal vibration = 3 # nicht automatisch loeschen ttl = 0 # Hoechste priority = 2 # nach 60 erneut senden bis gesehen...
[ "def delivery(self, message):", "def sendMessage(newMessage, withoutWeb=False):", "def receive(self, msg):", "def msg(self, message):\n\n message = PushoverMessage(message)\n self.messages.append(message)\n return message", "def notify(self, message):\n pass", "def send_msg(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates the panel with observables from the perspective of the econometrician.
def generate_panel(self): self.PanelData = self.RawData.filter(['ID', 'X', 'Z', 'W', 'R', 'β', 'LFP', 'H'], axis=1)
[ "def plot_multipanel(self, nophase=False, letter_labels=True):\n\n if nophase:\n scalefactor = 1\n else:\n scalefactor = self.phase_nrows\n\n figheight = self.ax_rv_height + self.ax_phase_height * scalefactor\n\n # provision figure\n fig = pl.figure(figsize=(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Amplia una imagen. Según el valor de url_api, la amplia con la API de EnhanceNet o devuelve la imagen ampliada con el algoritmo de ampliación bicúbica. También se amplia con el algoritmo bicúbico si no es posible acceder a la API o se presenta alguna excepción en el intento.
def ampliar(imagen, extension, factor_aumento, url_api=None): if url_api is None: return _ampliar_local(imagen, extension, factor_aumento) else: # preprocesamos la imagen imagen_formato_PIL = procesado_imagenes.numpy_array_normalizado_a_imagen(imagen) imagen_base64 = procesado_i...
[ "async def astronomy_picture(self, ctx: Context) -> None:\n async with self.session.get(f\"https://api.nasa.gov/planetary/apod?api_key={NASA_API}\") as resp:\n data = await resp.json()\n\n if len(data[\"explanation\"]) > 2048:\n description = f\"{data['explanation'][:2045].strip(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The first time you call this you must set entityUrl. After that you can omit it and it will be read from the auth config file. If entityUrl is None and there is no auth config file, an error will be raised. Upon instantiation a TentApp object will perform server discovery on the entityUrl, so you should expect a short ...
def __init__(self,entityUrl): debugMain('init: entityUrl = %s'%entityUrl) self.entityUrl = entityUrl # details of this app # basic self.name = 'python-tent-client' self.description = 'description of my test app' # urls self.url = 'http://zzzzexample.c...
[ "def __init__(self):\n super().__init__()\n\n etc_conf_names = ('app.conf', 'app.local.conf')\n conf_paths = [os.path.join(APP_DIR, 'etc', c) for c in etc_conf_names]\n\n user_config_path = os.path.join(\n os.path.expanduser('~'),\n '.config',\n 'url_mana...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set a value for one of the profile types on your profile.
def putProfile(profileType,value): # PUT /profile/$profileType pass
[ "def test_update_profile_type(self):\n pass", "def save_user_profile(self, user_type):\n if user_type == 'user':\n self.userobj.userprofile.is_user = True\n self.userobj.userprofile.save()\n elif user_type == 'superuser':\n self.userobj.userprofile.is_superuse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Begin following the given entity. Note that unlike the other followrelated methods, this one uses an entity URL instead of an id.
def follow(self,entityUrl): # POST /followings debugMain('follow') resource = '/followings' requestUrl = self.apiRootUrls[0] + resource headers = dict(DEFAULT_HEADERS) headers['Content-Type'] = 'application/vnd.tent.v0+json' debugRequest('following via: %s'%reque...
[ "def follow(self, followerId, followeeId):\n\n if followerId == followeeId:\n return\n\n self.follows[followerId].add(followeeId)", "def follow(self, followerId: int, followeeId: int) -> None:\n if followerId not in self.users:\n self.users[followerId]=Twitter.Node()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the entities I'm following. Any additional keyword arguments will be passed to the server as request parameters.
def getFollowings(self,id=None,**kwargs): # GET /followings [/$id] debugMain('getEntitiesIFollow') if id is None: return self._genericGet('/followings',**kwargs) else: return self._genericGet('/followings/%s'%id,**kwargs)
[ "def request_follows(self, *args, **kwargs):\n for follow_type in [\"following\", \"followers\"]:\n # request followers and following of the user\n yield self.request_follow(follow_type, *args, **kwargs)", "def _QueryFollowers():\r\n tasks = []\r\n for vp_dict in request['viewpo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an attachment from a post.
def getPostAttachment(self,id,filename): # GET /posts/$id/attachments/$filename pass
[ "def blog_get_mkd_attachment(post):\n attach = dict()\n try:\n lead = post.rindex(\"<!-- \")\n data = re.search(g_data.TAG_RE, post[lead:])\n if data is None:\n raise VimPressFailedGetMkd(\"Attached markdown not found.\")\n attach.update(data.groupdict())\n attach...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a generator which iterates through all of the user's followers, newest first, making multiple GET requests behind the scenes.
def generateFollowers(self): for f in self._genericGenerator(self.getFollowers): yield f
[ "def _QueryFollowers():\r\n tasks = []\r\n for vp_dict in request['viewpoints']:\r\n if vp_dict.get('get_followers', False):\r\n start_key = vp_dict.get('follower_start_key', None)\r\n tasks.append(Viewpoint.QueryFollowers(client,\r\n vp_dict['vi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
element is the subdocument key name.
def get_subdocument_key(crawler=None, parser_id=None): for extractor in crawler['parsers']: if extractor.get("parser_id") == parser_id: for selector in extractor.get('data_selectors', []): if selector.get('selector_attribute') == 'element': ...
[ "def GetSubkeyByName(self, name):", "def key(self):\n raise NotImplementedError(\"'key' not implemented for Element subclass\")", "def sub_object_id_key(self) -> str:\n return \"name\"", "def GetSubkeyByIndex(self, index):", "def GetSubkeys(self):", "def handler_key(self):\r\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
processing a heartbeat packet
def test_process_packet_heartbeat(self): pkt = {'type': 'heartbeat', 'endpoint': '' } self.ns.process_packet(pkt) assert not self.environ['socketio'].error.called
[ "def heartbeat_thread_func(self):\n while True:\n heartbeat = json.dumps({\"type\": \"HEARTBEAT\",\n \"issued\": time.time() * 1000})\n log.info(\"Sending ACL heartbeat %s\" % heartbeat)\n self.pub_lock.acquire()\n self.pub_socket...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
processing an event packet
def test_process_packet_event(self): pkt = {'type': 'event', 'name': 'woot', 'endpoint': '', 'args': []} self.ns.process_packet(pkt) assert not self.environ['socketio'].error.called # processing an event packet with message id and ack ...
[ "def process(self, pkt):\n pass", "def process_event(self, st):\n self.server.process_event(st)", "def _process_event(self, event: Dict[str, Any]) -> None:\n try:\n content = event[\"content\"]\n _LOGGER.debug(\"Received event: %s\", content)\n except KeyError:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
processing a ack packet
def test_process_packet_ack(self): pkt = {'type': 'ack', 'ackId': 140, 'endpoint': '', 'args': []} self.ns.process_packet(pkt) assert not self.environ['socketio'].error.called
[ "def ACK_IN(self, pkt):\r\n # check if type is ACK\r\n if pkt.getlayer(GBN).type == 0:\r\n log.error(\"Error: data type received instead of ACK %s\", pkt)\r\n raise self.SEND()\r\n else:\r\n log.debug(\"Received ACK %s\", pkt.getlayer(GBN).num)\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test calling a method that doesn't exist
def test_method_not_found(self): pkt = {'type': 'event', 'name': 'foo', 'endpoint': '/chat', 'args': [] } self.ns.process_packet(pkt) kwargs = dict( msg_id=None, endpoint='/woot', quiet=False ...
[ "def no_such_method(self):\n\t\tself.write_line(\"Error: XXX - No such method\")", "def test_run_MethodNotFound(self):\n i = JsonInterface(RPCSystem())\n response = self.successResultOf(run(i, 'foo.bar'))\n self.assertEqual(response['error']['code'], MethodNotFound.code)\n self.assertE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test_create_show_update_delete_firewall_admin_down Create firewall with a router, admin state down update firewall to be admin state up update firewall to be admin state down delete firewall
def test_create_show_update_delete_firewall_admin_down(self): # Create tenant network resources required for an ACTIVE firewall network = self.create_network() subnet = self.create_subnet(network) router = self.create_router( data_utils.rand_name('router-'), admin...
[ "def test_create_show_update_delete_firewall_admin_down_no_router(self):\n\n # Create firewall\n body = self.firewalls_client.create_firewall(\n name=data_utils.rand_name(\"firewall\"),\n firewall_policy_id=self.fw_policy['id'],\n router_ids=[],\n admin_stat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test_create_show_update_delete_firewall_admin_down Create firewall with a router, admin state down update firewall to be admin state up update firewall to be admin state down delete firewall
def test_create_show_update_delete_firewall_admin_down_no_router(self): # Create firewall body = self.firewalls_client.create_firewall( name=data_utils.rand_name("firewall"), firewall_policy_id=self.fw_policy['id'], router_ids=[], admin_state_up=False) ...
[ "def test_create_show_update_delete_firewall_admin_down(self):\n # Create tenant network resources required for an ACTIVE firewall\n network = self.create_network()\n subnet = self.create_subnet(network)\n router = self.create_router(\n data_utils.rand_name('router-'),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function prints today's weather
def today_weather(city_name): output = ( datetime.date.today().strftime("%d/%m/%Y") + "Temperature: " + "{}".format( get_weather(city_name, datetime.date.today().strftime("%d/%m/%Y")) ) ) print(output)
[ "def full_broadcast(city_name):\n today_weather(city_name)\n for i in range(1, 4):\n output = (\n (datetime.date.today() + datetime.timedelta(days=i)).strftime(\"%d/%m/%Y\")\n + \"Temperature: \"\n + \"{}\".format(\n get_weather(\n city...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function prints the weather for today and 3 more days.
def full_broadcast(city_name): today_weather(city_name) for i in range(1, 4): output = ( (datetime.date.today() + datetime.timedelta(days=i)).strftime("%d/%m/%Y") + "Temperature: " + "{}".format( get_weather( city_name, ...
[ "def today_weather(city_name):\n output = (\n datetime.date.today().strftime(\"%d/%m/%Y\")\n + \"Temperature: \"\n + \"{}\".format(\n get_weather(city_name, datetime.date.today().strftime(\"%d/%m/%Y\"))\n )\n )\n print(output)", "def weather_daily():\n #Fetches d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function return the checksum for a given city and date
def checksum(city_name, date): second_part = 0 first_part = sum(ord(c) - ord("a") + 1 for c in city_name.lower()) date = date.split("/") for i in date: for j in i: second_part += int(j) return "{}.{}".format(first_part, second_part)
[ "def _get_checksum(self, arg):", "def _checksum(addr):\n return checksum(addr)[-constants.check_sum_len_bytes :]", "def _calc_checksum(self, method, querystring):\n blob = method + querystring + self.api_secret\n logger.debug(f\"Creating checksum from {blob}\")\n return hashlib.sha1(blob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a game tree into nerual network input
def convert_game(game_tree): root_node = game_tree.get_root() if root_node.is_leaf(): raise ValueError("no moves available") # iterate moves until game end or leaf node arrived current_node = root_node while True: features = extract_features(current_node) r = curren...
[ "def build_tree(self) -> None:\r\n for i in range(1, 51):\r\n filename = 'data/reversi_games/' + str(i) + '_w.txt'\r\n file = open(filename)\r\n lines = file.readlines()\r\n moves = []\r\n previous_player = 1\r\n for line in lines:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return clusters of uniprot id that are cluster at the leaf node layer
def get_uniprot_clusters(): json_str = "" for line in open(gpcr_tree_path, 'r'): json_str += line gpcr_tree = json.loads(json_str) uniprot_clusters = [] for a in gpcr_tree["children"]: for b in a["children"]: cluster = [] for uniprot in b["children"]: uniprot_id = (str(uniprot['name']) + "_human"...
[ "def get_clusters():\n return clusters", "def get_nodes_in_cluster(self, context, cluster_id):", "def cluster_ids(self):\n return self.model.cluster_ids", "def atlas_clusters():\n pass", "def get_clusters(self):\n clusters = defaultdict(list)\n for node in self.ds:\n le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverse the list of projects and samples Generator that yields tuples consisting of (SampleSheetProject,SampleSheetSample) pairs
def walk(self): for project in [self.get_project(name) for name in self.project_names]: for sample in [project.get_sample(idx) for idx in project.sample_ids]: yield (project,sample)
[ "def samples_in_multiple_projects(self):\n # Look for samples with multiple projects\n samples = {}\n for project,sample in self.walk():\n if sample.sample_id not in samples:\n samples[sample.sample_id] = []\n samples[sample.sample_id].append(project.name)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of samples which have multiple associated barcodes
def samples_with_multiple_barcodes(self): # Look for samples with multiple barcodes multiple_barcodes = {} for project,sample in self.walk(): if len(sample.barcode_seqs) > 1: multiple_barcodes[sample.sample_id] = \ [s for s in sample.barcode_seqs] ...
[ "def test_extract_barcodes_from_mapping(self):\r\n\r\n # cases that are valid\r\n expected = {'FV9NWLF.01.EVGI8': 'TCGAGCGAATCT',\r\n 'FV9NWLF.01.DROG9': 'TAGTTGCGAGTC',\r\n 'FV9NWLF.01.DZTVJ': 'TCGAGCGAATCT',\r\n 'FV9NWLF.01.DI8SC': 'TCTGCTAGAT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of samples which are in multiple projects
def samples_in_multiple_projects(self): # Look for samples with multiple projects samples = {} for project,sample in self.walk(): if sample.sample_id not in samples: samples[sample.sample_id] = [] samples[sample.sample_id].append(project.name) mult...
[ "def samples_in_project(self,project_name):\n project = self.__projects[self.__project_dir(project_name)]\n samples = []\n for sample_name in project:\n if sample_name.startswith('Sample_'):\n samples.append(sample_name.split('_')[1])\n samples.sort()\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of samplesheet lines which are invalid
def has_invalid_lines(self): # Convience variables sample_id = self._sample_sheet.sample_id_column sample_name = self._sample_sheet.sample_name_column sample_project = self._sample_sheet.sample_project_column # Look at first line to see which items have been provided line...
[ "def has_invalid_barcodes(self):\n invalid_lines = list()\n indices = list()\n for indx in ('index','index2'):\n if indx in self._sample_sheet.data.header():\n indices.append(indx)\n if indices:\n for line in self._sample_sheet.data:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of lines with invalid barcodes
def has_invalid_barcodes(self): invalid_lines = list() indices = list() for indx in ('index','index2'): if indx in self._sample_sheet.data.header(): indices.append(indx) if indices: for line in self._sample_sheet.data: for indx in i...
[ "def barcode_mismatches(self):\n raise NotImplementedError()", "def getCellBarcodes(dem_file_path):\n with open(dem_file_path) as csvfile:\n in_txt = csv.reader(csvfile, delimiter = '\\t')\n for line in in_txt:\n cell_barcodes = line[1: ]\n cell_barcodes = [x.split('_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if text file contains any 'invalid' characters
def has_invalid_characters(self): return has_invalid_characters(text=self._sample_sheet.show())
[ "def has_invalid_characters(filen=None,text=None):\n if filen is not None:\n with open(filen,'r') as fp:\n for line in fp:\n for c in set(line.replace('\\n','').replace('\\t','')):\n if ord(c) > 127 or ord(c) < 32:\n return True\n else...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a sample sheet barcode sequence is valid Valid barcodes must consist of only the letters A,T,G or C in any order, and always uppercase. 10xGenomics sample set IDs of the form e.g. 'SIP03C9' or 'SIGAB3' are also considered to be valid.
def barcode_is_valid(s): return (bool(re.match(r'^[ATGC]*$',s)) or barcode_is_10xgenomics(s))
[ "def test_check_barcode(self):\r\n self.assertEqual(check_barcode('AA', None, ['AA']), (False, 'AA',\r\n False))\r\n self.assertEqual(check_barcode('GCATCGTCCACA', 'golay_12',\r\n ['GCATCGTCAACA']), (2, '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if sample sheet barcode is 10xGenomics sample set ID 10xGenomics sample set IDs of the form e.g. 'SIP03C9' or 'SIGAB3' are also considered to be valid.
def barcode_is_10xgenomics(s): return bool(re.match(r'^SI\-[A-Z0-9]+\-[A-Z0-9]+$',s))
[ "def barcode_is_valid(s):\n return (bool(re.match(r'^[ATGC]*$',s))\n or barcode_is_10xgenomics(s))", "def check_sample_id(value: str, length: int = 15) -> bool:\n if len(value) != length:\n return False\n components = value.split(\"-\")\n if len(components) != 3:\n return Fals...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check for sample sheet problems and issue warnings
def check_and_warn(sample_sheet=None,sample_sheet_file=None): # Acquire sample sheet linter instance linter = SampleSheetLinter(sample_sheet=sample_sheet, sample_sheet_file=sample_sheet_file) # Do checks warnings = False if linter.close_project_names(): logger....
[ "def test_verify_run_against_sample_sheet_with_missing_sample(self):\n shutil.rmtree(os.path.join(self.mock_illumina_data.dirn,\n self.mock_illumina_data.unaligned_dir,\n \"Project_AB\",\"Sample_AB1\"))\n illumina_data = IlluminaData(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if text file contains any 'invalid' characters
def has_invalid_characters(filen=None,text=None): if filen is not None: with open(filen,'r') as fp: for line in fp: for c in set(line.replace('\n','').replace('\t','')): if ord(c) > 127 or ord(c) < 32: return True else: for ...
[ "def has_invalid_characters(self):\n return has_invalid_characters(text=self._sample_sheet.show())", "def contains_reserved_chars(filename):\n for reserved_char in ReservedFilenameChars:\n if reserved_char in filename:\n return True\n\n return False", "def validate(data, badchars)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Teste les conditions de victoire. Si c'est bon, on modifie la liste qui gère l'activation, et c'est la classe Game qui se chargera de mettre à jour l'animation de victoire.
def test_victory(self): pos = self.actual_hero.position if self.coords[pos].name == "exit" and not self.draw_sprite[1]: self.draw_sprite[1] = True elif self.draw_sprite[1] and not self.one_victory: self.music.play_victory() self.one_victory = True
[ "def CheckVictoryCondition(self):\n opponentVictory = True\n for char in self.screen.characters:\n if char.team == 1 and char.leader and not char.dead:\n opponentVictory = False\n if opponentVictory:\n self.screen.refresh()\n self.music.stop()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Active le pathfinder, qui se charge de trouver un chemin.
def active_pathfinder(self, x_case, y_case): if not self.actual_hero.in_moove and not\ self.draw_sprite[0] and not self.draw_sprite[1]: self.pathfinder.test_path(self.actual_hero, x_case, y_case) else: self.pathfinder.path.case_list = []
[ "def _seek_path(self):\n solver = PathFinder(self.pos, food, self.tail, self.obstacles, self.steps)\n v = solver.exhaustive_search()\n self.safe_path = v\n print(v, self.pos)", "def search(self):\n self.parent[self.start] = None\n begin = self.start\n #target = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the benchmark(s) for the specified version, and parse the results using the given parser. If no benchmarks are specified, all benchmarks will be executed.
def run(self, version, parser, run=None, **kwargs): pass
[ "def _parse_suite(\n self, results: dict, extra_tags: dict = None\n ) -> List[BenchmarkResult]:\n # all results share a batch id\n batch_id = uuid.uuid4().hex\n\n parsed_results = []\n for result in results[\"benchmarks\"]:\n result_parsed = self._parse_benchmark(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sorts a dictionary of contacts
def sort_contacts(contacts): key_list = list(contacts.keys()) #get keys key_list.sort() #sort key_list sorted_list = [] #initialize sorted list for key in key_list: contact = (key, contacts[key][0], contacts[key][1]) #create tuple sorted_list += [contact] #add tuple to list ...
[ "def ordered_contacts(contacts):\n keys = contacts.keys() # assigns a list of the keys in a dictionary to variable keys\n names = sorted(keys)\n for name in names:\n print(name, ':', contacts[name])", "def sort_dict(self, dict):\n\t\treturn sorted(dict.items())", "def ordered_list_by_first_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create Terms With Execution
def test_add_terms_with_execution(): # When add a Terms field t = Terms("foo", ["bar", "baz"], execution="and") # Then I see the appropriate JSON results = { "terms": { "foo": ["bar", "baz"], "execution": "and" } } homogeneous(t, results)
[ "def test_get_create_token_terms(self):\n assert self.strategy.get_create_token_terms() == Terms(\n ledger_id=self.ledger_id,\n sender_address=self.skill.skill_context.agent_address,\n counterparty_address=self.skill.skill_context.agent_address,\n amount_by_currenc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removed headers and numbers from chains
def extract_mixed_chains(raw_chains): chain_isolation_regex = re.compile(r'^\w+\s+\d+\s+(.*)') mixed_chains = [ re.search(chain_isolation_regex, raw_chain).group(1).strip() # remove whitespace for raw_chain in raw_chains ] return mixed_chains
[ "def header_clean_row(row_of_data):\n header = row_of_data.get('header')[1]\n z = list(set(remove_filler_words([header])))\n return z", "def _remove_headers(full_regex_list):\n i_to_remove = []\n count = 0\n for index, regex_group in enumerate(full_regex_list):\n if count == 3:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take many chains and spit them into multiple lists
def split_chains(contents): raw_chains = list(isolate_with_header('^SEQRES', contents)) mixed_chains = extract_mixed_chains(raw_chains) chains = [ list(group) for _, group in itertools.groupby(mixed_chains, key=operator.itemgetter(0)) ] retu...
[ "def get_chains (structure):\n chains=[]\n for chain in structure[0]:\n chains.append(chain)\n return chains", "def getChainListFromResonanceToAtoms(self):\n \n self.chains = []\n \n for resonanceToAtoms in self.resonanceToAtoms.values():\n \n for resonanceToAtom in resonanceTo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract the entire aa sequence in a file Takes the dict from all_chains and merges the values
def extract_all_aa(contents): # TODO: Take the dict from extract_all_chains and merges the values aa_chains = split_chains(contents) y = list(itertools.chain(*aa_chains)) return generate_full_chain(y)
[ "def load_all_seqs_from_multiple_fasta_file( filename ):\n\t\n\tdata = {}\n\t\n\twith open( filename, \"r\" ) as f:\n\t \theader = f.readline().strip()[1:].split(' ')[0]\n\t\tline = f.readline()\n\t\tseq = []\n\t\twhile line:\n\t\t\tif line[0] == '>':\n\t\t\t\tdata.update( { header: \"\".join( seq ) } )\n\t\t\t\the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Count number of occurences of each amino acid
def count_each_aa(aa_seq): amino_acids = IUPAC_AA_codes.keys() return dict((aa, aa_seq.count(aa)) for aa in amino_acids)
[ "def count_aminoacid(aminoacid,sequence):\r\n sequence=sequence\r\n count=sequence.count(aminoacid)\r\n return count", "def aaCount(self):\r\n aaTotal = 0\r\n for aa in self.proteinString:\r\n if aa.upper() in self.aa2mw.keys(): # Checks if character in string is a valid amino a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a chain as a list of strings. Returns a single string
def generate_full_chain(chain): list_of_subchains = [extract_amino_acids(subchain) for subchain in chain] # Join list into single string separated by spaces return ' '.join(list_of_subchains)
[ "def check_format_chains(chains, out_log):\n if not chains:\n fu.log('Empty chains parameter, all chains will be returned.', out_log)\n return 'All'\n\n if not isinstance(chains, list):\n fu.log('Incorrect format of chains parameter, all chains will be returned.', out_log)\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Count the number of aa per chain
def count_amino_acids(all_aa_chains): # Count the spaces and add 1 to get number of amino acids return dict( (chain, all_aa_chains[chain].count(' ')) for chain in all_aa_chains)
[ "def _count(subchain: list) -> int:\n # TODO check around gaps only\n return sum([ 1 if _valid([ v for i, v in enumerate(subchain) if i not in g]) else 0 for g in _gaps(len(subchain)) ])", "def count_aminoacid(aminoacid,sequence):\r\n sequence=sequence\r\n count=sequence.count(aminoacid)\r\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate an aa sequence from a sequence of three letter amino acid codes Expects to receive a single string of three letter codes
def generate_aa_sequence(chain): chain.strip() chain_list = chain.split(' ') # TODO: What if aa is not in the lookup seq = [IUPAC_AA_codes[aa] for aa in chain_list] return ''.join(seq)
[ "def aacode_3to1(seq):\n if len(seq) % 3 == 0:\n single_seq = []\n for i in range(0, len(seq), 3):\n single_seq.append(aa3_to_1_coding_dict.get(seq[i:i+3]))\n return \"\".join(single_seq)\n else:\n raise False", "def translate_sequence(rna_sequence, genetic_code):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take aa seq from generate_aa_sequence and insert a newline every 50 chars.
def generate_aa_sequence_for_disp(aa_seq): return re.sub("(.{50})", "\\1\n", aa_seq, 0, re.DOTALL)
[ "def disp_sec_str(aa_seq):\n return re.sub(\"(.{80})\", \"\\\\1\\n\", aa_seq, 0, re.DOTALL)", "def test_to_fasta(self):\n even = \"TCAGAT\"\n odd = even + \"AAA\"\n even_dna = self.SEQ(even, name=\"even\")\n odd_dna = self.SEQ(odd, name=\"odd\")\n self.assertEqual(even_dna.to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take aa seq from generate_aa_sequence and insert a newline every 80 chars.
def disp_sec_str(aa_seq): return re.sub("(.{80})", "\\1\n", aa_seq, 0, re.DOTALL)
[ "def generate_aa_sequence_for_disp(aa_seq):\n return re.sub(\"(.{50})\", \"\\\\1\\n\", aa_seq, 0, re.DOTALL)", "def format_fasta(name, seq, wrap=60):\n return \">{}\\n{}\".format(name, textwrap.fill(seq, width=wrap))", "def print_aa_seq(self,sequence,y,position=0,frame=0,font=None):\n for letter in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a generator/filter object and gets only the first element Ignores the likelihood of more than one HEADER line Extracts the last word from the line and assumes it to be the file name.
def extract_filename(header_string): # Get the last word in the string file_name_regex = re.compile(r'\w+$') # Use only the first one first_header_string = next(header_string) header = re.findall(file_name_regex, first_header_string.strip())[0] return header
[ "def _skip_file_header(self, line) :\n #e.g. This region:\n \"\"\"\n ########################################\n # Program: water\n # Rundate: Thu 5 Jun 2008 16:56:06\n # Commandline: water\n # -asequence short1.fas\n # -bsequence short2.fas\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for companies_company_id_data_payment_methods_get
def test_companies_company_id_data_payment_methods_get(self): pass
[ "def test_companies_company_id_data_payment_methods_payment_method_id_get(self):\n pass", "def test_companies_company_id_data_bill_payments_get(self):\n pass", "def test_companies_company_id_data_bill_payments_bill_payment_id_get(self):\n pass", "def test_get_payments_by_id(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for companies_company_id_data_payment_methods_payment_method_id_get
def test_companies_company_id_data_payment_methods_payment_method_id_get(self): pass
[ "def test_companies_company_id_data_payment_methods_get(self):\n pass", "def test_companies_company_id_data_bill_payments_bill_payment_id_get(self):\n pass", "def test_companies_company_id_data_bill_payments_get(self):\n pass", "def test_get_payments_by_id(self):\n pass", "def te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal function that is called repeatedly to manage the update of the spectrum plot. It is better to use the `animation` strategy instead of a loop with plt.pause() because plt.pause() will always bring the window to the foreground. This function is also responsible for determining if the user asked to quit.
def animate(self, i): try: self.lastSpectrum = self.spectrometer.getSpectrum() if self.darkReference is not None: self.lastSpectrum -= self.darkReference if self.whiteReference is not None: np.seterr(divide='ignore',invalid='ignore') ...
[ "def update(self, timestep):\n self._draw_observation(timestep.observation['image'])\n plt.show(block=False)\n plt.pause(FLAGS.pause_between_frames)", "def live_plot(filename, x_value, y_value, scroll=True, refresh_rate=1000): #default is 1 sample per second\n data_file, dc_ps_dev, device_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Eventhandling function for when the user hits return/enter in the integration time text field. The new integration time is set in the spectrometer. We must autoscale the plot because the intensities could be very different. However, it takes a small amount of time for the spectrometer to react. We wait 0.3 seconds, whi...
def submitTime(self, event): try: time = float(self.integrationTimeBox.text) if time == 0: raise ValueError('Requested integration time is invalid: \ the text "{0}" converts to 0.') self.spectrometer.setIntegrationTime(time) plt.pause(0.3) ...
[ "def setIntegrationTime(self, time = 1.0):\n setI1DisplayIntegrationTime(time)", "def change_time(self):\r\n self.simulation.set_time(partition.time_step(self.time_entry.text()))\r\n self.time_entry.clearFocus()\r\n self.update_cursor()", "def update():\n draw_watch(timer) #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Eventhandling function to autoscale the plot
def clickAutoscale(self, event): self.axes.autoscale_view()
[ "def ontogglescale(self, event):\n self._onToggleScale(event)\n try:\n # mpl >= 1.1.0\n self.figure.tight_layout()\n except:\n self.figure.subplots_adjust(left=0.1, bottom=0.1)\n try:\n self.figure.delaxes(self.figure.axes[1])\n except:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Eventhandling function to acquire a white reference
def clickWhiteReference(self, event): if self.whiteReference is None: self.whiteReference = self.spectrometer.getSpectrum() self.lightBtn.color = '0.99' else: self.whiteReference = None self.lightBtn.color = '0.85' plt.pause(0.3) self.axes....
[ "def onEvent(self, event):", "def _press(self, event):", "def act_on(self, b):", "def _release(self, event):", "def trigger(self, type, event):", "def random_event():\n\n pass", "def place_call_onhold(self) -> None:", "def get_event(self): # real signature unknown; restored from __doc__\n pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Eventhandling function to acquire a dark reference
def clickDarkReference(self, event): if self.darkReference is None: self.darkReference = self.spectrometer.getSpectrum() self.darkBtn.color = '0.99' else: self.darkReference = None self.darkBtn.color = '0.85' plt.pause(0.3) self.axes.autosc...
[ "def clickWhiteReference(self, event):\n if self.whiteReference is None:\n self.whiteReference = self.spectrometer.getSpectrum()\n self.lightBtn.color = '0.99'\n else:\n self.whiteReference = None\n self.lightBtn.color = '0.85'\n plt.pause(0.3)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Eventhandling function to save the file. We stop the animation to avoid acquiring more spectra. The last spectrum acquired (i.e. the one displayed) after we have requested the filename. The data is saved as a CSV file, and the animation is restarted.
def clickSave(self, event): self.animation.event_source.stop() filepath = "spectrum.csv" try: filepath = backends.backend_macosx._macosx.choose_save_file('Save the data',filepath) except: import tkinter as tk from tkinter import filedialog ...
[ "def OnSaveData(self,e=None):\n # What Data do we wish to save?\n Page = self.notebook.GetCurrentPage()\n # Export CSV data\n filename = Page.tabtitle.GetValue().strip()+Page.counter[:2]+\".csv\"\n dlg = wx.FileDialog(self, \"Save curve\", self.dirname, filename, \n \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that our product is installed.
def test_product_is_installed(self): try: result = self.installer.is_product_installed(PROJECT_NAME) except AttributeError: result = self.installer.isProductInstalled(PROJECT_NAME) self.assertTrue(result)
[ "def test_product_installed(self):\n self.assertTrue(self.installer.isProductInstalled(self.name))", "def test_product_installed(self):\n self.assertTrue(\n self.installer.isProductInstalled(config.PROJECT_NAME),\n )", "def test_product_installed(self):\n self.assertTrue(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that our product is uninstalled.
def test_product_is_uninstalled(self): try: result = self.installer.is_product_installed(PROJECT_NAME) except AttributeError: result = self.installer.isProductInstalled(PROJECT_NAME) self.assertFalse(result)
[ "def testProductUninstalled(self):\n self.failIf(self.qitool.isProductInstalled(\"NuPlone\"))", "def test_product_uninstalled(self):\n self.assertFalse(self.installer.isProductInstalled(\n config.PROJECT_NAME,\n ))", "def test_uninstalled(self):\n self.assertFalse(self.qi....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }