query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Clear serbian text(convert to latinic, ignore stop words, lemmatization and stemming)
def clear_serbian_text(self, ordinal, three_classes): clean_text = [] data_text = loader.load_text_dictionary(ordinal, self._dictionary_path, three_classes) for w, tag, lemma in data_text: # convert word to lowercase and delete spaces word = w.lower().strip() ...
[ "def clear_english_text(self, text):\n clean_text = []\n\n tagged_text = pos_tag(word_tokenize(text))\n\n for word, tag in tagged_text:\n wn_tag = converter.penn_to_wn(tag)\n\n # ignore words with wrong tag\n if wn_tag not in (wn.NOUN, wn.ADJ, wn.ADV):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for calculating positive and negative score for serbian word
def get_score_for_serbian_word(self, word, wnsrb_param, is_prefix): if wnsrb_param == 'c': sentiments = self._wnsrb_data_changed elif wnsrb_param == 'd': sentiments = self._wnsrb_data_deleted else: sentiments = self._wnsrb_data_original pos_scores = [...
[ "def cal_doc_scores(self, sentences) :\n doc_pos_score =0\n doc_neg_score = 0\n for label, pos, neg in sentences:\n if label != 0 :\n doc_pos_score += pos\n doc_neg_score += neg\n return doc_pos_score, doc_neg_score", "def spa_polarity_score(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for calculating positive and negative score for english word
def get_score_for_english_word(self, lemma, wn_tag): pos_scores = [] neg_scores = [] for i in range(len(self._wnen_data["tag"])): tag = self._wnen_data["tag"][i] literals = self._wnen_data["literals"][i] for lit in literals: if lit == lemma an...
[ "def calc_word_value(word):\n score = 0\n for w in word.upper():\n for k, v in LETTER_SCORES.items():\n if k == w:\n score += v\n return score", "def calculate_sentiment(positive_words,negative_words,tweet_text):\n\tpos = 0\n\tneg = 0\n\tfor x in tweet_text:\n\t\tif np.an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test get salario total Este test comprueba el correcto funcionamiento del metodo Get_salario_total de la clase sucursal.
def test_get_salario_total(self): # Creamos mocks de Empleado emp1 = mock(Empleado) emp2 = mock(Empleado) # Creamos sucursal suc = Sucursal("Sevilla", "Pino Montano", "Sucursal1") # Simulamos comportamiento when(emp1).get_salario().thenReturn(1500) when(...
[ "def test_get_user_totals(self):\n response = base.get_totals(self.credentials)\n self.assertEqual(response.status_code, 200)", "def test_get_salario_total_mensual(self):\n dep = Departamento(\"Desarrollo de pruebas\", 1)\n i = 1\n while i <= 3:\n emock = mock(Emplead...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test aniadir empleado Este test comprueba que los empleados se agregan correctamente a la lista de empleados de la sucursal.
def test_aniadir_empleado(self): # Creamos mocks de Empleado emp1 = mock(Empleado) # Creamos sucursal suc = Sucursal("Sevilla", "Pino Montano", "Sucursal1") # Simulamos comportamiento when(emp1).get_ID().thenReturn(1) # Incluimos empleados suc.aniadir_e...
[ "def test_eliminar_empleado(self):\n # Creamos mocks de Empleado\n emp1 = mock(Empleado)\n emp2 = mock(Empleado)\n\n # Creamos sucursal\n suc = Sucursal(\"Sevilla\", \"Pino Montano\", \"Sucursal1\")\n\n # Incluimos empleados\n suc.aniadir_empleado(emp1)\n suc....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test aniadir producto Este test comprueba que los productos se agregan correctamente a la lista de productos de la sucursal.
def test_aniadir_producto(self): # Creamos mocks de Producto prod1 = mock(Producto) # Creamos sucursal suc = Sucursal("Sevilla", "Pino Montano", "Sucursal1") # Simulamos comportamiento when(prod1).get_ID().thenReturn(1) # Incluimos producto suc.aniadir_...
[ "def test_eliminar_producto(self):\n # Creamos mocks de Producto\n pro1 = mock(Producto)\n pro2 = mock(Producto)\n\n # Creamos sucursal\n suc = Sucursal(\"Sevilla\", \"Pino Montano\", \"Sucursal1\")\n\n # Incluimos productos\n suc.aniadir_producto(pro1)\n suc....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test aniadir incidencia Este test comprueba que las incidencias se agregan correctamente a la lista de incidencias de la sucursal.
def test_aniadir_incidencia(self): # Creamos mocks de Incidencia inc1 = mock(Incidencia) # Creamos sucursal suc = Sucursal("Sevilla", "Pino Montano", "Sucursal1") # Simulamos comportamiento when(inc1).get_id().thenReturn(1) # Incluimos incidencia suc.an...
[ "def test_eliminar_incidencia(self):\n # Creamos mocks de Incidencia\n inc1 = mock(Incidencia)\n inc2 = mock(Incidencia)\n\n # Creamos sucursal\n suc = Sucursal(\"Sevilla\", \"Pino Montano\", \"Sucursal1\")\n\n # Incluimos incidencias\n suc.aniadir_incidencia(inc1)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test aniadir proveedor Este test comprueba que los proveedores se agregan correctamente a la lista de proveedores de la sucursal.
def test_aniadir_proveedor(self): # Creamos mocks de Proveedor pro1 = mock(Proveedor) # Creamos proveedor suc = Sucursal("Sevilla", "Pino Montano", "Sucursal1") # Simulamos comportamiento when(pro1).get_ID().thenReturn(1) # Incluimos proveedor suc.aniad...
[ "def test_aniadir_empleado(self):\n # Creamos mocks de Empleado\n emp1 = mock(Empleado)\n\n # Creamos sucursal\n suc = Sucursal(\"Sevilla\", \"Pino Montano\", \"Sucursal1\")\n\n # Simulamos comportamiento\n when(emp1).get_ID().thenReturn(1)\n\n # Incluimos empleados\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test eliminar empleado Este test comprueba que los empleados se eliminan correctamente de la lista de empleados de la sucursal.
def test_eliminar_empleado(self): # Creamos mocks de Empleado emp1 = mock(Empleado) emp2 = mock(Empleado) # Creamos sucursal suc = Sucursal("Sevilla", "Pino Montano", "Sucursal1") # Incluimos empleados suc.aniadir_empleado(emp1) suc.aniadir_empleado(emp2...
[ "def test_eliminar_actividad(self):\n c = Client()\n c.login(username='admin', password='admin1')\n #creamos un US para luego eliminar\n self.test_crear_actividad()\n #eliminacion de un us existente\n resp = c.get('/actividades/actividad_eliminar/1/')\n self.assertTr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test eliminar producto Este test comprueba que los productos se eliminan correctamente de la lista de productos de la sucursal.
def test_eliminar_producto(self): # Creamos mocks de Producto pro1 = mock(Producto) pro2 = mock(Producto) # Creamos sucursal suc = Sucursal("Sevilla", "Pino Montano", "Sucursal1") # Incluimos productos suc.aniadir_producto(pro1) suc.aniadir_producto(pro2...
[ "def test_eliminar_proveedor(self):\n # Creamos mocks de Proveedor\n pro1 = mock(Proveedor)\n pro2 = mock(Proveedor)\n\n # Creamos sucursal\n suc = Sucursal(\"Sevilla\", \"Pino Montano\", \"Sucursal1\")\n\n # Incluimos proveedores\n suc.aniadir_proveedor(pro1)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test eliminar incidencia Este test comprueba que las incidencias se eliminan correctamente de la lista de incidencias de la sucursal.
def test_eliminar_incidencia(self): # Creamos mocks de Incidencia inc1 = mock(Incidencia) inc2 = mock(Incidencia) # Creamos sucursal suc = Sucursal("Sevilla", "Pino Montano", "Sucursal1") # Incluimos incidencias suc.aniadir_incidencia(inc1) suc.aniadir_i...
[ "def test_eliminar_actividad(self):\n c = Client()\n c.login(username='admin', password='admin1')\n #creamos un US para luego eliminar\n self.test_crear_actividad()\n #eliminacion de un us existente\n resp = c.get('/actividades/actividad_eliminar/1/')\n self.assertTr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test eliminar proveedor Este test comprueba que los proveedores se eliminan correctamente de la lista de proveedores de la sucursal.
def test_eliminar_proveedor(self): # Creamos mocks de Proveedor pro1 = mock(Proveedor) pro2 = mock(Proveedor) # Creamos sucursal suc = Sucursal("Sevilla", "Pino Montano", "Sucursal1") # Incluimos proveedores suc.aniadir_proveedor(pro1) suc.aniadir_prove...
[ "def test_eliminar_empleado(self):\n # Creamos mocks de Empleado\n emp1 = mock(Empleado)\n emp2 = mock(Empleado)\n\n # Creamos sucursal\n suc = Sucursal(\"Sevilla\", \"Pino Montano\", \"Sucursal1\")\n\n # Incluimos empleados\n suc.aniadir_empleado(emp1)\n suc....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preprocess PGN files to get board stated, move and game winner as a pandas dataframe, and save it as csv file.
def preprocess_pgn_files(path_pgn_files, num_moves_database, train_val_split, path_save_csv_database): # create empty pandas dataframe to save the information df_train = pd.DataFrame({"board_state": pd.Series([], dtype='str'), "move": pd.Series([], dtype='str'), ...
[ "def read_pgn_file(inp_file):\n my_pgn_file = open(inp_file).readlines()\n with open('datasets/chess_games.csv', 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerow([\"White rating\", \"Black rating\",\n \"White result\", \"Black result\", \"Victory by...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns percentage of col that is less than or equal to x.
def within(col, x): col = col.sort_values() number = 0 while col.iloc[number] <= x and number < len(col): number += 1 return number+1
[ "def percent(x):\n \"*** YOUR CODE HERE ***\"\n c=center(x)\n p=(100*abs(lower_bound(x)-c))/c\n return p", "def percent(x):\n \"*** YOUR CODE HERE ***\"\n a, b = lower_bound(x), upper_bound(x)\n w = (b - a) /2\n c = (b + a) /2\n return abs(w / c) * 100", "def percent(x):\n return w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the piece count difference, mobility (current player moves available) and potential mobility (amount of empty spaces around opponent pieces). Returns a weighted sum of the heuristics.
def calculate_utility(self, boardstate): #return self.mycount_difference(boardstate) #diff = self.mycount_difference(boardstate) legMovs = len(boardstate.calculate_legal_moves()) potMob = self.get_potential_mobility(boardstate) return legMovs + potMob
[ "def weighted_score(player, board):\n opp = othello.opponent(player)\n total = 0\n for sq in othello.squares():\n if board[sq] == player:\n total += SQUARE_WEIGHTS[sq]\n elif board[sq] == opp:\n total -= SQUARE_WEIGHTS[sq]\n return total", "def calculate_weight(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the potential mobility by determining how many opponent pieces have adjacent empty spaces.
def get_potential_mobility(self, boardstate): potential_mobility = 0 for space in boardstate._board: if space == opponent(self.mycolor): if space + 1 == Empty: potential_mobility += 1 elif space - 1 == Empty: potential_m...
[ "def check_if_strong_enough(MyMoves, middle_coord):\n\n ## GET ACTUAL COORDS/DISTANCE OF THE ENEMY\n value = MyMoves.myMatrix.matrix[MyMoves.myMap.my_id][0] ## 1 IS FOR HP MATRIX\n # v_enemy = MyCommon.get_section_with_padding(value, ship_coords, MyCommon.Constants.ATTACKING_RADIUS, 0)\n v_enemy = MyCo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the of empty spaces from the boardstate.
def get_empty_spaces(self, boardstate): empty = 0 for space in range(11, 90): if boardstate._board[space] == 0: empty += 1 return empty
[ "def _get_empty(self):\n empty_cells = []\n row_i = 0\n column_i = 0\n\n for row in self._grid:\n column_i = 0\n for column in row:\n if column == 0:\n empty_cells.append([row_i, column_i])\n column_i += 1\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that fills up a square with a color in the grid, coressponding to arr position
def fill_rect(win, arr_pos, coordinates, sq_dimensions, color): color_dict = {"maroon": (128,0,0), "navyblue": (0,0,128), "green":(0,255,0), "black":(0,0,0), "white":(255,255,255)} x, y = coordinates[str(arr_pos)] sq_width, sq_height = sq_dimensions pygame.draw.rect(win, color_dict[color], (x+1, y+1, s...
[ "def color_position(row: int, col: int):\r\n self.__grid[block.y_pos+row][block.x_pos+col] = block.color", "def fill_grid(self, board):\r\n for x in range(CELLSIZE, FULLSIZE[0] + CELLSIZE, CELLSIZE):\r\n for y in range(CELLSIZE, FULLSIZE[0] + CELLSIZE, CELLSIZE):\r\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the shape of images returned by next_batch_train
def get_images_shape(): return (self.batch_size, self.OUTPUT_SIZE, self.OUTPUT_SIZE, self.NUM_CHANNELS)
[ "def state_shape(self, batch_size):\n return [self.num_layers * self.num_dirs, batch_size, self.num_units],", "def image_shape(self):\n return self.mri_imgs[0].shape", "def state_shape(self, batch_size):\n return ([self.num_layers * self.num_dirs, batch_size, self.num_units],\n [self.num...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the next batch for the test data with the requested batch_size or the current default. This function takes care of all the data augmentation techniques.
def next_batch_test(self, batch_size=None): # set the batch_size and output_size to class default if batch_size is None: batch_size = self.test_batch_size output_size = self.OUTPUT_SIZE input_size = self.INPUT_SIZE # create an array of indicies to retrieve ...
[ "def get_batch(batch_size=None, test=False):\n examples = TEST_EXAMPLES if test else TRAIN_EXAMPLES\n batch_examples = random.sample(\n examples, batch_size) if batch_size else examples\n return batch_examples", "def next_batch(self, batch_size):\n start = self._index_in_epoch\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the controller that returns the torque for the desired state.
def qp_controller(current_state, desired_state, dt, dim=2): # torque PD controller values wheel_kp = 50.0 wheel_kd = 10.0 max_torque = 20.0 # cost on obtaining next state and velocity kp = 0.0 kd = 1.0 # half state length hl = len(current_state) / 2 mp = MathematicalProgram()...
[ "def torque(b):\n return length(b) * total_weight(contents(b))", "def calc_control(self, pose_goal):\n cmd_vel = Twist()\n\n # TODO: fill in your favorite controller\n\n return cmd_vel", "def run_controller(self):\n # Check if the goal has been set.\n if self.goal_pos is No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a known_good.json file and extract its git url + revisions from it.
def parse_known_good_file(good_data): result = {} SITE_MAP = {'github': 'https://github.com'} deps = json.loads(good_data) assert 'commits' in deps for dep in deps['commits']: name = dep['name'] site = dep['site'] site_url = SITE_MAP.get(site) assert site_url, 'Unknow...
[ "def FindURLSInJSON(json_file, gs_urls):\n output = subprocess.check_output(['svn', 'cat', json_file])\n json_content = json.loads(output)\n for dict_type in ['actual-results']:\n for result_type in json_content[dict_type]:\n if json_content[dict_type][result_type]:\n for result in json_content[di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a .gitmodules file to extract a { name > url } map from it.
def parse_git_submodules(gitmodules_data): gitmodules_data = gitmodules_data.decode("utf-8") result = {} # NOTE: configparser.ConfigParser() doesn't seem to like the file # (i.e. read_string() always returns None), so do the parsing # manually here. section_name = None in_submodu...
[ "def parse_gitmodules(raw):\n\n result = {}\n locals_ = {}\n\n def reset():\n locals_.clear()\n\n def add_result():\n if locals_.get('added'):\n return\n\n path = locals_.get('path')\n url = locals_.get('url')\n\n if (path is None or url is None):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
extract_indices(indices, start_index = 0, stepsize = 1, length = 2) returns all indices in indices, that are not contained in the series generated by start_index and step_size.
def extract_indices(indices, start_index = 0, stepsize = 1, length = 2): samples = np.arange(start_index, length, stepsize).astype('int') return np.setdiff1d(indices, samples)
[ "def process_start_indices(start_indices: Union[int, Iterable[int]],\n max_length: int) -> List[int]:\n if isinstance(start_indices, Number):\n start_indices = range(int(start_indices))\n\n start_indices = np.array(start_indices, dtype=int)\n\n # check, whether index set is ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
backprop_square(ancestor, mode = 'pos')
def backprop_square(ancestor, mode = 'pos'): series = ancestor.series positions = np.arange(0,series.size) #the positions which are not prooven to be squares if mode == 'pos': positive_indices = [i for i, e in enumerate(ancestor.positive_tests) if (e[0] == 'square' and e[3] == '+')] for e...
[ "def backprop_cube(ancestor, mode = 'pos'):\n series = ancestor.series\n positions = np.arange(0,series.size) #the positions which are not prooven to be cubes\n if mode == 'pos':\n positive_indices = [i for i, e in enumerate(ancestor.positive_tests) if (e[0] == 'cube' and e[3] == '+')]\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
backprop_cube(ancestor, mode = 'pos')
def backprop_cube(ancestor, mode = 'pos'): series = ancestor.series positions = np.arange(0,series.size) #the positions which are not prooven to be cubes if mode == 'pos': positive_indices = [i for i, e in enumerate(ancestor.positive_tests) if (e[0] == 'cube' and e[3] == '+')] for element...
[ "def backprop_square(ancestor, mode = 'pos'):\n series = ancestor.series\n positions = np.arange(0,series.size) #the positions which are not prooven to be squares\n if mode == 'pos':\n positive_indices = [i for i, e in enumerate(ancestor.positive_tests) if (e[0] == 'square' and e[3] == '+')]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
backprop_prime(ancestor, mode = 'pos')
def backprop_prime(ancestor, mode = 'pos'): series = ancestor.series positions = np.arange(0,series.size) #the positions which are not prooven to be prime if mode == 'pos': positive_indices = [i for i, e in enumerate(ancestor.positive_tests) if (e[0] == 'prime' and e[3] == '+')] for eleme...
[ "def backprop_square(ancestor, mode = 'pos'):\n series = ancestor.series\n positions = np.arange(0,series.size) #the positions which are not prooven to be squares\n if mode == 'pos':\n positive_indices = [i for i, e in enumerate(ancestor.positive_tests) if (e[0] == 'square' and e[3] == '+')]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify that a block actually has the correct hash when submitted by a different miner
def verify_block(self, block): sha = hasher.sha256('a') sha.update( str(block.block_id) + str(block.miner_id) + str(block.timestamp) + str(block.data) + str(block.previous_hash)) verify_hashed = sha.hexdigest() if verify_hashed != block.hash: print("Miner ({}) could not verify the prev...
[ "def test_last_block_hash():\n # Setup\n mock_ledger = Ledger('monies')\n mock_miner = Miner('Mock', mock_ledger)\n mock_header = {'hdr': 'foo'}\n mock_ledger.block_count = 1\n mock_ledger.all_transactions.append(mock_header)\n mock_message = mock_ledger.all_transactions[0]['hdr']\n mock_non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and return an AthenaHook.
def hook(self) -> AthenaHook: return AthenaHook(self.aws_conn_id, log_query=self.log_query)
[ "def hook(self) -> DynamoDBHook:\n return DynamoDBHook(self.aws_conn_id, region_name=self.region_name)", "def add_webhook(self, **kwargs):\r\n allowed = ['scaling_group', 'policy', 'name', 'metadata']\r\n self._check_args(kwargs, allowed)\r\n webhook_id = str(self.webhook_counter.next(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
There are no movie projections on the given date
def test_show_movie_projections_valid_movie_invalid_date(self): user_input = "show movie projections 1 2014-12-31" expected_output = """Projections for movie 'The Hunger Games: Catching Fire' on date 2014-12-31:""" output = StringIO() try: sys.stdin = StringIO(user_input) ...
[ "def is_projection_empty(self):\n ret_val = self._is_projection_empty()\n return ret_val", "def _is_null_date(fecha):\n return year(fecha) == YEAR_NULL_TERADATA", "def check_missing_dates(dates, data_location):\n suffix = proximus_mobility_suffix()\n full_list = []\n for f in os.listdi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read and append errors to the log
def read_errors(self): self.output.append(str(self.process.readAllStandardError()))
[ "def print_errors(self):\n if not os.path.exists(self.errlog):\n print('Error file have been not created!')\n return\n\n with open(self.errlog, 'r') as fid:\n print(fid.read())", "def _log_errors(errors):\n # NOTE: DataCiteError is a tuple with the errors on t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the URI for a route named name.
def reverse(name, *args, **kwargs): return webapp2.uri_for(name, *args, **kwargs)
[ "def url_for(self, name: str, **kwargs) -> str:\n route = self._router.get_route_or_404(name)\n return route.url(**kwargs)", "def route(self, name, params={}, full=False):\n from config import application\n if full:\n route = application.URL + self._get_named_route(name, par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Custom Jinja2 factory method to insert our own extensions.
def jinja2_factory(app): config = { 'globals': {'reverse': reverse}, 'filters': {} } return jinja2.Jinja2(app, config)
[ "def instantiate_extensions(self, template):\n return [ ext_cls(template) for ext_cls in self.extensions ]", "def jinja_engine():\n\treturn JinjaEngine()", "def register_template_extensions(\n cls,\n exts_fn: Callable[[CompileCtx], Dict[str, Any]]\n ) -> None:\n assert not cls._te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a secure cookie session for flash messages. Django and Flask have a similar implementation. If you do not use flash messages, then no secure cookie is written. To add a flash message self.flash.add_flash('Foobar!') To get all flash messages messages = [value for value, level in self.flash.get_flashes()] It is fi...
def flash(self): # Need to supply a name to avoid using the same default cookie name return self.session_store.get_session( name='gordon', backend='securecookie')
[ "def messages(self, clear=True):\n flashes = self.controller.session.get('__flash', None) or {}\n if clear:\n self.controller.session['__flash'] = {}\n return flashes", "def set_secure_cookie(self, name, value):\n secure_val = make_secure_val(value)\n self.response.se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Will check to see if the user has a role specified in roles for thie object It needs to find the object. It does this in two ways. You specify a param. It will look in the arguments passed to the decorated function for a param named whatever you pass to param in this ctor. If that fails, you can specify get_from, which...
def __init__(self, roles, param=None, get_from=None): self.param = param self.roles = roles self.get_from = None if get_from: self.get_from = isinstance(get_from, (list, tuple)) and get_from or [get_from]
[ "def _existing_only(func):\n\n @wraps(func)\n def _check_existence(db, entity, role=None, *, rolename=None):\n if isinstance(role, str):\n rolename = role\n if rolename is not None:\n # if given as a str, lookup role by name\n role = orm.Role.find(db, rolename)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function that produces a list of unique pixel values for a set of images
def extract_pixel_vals(ref_img_list): from scipy import misc import numpy as np imRef = [] for ref in range(len(ref_img_list)): tmpRef = misc.imread(ref_img_list[ref]) for i in range(tmpRef.shape[0]): for j in range(tmpRef.shape[1]): imRef.append(tuple(tm...
[ "def unique(kernels):\n r, s = list(), set()\n for kernel in kernels:\n if isinstance(kernel.length, list):\n key = tuple(kernel.length) + (kernel.scheme,)\n else:\n key = (kernel.length, kernel.scheme)\n if key not in s:\n s.add(key)\n r.append...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Codec defaults to Latin1 / ISO 88591
def test_default(self): self.assertEqual(Codec.default(), Latin1Codec())
[ "def get_data_encoding():", "def __init__(self, encoding):\n self.trans = {}\n for char in 'ÀÁÂẦẤẪẨẬÃĀĂẰẮẴẶẲȦǠẠḀȂĄǍẢ':\n self.trans[char] = 'A'\n for char in 'ȀǞ':\n self.trans[char] = 'Ä'\n self.trans['Ǻ'] = 'Å'\n self.trans['Ä'] = 'Ae'\n self.trans...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Codec can be retrieved by magic id3v2.3 encoding number
def test_get_by_magic_number(self): self.assertEqual(Codec.get(0), Latin1Codec()) self.assertEqual(Codec.get(1), UTF16Codec()) self.assertEqual(Codec.get(2), UTF16BECodec()) self.assertEqual(Codec.get(3), UTF8Codec())
[ "def get_data_encoding():", "def codecTag(self):\n codec_t = None\n if 'codec_tag_string' in self.__dict__:\n codec_t = self.__dict__['codec_tag_string']\n return codec_t", "def get_id_from_enc(encoding_list_tuple, encoding):\n for i in encoding_list_tuple:\n if i[0] ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the turnRestrictOff override, return control to the Xset flag.
def _resetRestrict(self): self.__tmpRemoveRestrict = False
[ "def control_points_off(self):\n self.object.GripsOn = False\n sc.doc.Views.Redraw()", "def eval_off(target):\n target.power.off()", "def toggle_recharge_off(self):\n self.will_recharge = False", "def undefine(self):\n ret = libvirtmod.virNWFilterUndefine(self._o)\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restore all XSPEC contexts to singleprocess execution.
def reset(self): self.leven = 1 self.error = 1 msgStr = "All parallel contexts are now reset to single-process \ execution." print(msgStr) if Xset.log is not None: print(msgStr,file=Xset.log)
[ "def teardown_workflow(self):\n del self.sca_preproc", "def resetContexts(parts):\n\tfor part in parts:\n\t\tfor item in part:\n\t\t\tresetContext(item)", "def reset_context():\n global _model\n _model = None", "def reset(self):\n try:\n for module in self.modules:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a key,value pair of strings to XSPEC's internal database. This database provides a way to pass string values to certain model functions which are hardcoded to search for "key". (See the XSPEC manual description for the "xset" command for a table showing model/key usage.) If the key,value pair already exists, it wil...
def addModelString(self, key, value): if isinstance(key,str) and isinstance(value,str): # User should not have entered whitespace in key or value, # but use split() to be sure. modStringArgs = ["xset"] modStringArgs += key.split() modStringArgs += valu...
[ "def __setitem__(self, key, value):\n query = self.store.update().where(self.store.c.key == key).values(value=value)\n result = self.conn.execute(query)\n if result.rowcount == 0:\n query = self.store.insert().values(key=key, value=value)\n result = self.conn.execute(query...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close XSPEC's current log file.
def closeLog(self): _pyXspec.closeLog()
[ "def log_close(self):\n self._logfile.close()", "def close_log(self):\n if self._logFile is not None:\n self._logFile.close()\n self._logFile = None", "def closeLog() :\n global messageLog\n messageLog.close()", "def close_file():\n lib_close.close_file()", "def clos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restore the data/model configuration and settings. This will restore the data, models, and settings from a previous PyXspec session, as saved in file generated by the Xset.save() function.
def restore(self, fileName): if isinstance(fileName, str): savedFile = open(fileName,'r') # check for PyXspec indicator in first line isPyXspecSave = savedFile.readline().startswith('#PyXspec') warningMsg ="\n***Warning: The file sent to Xset.restore(): "+fileName...
[ "def btnRestoreClicked(self):\n pyzo.resetConfig()\n shutil.copyfile(self.backup_file, self.conf_file)\n pyzo.main.restart()", "def _restore(self):\n\n # check restore\n if not self.restore:\n return\n\n # restore\n settings = self._settings\n set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
wavelet decomposition of into scales This function uses Haar wavelets for demonstration purposes.
def simpleWaveDec(signal, nb_scales): # Haar Wavelets filters for decomposition and reconstruction ld = [1, 1] hd = [-1, 1] # transformation C = [] A = signal # approximation for i in range(nb_scales): A, D = waveSingleDec(A, ld, hd) # get the coefficients C.append(...
[ "def scalogram(filename, savename):\n\n #signal reading\n (rate,signal) = wav.read(filename)\n\n #ignore other bands for primary treatment\n if signal.shape[1] > 1:\n signal = signal[:,0]\n\n #clip the signal\n max_energy = max(energy)\n start_frame = 0\n for k in range(len(energy)):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
wavelet simple reconstruction function of a 1D signal
def simpleWaveRec(C): ld = np.array([1, 1]) hd = np.array([-1, 1]) lr = ld/2 hr = -hd/2 A = C[-1] for scale in reversed(C[:-1]): A = waveSingleRec(A, scale, lr, hr) return A
[ "def cwt(\n x ,\n# frequencies = np.exp(np.arange( -5.5 , 0.0 , 0.01 )) ,\n frequencies = np.exp(np.arange( -2.5 , 0.0 , 0.01 )) ,\n wavelet = cauchy,\n Q = 10.\n):\n\n\n N_x = len(x)\n N_pad = closest_anti_prime( N_x + 120 ) - N_x\n N = N_x + N_pad # data length including padding...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
% wavelet decomposition of a 2D image into four new images. % The image is supposed to be square, the size of it is a power of 2 in the % x and y dimensions.
def decWave2D(image, ld, hd): # Decomposition on rows sx, sy = image.shape LrA = np.zeros((sx, int(sy/2))) HrA = np.zeros((sx, int(sy/2))) for i in range(sx): A, D = waveSingleDec(image[i, :], ld, hd) LrA[i, :] = A HrA[i, :] = D # Decomposition on cols LcLrA = np....
[ "def multiband_starlet_transform(image, scales=None, generation=2, convolve2D=None):\n assert len(image.shape) == 3, f\"Image should be 3D (bands, height, width), got shape {len(image.shape)}\"\n assert generation in (1, 2), f\"generation should be 1 or 2, got {generation}\"\n scales = get_scales(image.sha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
wavelet reconstruction of an image described by the wavelet coefficients C
def simpleImageRec(C): # The Haar wavelet is used ld = np.array([1, 1]) hd = np.array([-1, 1]) lr = ld/2 hr = -hd/2 A = C[-1] for scale in reversed(C[:-1]): A = recWave2D(A, scale[0], scale[1], scale[2], lr, hr) return A
[ "def wavelet_coeffs(data,srate,freqs,nco=2):\n\n # Generate the scaled wavelets for each frequency\n Ws = list()\n for k,f in enumerate(freqs):\n\n sigma_tf = nco/(2*np.pi*f) #f: frequency in Hz\n\n t = np.arange(0,5*sigma_tf,1/srate)\n t = np.r_[-t[::-1],t[1:]]\n\n osc = np.exp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function to perform reverse enumerate of a list returns zip
def reversedEnumerate(l): return zip(range(len(l)-1, -1, -1), l[::-1])
[ "def reversed_enumerate(seq):\r\n return izip(reversed(xrange(len(seq))), reversed(seq))", "def reverse_enumerate(iterable):\n\t# Lifted from http://galvanist.com/post/53478841501/python-reverse-enumerate\n\treturn itertools.izip(reversed(xrange(len(iterable))), reversed(iterable))\n\t# Alternative python3 ver...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to read in start and end simulaiton time and return a `ClockStructClass` object
def read_clock_paramaters(SimStartTime,SimEndTime,OffSeason=False): # extract data and put into numpy datetime format SimStartTime = pd.to_datetime(SimStartTime) SimEndTime = pd.to_datetime(SimEndTime) # create object ClockStruct = ClockStructClass() # add variables ClockStruct.Simulatio...
[ "def GetTime(self):\n\t\tseconds = self.bcd2dec( self.readRegister(SEC) &(~START_32KHZ)) # mask out ST bit\n\t\tminutes = self.bcd2dec( self.readRegister(MIN))\n\t\t\n\t\thour_t = self.readRegister(HOUR)\n\t\tif((hour_t & HOUR_12) == HOUR_12):\n\t\t\t(hour_t & 0x1F) \n\t\telse:\n\t\t\t(hour_t & 0x3F)\n\t\t\t\n\t\th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finalise soil and crop paramaters including planting and harvest dates save to new object ParamStruct
def read_model_parameters(ClockStruct,Soil,Crop,weather_df): # create ParamStruct object ParamStruct = ParamStructClass() Soil.fill_nan() # Assign Soil object to ParamStruct ParamStruct.Soil = Soil while Soil.zSoil < Crop.Zmax+0.1: for i in Soil.profile.index[::-1]: if S...
[ "def init_coupled_parameters(self):\n params=NamedObjects(scenario=self,cast_value=cast_to_parameter)\n # All of the current known options:\n # params['Tau']=1\n # params['TauFlow']=1\n # params['Velocity']=1\n if self.model.mdu.get_bool('physics','Salinity'):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to compute additional parameters needed to define crop phenological calendar
def compute_crop_calander(crop,ClockStruct,weather_df): if len(ClockStruct.PlantingDates)==0: plant_year = pd.DatetimeIndex([ClockStruct.SimulationStartDate]).year[0] if pd.to_datetime(str(plant_year)+"/"+crop.PlantingDate) < ClockStruct.SimulationStartDate: pl_date = str(plant_year+1)...
[ "def process_epidemic_parameters(self):", "def update_roi_params(self,roi_pnts,**kwargs):\n self.cal_factor = kwargs.get('cal_factor',0.0212) \n \n #width values\n self.width_value = self.configs.get('width_default',150) #current value for filament width\n\n \n #roi\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
funciton to create soil profile class to store soil info. Its much faster to access the info when its in a class compared to a dataframe
def create_soil_profile(ParamStruct): Profile = SoilProfileClass(int(ParamStruct.Soil.profile.shape[0])) pdf = ParamStruct.Soil.profile.astype('float64') Profile.dz = pdf.dz.values Profile.dzsum = pdf.dzsum.values Profile.zBot = pdf.zBot.values Profile.zTop = pdf.zTop.values Profile.zMid ...
[ "def __init__(self):\n self.profiles = namedtuple('profiles',fake.profile().keys())\n self.group = namedtuple('group',['profiles'])\n\n for i in range(10000):\n p1 = self.profiles(**fake.profile())\n if(i==0):\n self.profiles_nt = self.group(p1)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
bperturbations are now calculated and stored in the nncomp_df dataframe. If CLEAR calculates a bperturbation that is infeasible, then the details of the bperturbation are stated in the missing_log_df dataframe. CLEAR will classify a bperturbation as being infeasible if it is outside 'the feasibility range' it calculate...
def Calculate_Perturbations(explainer, results_df, multiClassBoundary_df, multi_index=None): print("\n Calculating b-counterfactuals \n") nncomp_df = pd.DataFrame(columns=['observation', 'multi_class', 'feature', 'orgFeatValue', 'orgAiProb', 'actPerturbedFeatValue', 'AiP...
[ "def fit(self):\n # if self.verbose == 1:\n # print ('The list of all perturbation with its probability: \\n')\n # for perturb in range(len(self.p_list)):\n # print('%s perturbation with probability of: %s \\n' %(self.p_list[perturb], self.p_prob[perturb]))\n #p_cu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the tags associated with video frames in the file videotags.csv.
def read_tags(): f = open('videotags.csv') skip = f.readline() tags = defaultdict(lambda: []) for line in f: fields = line.rstrip().split(',') vid = int(fields[0]) framestart = int(fields[1]) frameend = None if len(fields[2])==0 else int(fields[2]) frametags = set...
[ "def read_features(video_name: str, directory: str) -> Tuple[np.ndarray, np.ndarray]:\n if not os.path.isfile(f'{directory}/{video_name}-feats.npy'):\n raise Exception(f'Missing features file for video {video_name} in {directory}')\n if not os.path.isfile(f'{directory}/{video_name}-tags.npy'):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all tags associated with a given video frame.
def frame_tags(self, vid, frame): if not self.tags.has_key(vid): raise Exception("Video ID not found.") v = self.tags[vid] L = [] for interval in v: if frame >= interval[0] and frame <= interval[1]: L += interval[2] return set(L)
[ "def search_videos_tag(self, video_tag):\n results = []\n for video in self._video_library.get_all_videos():\n for tag in video.tags:\n if video_tag.lower() == tag.lower():\n if not video.flag:\n results.append(video)\n self.di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The set of all tags as a sorted list.
def all_tags(self): t = list(set.union(*[L[2] for v in self.tags.values() for L in v])) t.sort() return t
[ "def _list(self):\n with self._treant._read:\n tags = self._treant._state['tags']\n\n tags.sort()\n return tags", "def tags(self) -> List:", "def get_tags(self):\n\n return sorted(self.tags, key=lambda tag: tag.commit.committed_datetime, reverse=True)", "def get_tags(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test correct message composing.
def test_compose_message(): message = b'message' topic = b'test topic' # Basic composing for serializer in AgentAddressSerializer.SERIALIZER_SIMPLE: serializer = AgentAddressSerializer(serializer) assert compose_message(message, topic, serializer) == topic + message for serializer i...
[ "def test_message_exactly_buffsize(self):\n buf_message = \"It's 16 bytes eh\"\n self.send_message(buf_message)\n actual_sent, actual_reply = self.process_log()\n expected_sent = self.sending_msg.format(buf_message)\n self.assertEqual(expected_sent, actual_sent)\n expected_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple requestreply pattern between two agents with different serializations.
def test_reqrep(nsproxy, serializer, message, response): def rep_handler(agent, message): return response a0 = run_agent('a0') a1 = run_agent('a1') addr = a0.bind('REP', 'reply', rep_handler, serializer=serializer) a1.connect(addr, 'request') assert a1.send_recv('request', message) == ...
[ "async def test_quickresponse(self):\n actions = [\n ('id1', 'Action 1'),\n ('id2', 'Action 2'),\n ]\n self.clients[0]['xep_0439'].ask_for_actions(\n self.clients[1].boundjid.full,\n \"Action 1 or 2 ?\",\n actions\n )\n msg = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple requestreply pattern between an agent and a direct ZMQ connection.
def test_reqrep_raw_zmq_outside(nsproxy): # Create an osBrain agent that will receive the message a1 = run_agent('a1') a1.set_attr(received=None) addr = a1.bind( 'REP', transport='tcp', handler=echo_handler, serializer='raw' ) # Create a raw ZeroMQ REQ socket context = zmq.Context()...
[ "def test_reqrep(nsproxy, serializer, message, response):\n\n def rep_handler(agent, message):\n return response\n\n a0 = run_agent('a0')\n a1 = run_agent('a1')\n addr = a0.bind('REP', 'reply', rep_handler, serializer=serializer)\n a1.connect(addr, 'request')\n assert a1.send_recv('request'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple pushpull pattern test, using different serializations.
def test_pushpull(nsproxy, serializer, message): a0 = run_agent('a0') a1 = run_agent('a1') a1.set_attr(received=None) addr = a1.bind('PULL', handler=set_received, serializer=serializer) a0.connect(addr, 'push') a0.send('push', message) assert wait_agent_attr(a1, name='received', value=messag...
[ "def test_simple_push_pull():\n with Remote() as remote, Pusher(remote) as pusher:\n pusher.push_file('README.md', '1')\n\n with Puller(remote) as puller:\n assert puller.git('rev-parse', 'HEAD') == pusher.git('rev-parse', 'HEAD')\n assert puller.read_file('README.md') == push...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple pushpull pattern test. Channel without serialization. The message is sent from outside osBrain, through a ZMQ PUSH socket.
def test_pushpull_raw_zmq_outside(nsproxy): # Create an osBrain agent that will receive the message a1 = run_agent('a1') a1.set_attr(received=None) addr = a1.bind( 'PULL', transport='tcp', handler=set_received, serializer='raw' ) # Create a raw ZeroMQ PUSH socket context = zmq.Conte...
[ "def test_pushpull(nsproxy, serializer, message):\n a0 = run_agent('a0')\n a1 = run_agent('a1')\n a1.set_attr(received=None)\n addr = a1.bind('PULL', handler=set_received, serializer=serializer)\n a0.connect(addr, 'push')\n a0.send('push', message)\n assert wait_agent_attr(a1, name='received', ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple publishersubscriber pattern test with different serializations.
def test_pubsub(nsproxy, serializer, message): a0 = run_agent('a0') a1 = run_agent('a1') a1.set_attr(received=None) addr = a0.bind('PUB', alias='pub', serializer=serializer) a1.connect(addr, handler=set_received) while not a1.get_attr('received'): a0.send('pub', message) time.sle...
[ "def test_multiple_publishers_one_subscriber(self):\n\n def client(port, result_queue, registrations):\n def callback(cb_topic, cb_message_data, cb_associated_data):\n self.assertIn(int(cb_topic), registrations)\n expected_message, data = registrations[int(cb_topic)]\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple publishersubscriber pattern test. Channel without serialization. The message is sent from outside osBrain, through a ZMQ PUB socket.
def test_pubsub_raw_zmq_outside(nsproxy): # Create an osBrain agent that will receive the message a1 = run_agent('a1') a1.set_attr(received=None) addr = a1.bind( 'SUB', transport='tcp', handler=set_received, serializer='raw' ) # Create a raw ZeroMQ PUB socket context = zmq.Context()...
[ "def test_pubsub(nsproxy, serializer, message):\n a0 = run_agent('a0')\n a1 = run_agent('a1')\n a1.set_attr(received=None)\n addr = a0.bind('PUB', alias='pub', serializer=serializer)\n a1.connect(addr, handler=set_received)\n while not a1.get_attr('received'):\n a0.send('pub', message)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the weighted value of this input
def getWeightedValue(): weight*value
[ "def get_weight(self) -> float:\n return 0", "def get_weight(self, temp):\n return self.temp_dict[temp]['weight']", "def getWeight(self):\n return np.concatenate([self.weight.ravel()] * 4)", "def easyWeighting(self, weights, values):\n summedVal = 0 \n for k, weight in enume...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return sink of this input edge
def getSink(): return sink
[ "def src_sink(self) -> SrcSink:\n pass", "def signal(self):\n return self.source.output", "def sink_path(self):\n return self._sink_path if self.enabled else None", "def get_propagate_wire(self):\r\n return self.out.get_wire(2)", "def getSinkFlow(self):\r\n return self.sin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the currently configured storefront search function. Returns a callable that accepts the search phrase.
def pick_backend(): return import_module(settings.SEARCH_BACKEND).search_storefront
[ "def get_function_search_session(self):\n if not self.supports_function_search():\n raise errors.Unimplemented()\n # pylint: disable=no-member\n return sessions.FunctionSearchSession(runtime=self._runtime)", "def get_function_search_session(self):\n return # osid.authorizat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the currently configured dashboard search function. Returns a callable that accepts the search phrase.
def pick_dashboard_backend(): return import_module(settings.SEARCH_BACKEND).search_dashboard
[ "def get_filter_function(study_name: str) -> Callable:\n if study_name not in _filter_funcs:\n return _filter_funcs[\"*\"]\n\n return _filter_funcs[study_name]", "def get_function_search_session(self):\n return # osid.authorization.FunctionSearchSession", "def do_alfred_search(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tbl True for tblname being tested, False if a fldname being tested. Bad name for SQLite? The best way is to find out for real (not too costly and 100% valid by definition). Strangely, SQLite accepts '' as a table name but we won't ;).
def valid_name(name, is_tblname=True): debug = False if name == '': return False default_db = mg.LOCAL_PATH / mg.INT_FOLDER / 'sofa_tmp' con = sqlite.connect(str(default_db)) ## Note - newer versions accept pathlib Path as well as strings but Bionic doesn't :-( add_funcs_to_con(con) cur...
[ "def verify_table_name(table_name):\n table_names = get_table_names()\n if table_name in table_names:\n return True\n else:\n return False", "def test_db_table_name_must_be_tag(self):\n db_table = Tag._meta.db_table\n self.assertEquals(db_table, 'tag')", "def test_contest_ta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
u"""Create a decorator that requires ``predicate(request)`` to evaluate ``True`` before calling the decorated function. If the predicate evalutates ``False`` then ``response_builder`` is called with the original function, request and args and kwargs and returned.
def create_require(predicate, response_builder): def require(func): @wraps(func) def decorated(request, *args, **kwargs): if predicate(request): return func(request, *args, **kwargs) else: return response_builder(func, request, *args, **kwargs)...
[ "def require(predicate):\n def outer(f):\n @wraps(f)\n def inner(request, *args, **kwargs):\n try:\n predicate.check_authorization(request.environ)\n except NotAuthorizedError as e:\n reason = unicode(e)\n if request.environ.get('re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialise a deck of cards and return lists of suits and card values.
def deck(): suits = ['clubs', 'diamonds', 'hearts', 'spades'] cards = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'] return suits, cards
[ "def build_deck(self):\n suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs']\n ranks = {\n '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'J':10, 'Q':10, 'K':10, 'A':11,\n }\n for suit in suits:\n for rank, value in ranks.items():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw up to n unique cards from a deck with or without replacement. Randomly draw n unique cards from a standard deck until the desired number (n_cards) is reached.
def draw(n_cards, replacement=False): import random # If replacement is True, the same card can be picked multiple times if replacement: # Initialise hand to the empty list (no card picked yet) hand = [] # Append a random card to the hand while len(hand) < n_cards: ...
[ "def draw(self, n: int):\n draw_cards = self.cards[:n]\n self.cards[:n] = [] # remove cards drawn from deck\n return draw_cards", "def deal(self, n: int):\n d = Deck()\n d.shuffle()\n deal = tuple([] for _ in range(n))\n for _ in range(3):\n for i in ran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract card values from drawn cards. Extract values out of all cards in the hand. Assign numerical value to
def card_values(hand): # Extract card values card_values = [value for (suit, value) in hand] # Convert special card names to values card_values = [10 if value in ('J', 'Q', 'K') else 1 if value == 'A' \ else value for value in card_values] return card_values
[ "def values(self):\n val = 0\n aces = 0\n for card in self.cards:\n if cardvals[card.val] == 1:\n aces+=1\n else:\n val += cardvals[card.val]\n\n handval = [val]\n\n for ace in range(aces):\n newhandval = [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw n cards with or without replacement for each of k hands. Randomly draw n cards from the deck until the desired number is reached. Repeat the step k times to obtain k distinct hands. Return already converted card values. If 'replacement' is omitted or False, the cards are drawn
def hands(n_cards, k_hands, replacement=False): # For each of the k hands draw n cards (with or without replacement) and # compute their values if replacement: hands = [card_values(draw(n_cards, True)) for hand in range(k_hands)] else: hands = [card_values(draw(n_cards)) for hand in ran...
[ "def draw(n_cards, replacement=False):\n import random\n\n # If replacement is True, the same card can be picked multiple times\n if replacement:\n\n # Initialise hand to the empty list (no card picked yet)\n hand = []\n\n # Append a random card to the hand\n while len(hand) < n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sum card values for each of the k hands. Return the sum of the card values, for each of the k hands provided.
def sum_hands(hands): # Give me the sum, for each of the hands provided sum_hands = [sum(hand) for hand in hands] return sum_hands
[ "def sum_hand(self, hand):\n total = 0\n for card in hand:\n if \"Ace\" in card:\n if total + 11 > 21:\n total += 1\n else:\n total += 11\n else:\n total += self.deck.deck[card]['value']\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute Student's t cumulative distribution function (cdf). Compute Student's t cumulative distribution function, F(x) = P(X <= x). Compute 1 F(x)if upper = True.
def tcdf(x, m, s, n, upper=False): from scipy import stats # If upper is set to True, compute 1 - F(x); else, compute F(x) if upper: tcdf = 1 - stats.t.cdf(x, n - 1, m, s) print('P(X >= %s) = %.4f'%(x, tcdf)) else: tcdf = stats.t.cdf(x, n - 1, m, s) print('P(X <= %s) = %...
[ "def to_cdf(pdf):\n return np.cumsum(pdf)", "def _uniform_order_statistic_cdf(i, n, t):\r\n return betainc(i+1, n-i, t)", "def cdf(self, t, l):\n def _cdf(t):\n x = np.linspace((self.r-l)/self.c,t,100)\n return np.trapz(self.pdf(x,l),x)\n\n if np.iterable(t):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces org token with html representation
def org(value): start_token = '<org>' end_token = '</org>' return value.replace(start_token,'<i class="organisation">').replace(end_token,'</i>&nbsp;<sup><i class="fa fa-briefcase"></i></sup>')
[ "def export_to_html(org_filename):\n if not org_filename.endswith(ORG_FILE_EXTENSION):\n raise Exception(\"Must provide an org-mode file.\")\n\n output_lines = []\n title, language, date, tags, author, description = \"\", \"\", \"\", \"\", \"\", \"\"\n with open(org_filename, 'r') as input:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces tech token with html representation
def tech(value): start_token = '<tech>' end_token = '</tech>' return value.replace(start_token,'<i class="technology">').replace(end_token,'</i>&nbsp;<sup><i class="fa fa-file-screen"></i></sup>')
[ "def clean_kspon(token: str) -> str:\n token = replace_number_token(token)\n token = remove_erroneous_tags(token)\n token = replace_double_space(token)\n return token", "def __handle_raw_html_token(cls, output_html, next_token, transform_state):\n _ = transform_state\n\n return \"\".join...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the INDRA Statement corresponding to a given rule by name.
def _stmt_from_rule(model, rule_name, stmts): stmt_uuid = None for ann in model.annotations: if ann.predicate == 'from_indra_statement': if ann.subject == rule_name: stmt_uuid = ann.object break if stmt_uuid: for stmt in stmts: if stmt....
[ "def get_rule(node_name: str):\n rule_name = get_rule_name(node_name)\n return Rule(rule_name)", "def get_replication_rule_by_name(self, name):\n LOG.info(\"Getting replication_rule details by name: '%s'\" % name)\n return self.rest_client.request(\n constants.GET,\n cons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the maximum length of the longest ORF over num_trials shuffles of the specfied DNA sequence
def longest_ORF_noncoding(dna, num_trials): for x in range (0,num_trials): shuffle= shuffle_string(dna) maxlengthORF= longest_ORF(shuffle) return maxlengthORF
[ "def longest_ORF_noncoding(dna, num_trials):\n longest_length = 0\n for i in range(0, num_trials):\n \tshuffled_dna = shuffle_string(dna)\n \tshuffled_dna_longest_length = len(longest_ORF(shuffled_dna))\n \tif shuffled_dna_longest_length > longest_length:\n \t\tlongest_length = shuffled_dna_longes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the frame number at the topleft corner of the frame.
def draw_frame_num(image, frame_num): cv2.putText(image, '{}'.format(frame_num), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), thickness=2) return image
[ "def _draw_number(number, pos, frame):\n width, height, _ = number.shape\n\n # Calculate box.\n num_x, num_y = pos\n num_x_start = num_x - width / 2\n num_x_end = num_x + width / 2\n num_y_start = num_y - width / 2\n num_y_end = num_y + width / 2\n\n # We make this additive to two numbers can safely overlap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the box with an ID tag for a tracked target.
def draw_target_box(image, box, id, draw_center=False): image = cv2.rectangle(image, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), _colors[int(id) % _colors.__len__()], thickness=3) id_string = '{:d}'.format(int(id)) id_size, baseline = cv2.getTextSize(id_string, cv2.FONT...
[ "def draw_target(self, col=(255,0,0)):\r\n\t\tself.app.fill(*col)\r\n\t\tself.app.ellipse(self.target_center.x, self.height-self.ground_height, 10,10)\r\n\t\tself.app.rect(self.target_pos, self.height-self.ground_height, self.target_size, self.ground_height)", "def _get_new_id(self, *bbox, **options) -> int:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the prediction box with an ID tag for a tracked target.
def draw_target_prediction(image, box): image = cv2.rectangle(image, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (255, 255, 255), thickness=1) return image
[ "def draw_instance_predictions(self, predictions, track_ids):\n boxes = predictions.pred_boxes if predictions.has(\"pred_boxes\") else None\n scores = predictions.scores if predictions.has(\"scores\") else None\n classes = predictions.pred_classes if predictions.has(\"pred_classes\") else None\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the skeleton for a tracked target..
def draw_target_skeleton(image, keypoints, id): for connection in _keypoint_connections: image = cv2.line(image, (int(keypoints[connection[0]][0]), int(keypoints[connection[0]][1])), (int(keypoints[connection[1]][0]), int(keypoints[connection[1]][1])), ...
[ "def draw_skeleton(self):\n raise NotImplementedError", "def draw_skeleton_image(self, ax, array):\n draw_array(ax, array)", "def draw_snake(self):\n # Draw the head\n self._draw_head()\n\n # Draw the rest of the body\n if len(self.body) > 0:\n self._draw_bod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a name this will resolve the full list of actions, in the correct order, and return a list of names
def resolve(cls, name, seen=None): action = cls.get(name) resolved = deque() if seen is None: seen = [] elif name in seen: return [] seen.append(name) def find_in_instances(find_name, attr): """Closure to find the current name in our ...
[ "def get_actions_names(self, name):\n actions = []\n resp_rule = self.get(name)\n resp_actions = resp_rule[\"Actions\"] \n if isinstance(resp_actions, list):\n for resp_action in resp_actions:\n actions.append(resp_action[\"value\"])\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load any class object stored with Pickle. Create and store a new instance in case it doesn't exist.
def load_pickle_object(filename, class_name, class_args): try: with open(filename, 'rb') as f: loaded_object = pickle.load(f) # except (OSError, IOError) as e: except Exception as e: loaded_object = class_name(*class_args) with open(filename, 'wb') as f: pic...
[ "def load_obj(path):\n with open(path, \"rb\") as f:\n return pickle.load(f)", "def load_obj(name):\r\n with open(name + '.pkl', 'rb') as f:\r\n return pickle.load(f)", "def pickle_main(f_name, pickle_source, do_pickle, instance = None):\n \n if do_pickle and instance is not None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Note This function requires the UGCNormal normalizer to be on the parent directory.
def normalize_corpus(input_folder, output_folder): subprocess.call(['../UGCNormal/ugc_norm.sh', input_folder, output_folder])
[ "def _normalise_path(self, path: str) -> str:\n return os.path.normpath(os.path.normcase(path))", "def preproc(indir, outdir):\n subdirs = glob.glob(indir + '/*')\n for i,subdir in enumerate(subdirs):\n print \"Preprocessing directory {} of {}\".format(i+1, len(subdirs))\n files = glob....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
change the messages into the desired form 1. change the toAddresses value to a list.
def format_messages(messages: list): for message in messages: to_addresses = message.get('toAddresses') if isinstance(to_addresses, str): message['toAddresses'] = argToList(to_addresses) return messages
[ "def sendall_recipient_addresses() -> List[str]:\n return [to_address(0x1234)]", "def _transform_recipients(self):\n # Extract recipients\n addrs = email.utils.getaddresses(self._message.get_all(\"TO\", [])) + \\\n email.utils.getaddresses(self._message.get_all(\"CC\", [])) + \\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get messages from a threat and return only the messages that are in the time range
def get_messages_by_datetime(client: Client, threat_id: str, after: str, before: str): messages = [] res = client.get_threat(threat_id) for message in res.get('messages'): # messages are ordered from newest to oldest received_time = message.get('receivedTime') if before >= received_t...
[ "def filter_time_range(messages, time_keys, start_time_inclusive, end_time_inclusive):\n # De-duplicate time_keys\n assert isinstance(time_keys, set)\n\n log.debug(f\"Filtering out messages sent outside the time range \"\n f\"{start_time_inclusive.isoformat()} to {end_time_incl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get list of all threats ids in the time range
def get_list_threats(client: Client, after: str, before: str): threats = [] is_next_page = True page_number = 1 while is_next_page: params = assign_params(pageSize=1000, filter=f'receivedTime gte {after} lte {before}', pageNumber=page_number) res = client.list_threats(params) thr...
[ "def all_timestamps():\n ts = current_timestamp()\n return list(range(ts - history_sec, ts, aggregation_interval_sec))", "def get_ids():", "def get_incidents_since(hours):\n\n def get_since(hours):\n\n now = datetime.utcnow()\n since = now - timedelta(hours=hours)\n\n return since\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read Object File Format (.off) into Numpy 3D array.
def load_off(filename, size): # create 3D array (cube with edge = size) obj = np.zeros([size, size, size]) # open filename.off with open(filename) as f: # read first line header = f.readline() # returns a string # set properties properties = f.readlin...
[ "def data_from_fileobj(self, fileobj):\n dtype = self.get_data_dtype()\n shape = self.get_data_shape()\n offset = self.get_data_offset()\n return array_from_file(shape, dtype, fileobj, offset,\n order=self.data_layout)", "def cube_to_array(fname):\n cub...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load all files from a folder into a 4D nupmy array.
def load_folder(folder, size): # create a 4D array with first dimension the number of files num_files = len(os.listdir(folder)) print(folder, "contains", num_files, "objects.") dataset = np.zeros([num_files, size, size, size]) for index, filename in enumerate(os.listdir(folder)): print("\n...
[ "def get_data():\n frames = []\n filenames = []\n for imname in sorted(os.listdir(folder), key=numericalSort):\n if not imname.startswith('.'):\n im = imageio.imread(folder+'/'+imname)\n #im = im[:,180:1100,:]\n im = im[:,275:1000,:]\n im = skimage.transfo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a 3d solid using points with straight connections edges, azimuth_placement_angle and rotation_angle.
def create_solid(self): # Creates a cadquery solid from points and revolves solid = ( cq.Workplane(self.workplane) .polyline(self.points) .close() .extrude(distance=-self.distance / 2.0, both=self.extrude_both) ) # Checks if the azimuth_p...
[ "def solid(self):\n return RotatedShape(shape_in=self.endplate.solid,\n rotation_point=self.position.point,\n vector=self.main[0].surface.position.orientation.Vx,\n angle=radians(-self.cant),\n label=\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a random initial configuration with values from 0 to base1 inclusive and, if positional arguments are given, use the supplied percentages for the different states.
def __init__(self, base=2, *percentages): self.values = range(base) self.percentages = percentages self.make_percentages_cumulative(percentages)
[ "def init_params_random(self) -> None:\n self.probs = Dirichlet(self.prior).sample()", "def random_param_init(dim):\n # TODO\n pass", "def init_params_random(self) -> None:\n prec_m = Gamma(self.prec_alpha_prior,\n self.prec_beta_prior)\n self.precs = prec_m.samp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turns a function that takes the radius and maximum distance as arguments into a function compatible with the `DensityDistributedConfiguration` class.
def function_of_radius(function, max_dist="diagonal"): if max_dist == "shortest": calc_max_dist = lambda size: min(size) elif max_dist == "longest": calc_max_dist = lambda size: max(size) elif max_dist == "diagonal": def calc_max_dist(size): halves = [num / 2 for num in s...
[ "def create_evaluate_func_deap(self) -> typing.Callable:\n def evaluate_function(values: typing.List) -> typing.Tuple:\n \"\"\"\n Simply map the chromosome values into a dict like the original config file and return that to the evaluate function\n :param values: the \"chromos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a set of parameters for the neural network
def initialize_parameters(self): self.n_inputs = len(self.df.columns[:-1]) self.n_hidden_per_layer = 3 self.n_hidden = 2 self.n_outputs = len(self.df.Class.unique()) if self.c_t == "classification" else 1 self.learning_rate = .07 self.epochs = 3 self.momentum_fac...
[ "def __initialize_parameters(self):\n parameters = dict()\n parameters['weights_recognition'] = {\n 'l1': numpy.random.normal(loc=0.,\n scale=0.01,\n size=(self.__nb_visible, self.__nb_hidden)),\n 'mean': n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Backpropagates errors through neural network, assigning a delta weight value to each node. This delta weight value is the change that the node will make to its weight
def backpropagate(self, expected): #Assigns delta values to each node in the output layer and calculates momentum for i in range(len(self.output_layer)): node = self.output_layer[i] node.delta_weight = expected[i] - node.output #Backpropagates errors through hidden laye...
[ "def backpropagate(self, outputs, learning_rate, momentum):\n errors = {}\n for node in self.nodes:\n calculated_value = self.values[node]\n real_value = outputs[node - 1]\n\n errors[node] = ((real_value - calculated_value) *\n calculated_val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Goes through and updates all the weights utilizing input values, node weights, and the learning rate
def update_node_weights(self, inputs): #Iterates through each node in each layer for i in range(len(self.NN)): for node in self.NN[i]: #Iterates through each value in the inputs and assigns weights for j in range(len(inputs)): #Multiplies ...
[ "def update_weight(self, learn_rate):\n pass", "def update_weights(self) -> None:\n for neuron in self.__neurons__:\n neuron.update_weight(self.__inputs__)", "def update_weights(self):\n for layer in xrange(len(self.weights)):\n self.update_weights_layer(layer)", "def up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns on array of all weights in the network for training use
def get_weights(self): weights = [] for layer in self.NN: for node in layer: for weight in node.weights: weights.append(weight) return weights
[ "def get_weights(self, ):\n return [w for l in self.weights for w in l.flat]", "def get_all_weights(self):\n\n # add weights for each layer if layer is a Dense layer and return the list\n return [l.weights for l in self.layers if isinstance(l, Dense)]", "def weights ( self ) :\n N = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the weights of the nodes in the network after training them
def set_weights(self, weights): weight_index = 0 for layer in self.NN: for node in layer: for i in range(len(node.weights)): #print(weight_index) try: node.weights[i] = weights[weight_index] ...
[ "def set_weights(self, weights):\n self.actor_critic.load_state_dict(weights)\n self.alpha_optimizer.step()\n self.alpha = self.log_alpha.detach().exp()\n\n # Update target networks by polyak averaging.\n self.iter += 1\n self.update_target_networks()", "def do_change_nod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set flavors in a list
def store_flavors(self, *flavors_list): self.flavors = flavors_list return self
[ "def flavor_aware_sync_flavors(context, event):\n flavors = interfaces.IFlavors(context).content_flavors # tuple of names\n anno = IAnnotations(context)\n anno[interfaces.FLAVORS_KEY] = flavors", "def flavors(self, **kwargs):\n flavors = AwsFlavor(session=self.session)\n data = flavors.fet...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }