query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Get data from the spreadsheet.
def read(rng, sheets_service=_sheets_service, spreadsheet_id=None): # Get the default spreadsheet ID if it's not provided # (Do this instead of setting the default in the kwargs so that a user # can import gsheet;SPREADSHEET_ID = 'whatever'. if spreadsheet_id is None: spreadsheet_id = SPREADSHE...
[ "def _get_sheet_data(spreadsheet_id: str, worksheet_title: str, row_num_start: int = None, row_num_end: int = None) -> List[List]:\n rng = worksheet_title\n if row_num_start:\n rng += f'!{row_num_start}'\n if row_num_end:\n if not row_num_start:\n rng += f'!1'\n rng += f':{r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if circuits is the empty tensor.
def _check_empty(circuits): return len(circuits) == 0
[ "def is_empty(self):\n return len(self._rhs) == 0", "def is_empty(self):\r\n if self.discs == []:\r\n return True\r\n else:\r\n return False", "def is_empty(self):\n return len(self.vertices) == 0 and len(self.edges) == 0", "def is_empty(self):\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute states from a batch of circuits. Returns a NumPy array containing the final circuit state for each `cirq.Circuit` in `circuits`, given that the corresponding `cirq.ParamResolver` in `param_resolvers` was used to resolve any symbols in it. If simulator is a `cirq.DensityMatrixSimulator` this final state will be ...
def batch_calculate_state(circuits, param_resolvers, simulator): _validate_inputs(circuits, param_resolvers, simulator, 'analytic') if _check_empty(circuits): empty_ret = np.zeros((0, 0), dtype=np.complex64) if isinstance(simulator, cirq.DensityMatrixSimulator): empty_ret = np.zeros(...
[ "def batch_calculate_expectation(circuits, param_resolvers, ops, simulator):\n _validate_inputs(circuits, param_resolvers, simulator, 'expectation')\n\n if _check_empty(circuits):\n return np.zeros((0, 0), dtype=np.float32)\n\n if not isinstance(ops, (list, tuple, np.ndarray)):\n raise TypeEr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute expectations from a batch of circuits. Returns a `np.ndarray` containing the expectation values of `ops` applied to a specific circuit in `circuits`, given that the corresponding `cirq.ParamResolver` in `param_resolvers` was used to resolve any symbols in the circuit. Specifically the returned array at index `i...
def batch_calculate_expectation(circuits, param_resolvers, ops, simulator): _validate_inputs(circuits, param_resolvers, simulator, 'expectation') if _check_empty(circuits): return np.zeros((0, 0), dtype=np.float32) if not isinstance(ops, (list, tuple, np.ndarray)): raise TypeError('ops mus...
[ "def batch_calculate_sampled_expectation(circuits, param_resolvers, ops,\n n_samples, sampler):\n _validate_inputs(circuits, param_resolvers, sampler, 'sample')\n if _check_empty(circuits):\n return np.zeros((0, 0), dtype=np.float32)\n\n if not isinstance(ops, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute expectations from sampling a batch of circuits. Returns a `np.ndarray` containing the expectation values of `ops` applied to a specific circuit in `circuits`, given that the corresponding `cirq.ParamResolver` in `param_resolvers` was used to resolve any symbols in the circuit. Specifically the returned array at...
def batch_calculate_sampled_expectation(circuits, param_resolvers, ops, n_samples, sampler): _validate_inputs(circuits, param_resolvers, sampler, 'sample') if _check_empty(circuits): return np.zeros((0, 0), dtype=np.float32) if not isinstance(ops, (list, tupl...
[ "def batch_calculate_expectation(circuits, param_resolvers, ops, simulator):\n _validate_inputs(circuits, param_resolvers, simulator, 'expectation')\n\n if _check_empty(circuits):\n return np.zeros((0, 0), dtype=np.float32)\n\n if not isinstance(ops, (list, tuple, np.ndarray)):\n raise TypeEr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample from circuits. Returns a `np.ndarray` containing n_samples samples from all the circuits in circuits given that the corresponding `cirq.ParamResolver` in `param_resolvers` was used to resolve any symbols. Specifically the returned array at index `i,j` will correspond to a `np.ndarray` of booleans representing bi...
def batch_sample(circuits, param_resolvers, n_samples, simulator): _validate_inputs(circuits, param_resolvers, simulator, 'sample') if _check_empty(circuits): return np.zeros((0, 0, 0), dtype=np.int8) if not isinstance(n_samples, int): raise TypeError('n_samples must be an int.' ...
[ "def batch_calculate_sampled_expectation(circuits, param_resolvers, ops,\n n_samples, sampler):\n _validate_inputs(circuits, param_resolvers, sampler, 'sample')\n if _check_empty(circuits):\n return np.zeros((0, 0), dtype=np.float32)\n\n if not isinstance(ops, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rerank the test predict paraphrases according to the ranker
def rerank(test_predicted_paraphrases, test_features, ranker, minimum_score): new_test_predicted_paraphrases = { (w1, w2) : [] for (w1, w2) in test_predicted_paraphrases.keys() } for ((w1, w2), curr_paraphrases), curr_paraphrase_features in tqdm.tqdm(zip( test_predicted_paraphrases.items(), test_fe...
[ "def predict(self):\n # score prediction for unigrams\n if self.real_score > self.fake_score:\n self.is_fake = 0\n else:\n self.is_fake = 1\n\n # score prediction for bigrams\n if self.bi_real_score > self.bi_fake_score:\n self.bi_is_fake = 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses the Java scorer class to evaluate the current predictions against the gold standard
def evaluate(predictions, gold_file, out_prediction_file): # Save the evaluations to a file with codecs.open(out_prediction_file, 'w', 'utf-8') as f_out: for (w1, w2), curr_paraphrases in predictions.items(): for paraphrase, score in curr_paraphrases: f_out.write('\t'.join((w...
[ "def evaluate(self,simplifier):\n \n for complex_word,gold_standard in self.eval_data.items():\n \n candidates = simplifier.simplify_word(complex_word)\n \n if candidates:\n self.update_scores(candidates,gold_standard)\n \n scores = self.get_average_scores()\n \n logg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the language model and retrieves the best k paraphrases for each nouncompound.
def predict_paraphrases(model, noun_compounds, words, word2index, UNK, k, unrelated_threshold): paraphrases = {(w1, w2): defaultdict(float) for (w1, w2) in noun_compounds} for (w1, w2) in tqdm.tqdm(noun_compounds): w1_index, w2_index = word2index.get(w1, UNK), word2index.get(w2, UNK) # Returns...
[ "def load_language_model(model_file):\n from collections import defaultdict\n prob_of = defaultdict(float)\n for line in open(model_file, 'r'):\n line = line.strip()\n (word, P) = line.split(\"\\t\")\n word = word.decode(\"utf-8\")\n prob_of[word] = float(P)\n\n def get_bigram_prob(prev_word,curr_wo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the paraphrase word indices and returns the text
def get_paraphrase_text(words, par_indices): paraphrase_words = [words[i] for i in par_indices] paraphrase = ' '.join(paraphrase_words) yield paraphrase
[ "def compute_paraphrase_vector(w1, w2, paraphrase, model, word2index, UNK):\n paraphrase = paraphrase.replace(w1, '[w1]').replace(w2, '[w2]')\n par_indices = tuple([word2index.get(w, UNK) for w in paraphrase.split()])\n return model.__compute_state__(par_indices, -1).npvalue()", "def extract_noun_phrases...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a list of ranked paraphrases for each nouncompound and extracts features from them
def generate_features(paraphrases, pos2index, prep2index, model, wv, word2index, UNK): features = [] for (w1, w2), curr_paraphrases in tqdm.tqdm(paraphrases.items()): features.append([extract_paraphrase_features(w1, w2, paraphrase, pos2index, prep2index, mode...
[ "def extract_nouns_from_stanford_pos():\n noun_list_after_chunk = []\n\n pos_tagged_text = database.fetach_pos_tagged_sentence()\n\n chunk_reg_express = r\"\"\"NP: {<JJ>*<NN.*>}\"\"\" \n chunk_parsar = nltk.RegexpParser(chunk_reg_express)\n\n for review_id, pos_tagged_content in pos_tagged_text:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a textual paraphrase and returns its vector
def compute_paraphrase_vector(w1, w2, paraphrase, model, word2index, UNK): paraphrase = paraphrase.replace(w1, '[w1]').replace(w2, '[w2]') par_indices = tuple([word2index.get(w, UNK) for w in paraphrase.split()]) return model.__compute_state__(par_indices, -1).npvalue()
[ "def get_paraphrase_text(words, par_indices):\n paraphrase_words = [words[i] for i in par_indices]\n paraphrase = ' '.join(paraphrase_words)\n yield paraphrase", "def extract_noun_phrases(text: str) -> TextBlob:\n blob = TextBlob(text)\n return blob.noun_phrases", "def get_text():", "def get_ph...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the train gold file
def load_gold(train_gold_file): with codecs.open(train_gold_file, 'r', 'utf-8') as f_in: lines = [line.strip().split('\t') for line in f_in] train_gold = { (w1, w2) : {} for (w1, w2, paraphrase, score) in lines } for w1, w2, paraphrase, score in lines: train_gold[(w1, w2)][paraphrase] = flo...
[ "def train(self, trainfile):", "def load(self):\n latest = tf.train.latest_checkpoint(self.checkpoint_dir)\n self.model.load_weights(latest)", "def __init__(self, goldFile, testFile):\n # Read the labeled evaluation corpora\n self.pred_corpus = HMM.read_labeled_data(testFile)\n self.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws the maze, the dots in it and the number of PacMan's life.
def draw(self, DISP, life_counter:int, level:int): assert self.is_init, 'Call first Game_Field.init() before draw game!' y_count,x_count = 3, 0 start_maze = 0, 0 DISP.fill(Colors.colors['BLACK']) # Maze get blit on the Screen of the game DISP.blit(self.maz...
[ "def draw_pacman_life(self, life_counter, DISP):\r\n for i in range(1, life_counter):\r\n # Position depends on the value i\r\n # Draw yellow circle\r\n pg.draw.circle(DISP, Colors.colors['YELLOW'], (i * self.grid_size * 2, self.grid_size * 35), 20)\r\n # Draw Pac-...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the spwan position of the asked Object.
def find_startpos(self, searched_object:str): fak = 1 #< When the figure needs to be pushed to the right -> fak = 1 else fak = 0 # The main figures spwan position beginns at index 14 and ends at size(self.look_up_table) - 9 start_index = 14 y = start_index end_index = -9 ...
[ "def getPosition(self, n):\n return self._get_at(n).obj", "def _current_position(stream_obj):\n return stream_obj.pos", "def get_pos(self):\n return self.position", "def _current_position(stream_obj):\n pass", "def get_position(self):\n return self.position", "def pos(self):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws a blackline (if pink is False otherwise the line will be pink) on the position (indizes[0] grid_size, indizes[1] grid_size). Side indicates whether the line should be drawn horizontally or vertically. Possible values {'u', 'l'} 'u' > Up ; 'l' > Left
def draw_line(self, DISP, side:str, indizes:tuple, pink = False): offset = 1 #< Just to draw the line nicely pos = (indizes[0] - 1) * self.grid_size, indizes[1] * self.grid_size # Check if it's a pink line if pink: start_pos = pos[0], pos[1] + self.grid_size // 2 ...
[ "def draw_gray_grid(self):\n gray = \"#D3D3D3\"\n # Draw the vertical lines\n for x in range(0, self.width, self.scale):\n self.canvas.create_line(x, 0, x, self.height, fill=gray)\n\n # Draw the horizontal lines\n for y in range(0, self.height, self.scale):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws PacMan's life amount in the bottom left.
def draw_pacman_life(self, life_counter, DISP): for i in range(1, life_counter): # Position depends on the value i # Draw yellow circle pg.draw.circle(DISP, Colors.colors['YELLOW'], (i * self.grid_size * 2, self.grid_size * 35), 20) # Draw Pac-Man's mouth as ...
[ "def display_life(self, screen, life_img):\n distance = 190\n for i in range(self.life):\n screen.blit(life_img, (distance, 0))\n distance += 60", "def draw_pavement():\n\n roberto.penup()\n roberto.goto(-345, -100)\n roberto.pendown()\n roberto.begin_fill()\n fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws either 'READY!' or 'GAMER OVER!' on the screen depending on how much life PacMan has left.
def draw_ready_lose(self, DISP, life_counter = 1): # When the life_counter isn't 0 that means Pac-Man is still alive and 'READY!' will be drawn in yellow if life_counter != 0: string = 'READY!' color = Colors.colors['YELLOW'] # When the life_counter is 0 that means P...
[ "def draw_game_over(self):\n arcade.draw_rectangle_filled(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2,\n SCREEN_WIDTH // 2,\n SCREEN_HEIGHT // 1.5, arcade.color.BRONZE)\n arcade.draw_rectangle_filled(SCREEN_WIDTH // 2, 410, 600, 140, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the look up table.
def reset(self): self.look_up_table = list(map(convert_to_list, self.const_look_up_table))
[ "def reset(self):\n\n self.state = np.array(self.HOME)\n self.state_history = [self.state]\n self.fk_cache = dict()", "def __reset__(self) -> None:\n self._table: Table = Table()", "def reset_the_db(_step):\r\n reset_data(None)", "def reset(self):\n self.search_dict = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convertes the element to a list and return it. Is needed to convert the const_look_up_table to changeable list.
def convert_to_list(element): return list(element)
[ "def convert_to_list(self, item):\n return list(item)", "def _convert_to_list(self, input_argument):\n if type(input_argument) is not list:\n input_argument = [input_argument]\n return input_argument", "def __tolist(self, mylist):\n if mylist is None:\n return N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To get the article images of a particular article
def article_images(id): try: query_string = '&artile_id='+str(id) logger.info('Calling the api' + APIURL + '/images/?format=json'+query_string) response = requests.get(APIURL + '/images/?format=json'+query_string) parser = json.loads(response.content) return parser exce...
[ "def get_images(self, article: BeautifulSoup):\n images = []\n content = article.select_one(self.parsing_template.content)\n\n if content:\n body_images = content.select(self.parsing_template.image_element)\n else:\n body_images = None\n\n if body_images:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To show the article with the search functionality
def search_news(request): try: query_string = '' if request.GET['search_text'].strip() != '': query_string = '&title='+request.GET['search_text'] response = requests.get(APIURL + '/articles/?format=json'+query_string) parser = json.loads(response.content) return ...
[ "def articleSearch(article_name):\n search_article_name = article_name.split(\"\")\n search_name_format = \"+\".join(search_article_name)\n searched_articles = search_articles(search_name_format)\n\n return render_template('search.html',articles = searched_articles)", "def search(request):\n if 'q'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return version number applicable to the run_id. Most plugins just have a single version (in .__version__) but some may be at different versions for different runs (e.g. timedependent corrections).
def version(self, run_id=None): return self.__version__
[ "def get_model_run_version(self, model_run):\n return model_run.version + self.get_internal_model_run_version(model_run)", "def get_internal_model_run_version(self, model_run):\n key = self.get_model_run_key(model_run)\n if key not in self.model_run_version:\n return 0\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return dependencies grouped by data kind
def dependencies_by_kind(self, require_time=None): if require_time is None: require_time = \ len(self.dependencies_by_kind(require_time=False)) > 1 deps_by_kind = dict() key_deps = [] for d in self.depends_on: k = self.deps[d].data_kind ...
[ "def _dependencies_dict(self, deptype=\"all\"):\n _sort_fn = lambda x: (x.spec.name,) + _sort_by_dep_types(x)\n _group_fn = lambda x: x.spec.name\n deptype = dp.canonical_deptype(deptype)\n selected_edges = self._dependencies.select(deptypes=deptype)\n result = {}\n for key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function formats allcause mortality to be used for the ratein files.
def format_mortality_for_rate_in(mortality, input_dir): # calculate what we need for age inputs ages = get_age_bounds(input_dir) mortality = mortality.merge(ages, on = ['age_group_id']) mortality["age"] = (mortality["age_lower"] + mortality["age_upper"]) / 2 # in the function that c...
[ "def formatter(text):\n repl_map = {\n \"degC\": \"$^o$C\",\n \"K\": \"$^o$C\",\n \"month-1\": \"month$^{{-1}}$\",\n \"day-1\": \"day$^{{-1}}$\",\n \"d-1\": \"day$^{{-1}}$\",\n \"decade-1\": \"decade$^{{-1}}$\",\n \"year-1\": \"year...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Defines the Vagrant virtual machine's environment variables. Environments define and contain the information need to SSH into a server, e.g. IP address, SSH key, username, and possibly password.
def vagrant(): # Use Python's subprocess to run 'vagrant ssh-config' and parse results raw_ssh_config = subprocess.Popen(['vagrant', 'ssh-config'], stdout=subprocess.PIPE).communicate()[0] ssh_config = dict([l.strip().split() for l in raw_ssh_config.split("\n") ...
[ "def development():\n # Change the default user to 'vagrant'.\n result = api.local('vagrant ssh-config | grep IdentityFile', capture=True)\n api.env.key_filename = result.replace('\"', '').split()[1]\n api.env.user = 'vagrant'\n\n # Connect to the port-forwarded ssh.\n api.env.hosts = ['127.0.0.1:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Install the Python package 'virtualenv' so we can install Python packages safely into a virtualenv and not the system Python.
def sub_install_virtualenv(): sudo('pip install virtualenv') # Need sudo b/c installing to system Python
[ "def setup_virtualenv():\r\n run('virtualenv -p %(python)s --no-site-packages %(env_path)s;' % env)\r\n run('source %(env_path)s/bin/activate; easy_install -U setuptools; easy_install pip;' % env)", "def setup_virtualenv():\n run('virtualenv -p %(python)s --no-site-packages %(env_path)s;' % env)\n run...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Install the Flask apps' Python requirements into the virtualenv. We need to activate the virtualenv before installing into it. We do that with the command 'source /server/bin/activate'. The application requirements live in the requirements.txt file shared with the VM. This file lives at /vagrant/flask_ml/requirements.t...
def sub_install_python_requirements(): # Activate the virtualenv activate = 'source {0}/{1}/bin/activate'.format( env.virtualenv['dir'], env.virtualenv['name']) run(activate) # Install Python requirements install = 'pip install -r /vagrant/Flask_app/requirements.txt' # Join and execute...
[ "def sub_install_python_requirements_aws():\n # Activate the virtualenv\n activate = 'source {0}/{1}/bin/activate'.format(\n env.virtualenv['dir'], env.virtualenv['name'])\n run(activate)\n\n # make sure the directory is there\n run('mkdir -p /home/ubuntu')\n\n # put the local directory '/U...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the Flask development server on the VM.
def dev_server(): # Activate the virtualenv activate = 'source {0}/{1}/bin/activate'.format( env.virtualenv['dir'], env.virtualenv['name']) # Run the file app.py to start the Flask app dev_server = 'python vagrant/Flask_app/app.py' run(activate + '; ' + dev_server)
[ "def runserver():\n\n print green(\"Running the development webserver...\")\n denv = fabutils.dot_env()\n host = denv.get('SERVER_HOST', '0.0.0.0')\n port = denv.get('PORT', '8000')\n fabutils.manage_py('runserver %s:%s' % (host, port))", "def run(site):\n\n # Run the \"startdevserver\" scri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Install the Flask apps' Python requirements into the aws. We need to activate the virtualenv before installing into it. We do that with the command 'source /server/bin/activate'. We copy the Flask apps' directory using Fabric's copy mechanism to /home/ubuntu. The application requirements live in the requirements.txt fi...
def sub_install_python_requirements_aws(): # Activate the virtualenv activate = 'source {0}/{1}/bin/activate'.format( env.virtualenv['dir'], env.virtualenv['name']) run(activate) # make sure the directory is there run('mkdir -p /home/ubuntu') # put the local directory '/Users/jenniferc...
[ "def sub_install_python_requirements():\n # Activate the virtualenv\n activate = 'source {0}/{1}/bin/activate'.format(\n env.virtualenv['dir'], env.virtualenv['name'])\n run(activate)\n\n # Install Python requirements\n install = 'pip install -r /vagrant/Flask_app/requirements.txt'\n\n # Jo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the specified configuration file, return an instance of ConfigObj with the file contents. If no file is specified, look in the standard locations for weewx.conf. Returns the filename of the actual configuration file, as well as the ConfigObj.
def read_config(config_path, args=None, locations=DEFAULT_LOCATIONS, file_name='weewx.conf'): # Find and open the config file: config_path = find_file(config_path, args, locations=locations, file_name=file_name) # Now open it up and parse it. config_dict = con...
[ "def read_config_file(self, f):\n configspec = self.default_file if self.validate else None\n try:\n config = ConfigObj(\n infile=f, configspec=configspec, interpolation=False, encoding=\"utf8\"\n )\n # ConfigObj does not set the encoding on the configsp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a driver has a configuration editor, then use that to insert the stanza for the driver in the config_dict. If there is no configuration editor, then inject a generic configuration, i.e., just the driver name with a single 'driver' element that points to the driver file.
def modify_config(config_dict, stn_info, logger, debug=False): driver_editor = None driver_name = None driver_version = None # Get the driver editor, name, and version: driver = stn_info.get('driver') if driver: try: # Look up driver info: driver_editor, driver_n...
[ "def _configure(self, driver_config):\n\n #\n # NOTE the \"pnode\" parameter may be not very \"standard\" but it is the\n # current convenient mechanism that captures the overall definition\n # of the corresponding platform (most of which coming from configuration)\n #\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge the configuration dictionary into the template dictionary, overriding any options. Return the results.
def merge_config(config_dict, template_dict): # Turn off interpolation so what gets merged is the symbolic name # (such as WEEWX_ROOT), and not its interpolated value. csave, config_dict.interpolation = config_dict.interpolation, False tsave, template_dict.interpolation = template_dict.interpolation, ...
[ "def apply_merge_template(\n self, template_name: str, dry_run: Optional[bool] = True\n ):\n\n config = self.nornir.run(\n task=self.render_template_apply, \n template_name=template_name\n )\n\n return config", "def update_configuration_template(self, Appli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract station info from config dictionary.
def get_station_info(config_dict): stn_info = dict() if config_dict is not None: if 'Station' in config_dict: stn_info['location'] = weeutil.weeutil.list_as_string(config_dict['Station'].get('location')) stn_info['latitude'] = config_dict['Station'].get('latitude') st...
[ "def get_station(self, station_name):\n\n station_info = {}\n for stn in self.stations:\n station_names = [stn['name'].lower(), stn['locationCode'].lower()]\n if station_name.lower() in station_names:\n station_info.update(**stn)\n break\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the section with key src to just before (after=False) or after (after=True) the section with key dst.
def reorder_sections(config_dict, src, dst, after=False): bump = 1 if after else 0 # We need both keys to procede: if src not in config_dict.sections or dst not in config_dict.sections: return # If index raises an exception, we want to fail hard. # Find the source section (the one we intend ...
[ "def insert_after(dst, src):\n if not is_valid_pos(*dst) or not is_valid_pos(*src):\n return False\n dst_block, dst_index = pos_2_block_n_index(*dst)\n src_block, src_index = pos_2_block_n_index(*src)\n dst_block.insert(dst_index + 1, deepcopy(src_block[src_index]))\n return True", "def move...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorder any sections in concordance with a reference ordering. See the definition for canonical_ordering for the details of the tuple used to describe a section.
def reorder_to_ref(config_dict, section_tuple=canonical_order): if not len(section_tuple): return # Get the names of any subsections in the order they should be in: subsection_order = [x[0] for x in section_tuple[1]] # Reorder the subsections, then the scalars config_dict.sections = reorder(...
[ "def reorder_sections(config_dict, src, dst, after=False):\n bump = 1 if after else 0\n # We need both keys to procede:\n if src not in config_dict.sections or dst not in config_dict.sections:\n return\n # If index raises an exception, we want to fail hard.\n # Find the source section (the one...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorder the names in name_list, according to a reference list.
def reorder(name_list, ref_list): result = [] # Use the ordering in ref_list, to reassemble the name list: for name in ref_list: # These always come at the end if name in ['FTP', 'RSYNC']: continue if name in name_list: result.append(name) # For any that w...
[ "def reorder(self, flair_list: list[str]):\n self._reorder(flair_list, is_link=False)", "def reorder(self, flair_list: list[str]):\n self._reorder(flair_list, is_link=True)", "def sort_by_name(list_to_sort):\n return sorted(\n list_to_sort,\n key=lambda k: k['Name'].lower()\n )...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove fields from a_dict that are present in b_dict
def remove_and_prune(a_dict, b_dict): for k in b_dict: if isinstance(b_dict[k], dict): if k in a_dict and type(a_dict[k]) is configobj.Section: remove_and_prune(a_dict[k], b_dict[k]) if not a_dict[k].sections: a_dict.pop(k) elif k in a_...
[ "def strip(a, b):\n out = {}\n for key, value in a.items():\n if key in b:\n out[key] = value\n return out", "def diff_dicts(x, y, ignored_keys=('age', 'load_dt')):\n new_data = {k: y[k] for k in y if k not in x}\n modified_data = {k: y[k] for k in y if k in x and y[k] != x[k] and...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepend the value to every instance of the label in dict a_dict
def prepend_path(a_dict, label, value): for k in a_dict: if isinstance(a_dict[k], dict): prepend_path(a_dict[k], label, value) elif k == label: a_dict[k] = os.path.join(value, a_dict[k])
[ "def prepend_name_dict(prefix, d):\n return {prefix + name: value for name, value in d.items()}", "def prepend_attribute_label(table, header):\n for row in table:\n for i in range(len(row)):\n row[i] = header[i] + \"=\" + str(row[i])", "def _reformat_attr_dict(self,atr_dict):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scan the drivers folder, extracting information about each available driver. Return as a dictionary, keyed by the driver module name. Valid drivers must be importable, and must have attribute "DRIVER_NAME" defined.
def get_driver_infos(driver_pkg_name='weewx.drivers', excludes=['__init__.py']): __import__(driver_pkg_name) driver_package = sys.modules[driver_pkg_name] driver_pkg_directory = os.path.dirname(os.path.abspath(driver_package.__file__)) driver_list = [os.path.basename(f) for f in glob.glob(os.path.join(...
[ "def _get_drivers(self):\n all_drivers = {}\n all_driver_files = get_direct_sub_files(self.pd_dir, abs_path=True, extension=compile_regex(\"^\\.py$\"))\n for file_path in all_driver_files:\n driver_name = get_dir_from_path(file_path).split(\".\")[0]\n if driver_name != \"_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get information about all the available drivers, then print it out.
def print_drivers(): driver_info_dict = get_all_driver_infos() keys = sorted(driver_info_dict) print "%-25s%-15s%-9s%-25s" % ( "Module name", "Driver name", "Version", "Status") for d in keys: print " %(module_name)-25s%(driver_name)-15s%(version)-9s%(status)-25s" % driver_info_dict[d]
[ "def print_drivers():\n for i in range(ogr.GetDriverCount()):\n driver = ogr.GetDriver(i)\n writeable = driver.TestCapability(ogr.ODrCCreateDataSource)\n print('{0} ({1})'.format(driver.GetName(),\n 'read/write' if writeable else 'readonly'))", "def print_dr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the configuration editor from the driver file
def load_driver_editor(driver_module_name): __import__(driver_module_name) driver_module = sys.modules[driver_module_name] editor = None driver_name = None driver_version = 'undefined' if hasattr(driver_module, 'confeditor_loader'): loader_function = getattr(driver_module, 'confeditor_lo...
[ "def confeditor_loader():\n return MQTTSubscribeDriverConfEditor()", "def confeditor_loader():\n return MQTTSubscribeDriverConfEditor() # pragma: no cover", "def load_config(self):\n self.config.readfp(open('defaults.cfg'))\n self.config.read([os.path.expanduser('~/.apertium-simple-viewer.cf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the installer in the given extension installer subdirectory
def get_extension_installer(extension_installer_dir): old_path = sys.path try: # Inject the location of the installer directory into the path sys.path.insert(0, extension_installer_dir) try: # Now I can import the extension's 'install' module: __import__('install'...
[ "def install(root, extension):", "def get_install_path():\n return install_path", "def extant_dir(arg):\n return extant_item(arg, \"directory\")", "def get_installer_path(self):\n\n return utilities.resolve_from_source(self.params.INSTALLER_PATH)", "def getInstallerExt(platform):\n return in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate and return the candidate to vote fractions (<= 1.0).
def calculate_vote_fractions(): return _calculate_vote_fractions(models.get_candidate_to_vote_count())
[ "def _calculate_vote_fractions(candidate_to_vote_count):\n total_votes = sum(candidate_to_vote_count.values()) or 1\n return {\n candidate: vote_count / total_votes\n for candidate, vote_count\n in candidate_to_vote_count.items()\n }", "def proportion_amount(self, votes_per_cand, sur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From a dictionary from candidate to vote count, calculate candidate to vote fractions (<= 1.0).
def _calculate_vote_fractions(candidate_to_vote_count): total_votes = sum(candidate_to_vote_count.values()) or 1 return { candidate: vote_count / total_votes for candidate, vote_count in candidate_to_vote_count.items() }
[ "def calculate_vote_fractions():\n return _calculate_vote_fractions(models.get_candidate_to_vote_count())", "def norm_parties_votes_to_pct(votes: VotingCounts) -> Mapping[str, float]:\n total_votes = sum(votes.values())\n normed_votes = {k: (v / total_votes if total_votes else 0.) for k, v in votes.items...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get interesting objects currently visible from the given latitude and longitude.
def get_visible_objects(lat, lon): visible = [] observer = ephem.Observer() observer.lat = str(lat) observer.lon = str(lon) for object_class in AstroObject.INTERESTING_OBJECTS: obj = object_class() obj.compute(observer) if obj.alt >= MIN_ALT: visible.append(AstroO...
[ "def get_visible_objects(self):\n visible_objects = self.bot_client.send_command(_Command.GetVisibleObjects)\n bots = [VisibleBot(**x) for x in visible_objects[\"bots\"]]\n energy_sources = [VisibleEnergySource(**x) for x in visible_objects[\"energy_sources\"]]\n bullets = [VisibleBullet...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Based on the nucleotide base context number, return a list of strings representing each context.
def get_all_context_names(context_num): if context_num == 0: return ['None'] elif context_num == 1: return ['A', 'C', 'T', 'G'] elif context_num == 1.5: return ['C*pG', 'CpG*', 'TpC*', 'G*pA', 'A', 'C', 'T', 'G'] elif context_num == 2: dinucs = list(set( ...
[ "def get_basestrings(self):\n baseStrs = set()\n for x in self.xvals():\n for y in self.yvals():\n p = self.get_plaquette(x, y)\n if p is not None and p.base is not None:\n baseStrs.add(p.base)\n return list(baseStrs)", "def get_cont...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves relevant information about the effect of a somatic SNV on the amino acid of a gene. Information includes the germline codon, somatic codon, codon position, germline AA, and somatic AA.
def get_aa_mut_info(coding_pos, somatic_base, gene_seq): # if no mutations return empty result if not somatic_base: aa_info = {'Reference Codon': [], 'Somatic Codon': [], 'Codon Pos': [], 'Reference Nuc': [], 'Reference AA': [],...
[ "def determine_aa_change( self ):\n for k,v in self.obj_mi.hash_isoforms.iteritems(): #k = string that is isoform_id, v = Isoform instance\n obj_tt = self.create_transcript_instances( k )\n\n #METHOD 1: get the original codon & mutated codon\n # orig_codon = obj_tt.ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all currently running threads as thread collection
def get_currently_running(cls, include_main_thread: bool = True) -> 'ThreadCollection': result = [] for thread in threading.enumerate(): # noinspection PyProtectedMember if not include_main_thread and isinstance(thread, threading._MainThread): continue ...
[ "def threads(self):\n return self.rpc.call(MsfRpcMethod.CoreThreadList)", "def get_threads(self) -> list:\n threads = []\n h_snapshot = kernel32.CreateToolhelp32Snapshot(\n winnt_constants.TH32CS_SNAPTHREAD, 0)\n thread_entry = kernel32.Thread32First(h_snapshot)\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a thread collection
def from_class(cls, cls_to_use, iteratable, **kwargs) -> 'ThreadCollection': return ThreadCollection([cls_to_use(it, **kwargs) for it in iteratable])
[ "def start_collection(cls):\n\n cls.collector_thread = threading.Thread(target=cls._start_collection)\n cls.collector_thread.setDaemon(False)\n cls.collector_thread.start()", "def __init__(self, threads=1):\n self.pools = ThreadPool(processes=threads)\n self.updater_queue = Queu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is any of the threads a daemon? Also, when used a setter sets daemon attribute.
def daemon(self) -> bool: return any(thread.daemon for thread in self.threads)
[ "def daemon(self):\n assert self._initialized, \"Thread.__init__() not called\"\n return self._daemonic", "def threads_alive(threads: List[TrendThread]):\n return True in [thread.isAlive() for thread in threads]", "def daemon(self, flag):\r\n self._th.daemon = flag", "def daemon(self):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a thread to the collection
def add(self, thread: Thread) -> 'ThreadCollection': self.threads.append(thread) return self
[ "def add(thread, run=True):\r\n\tlogging.debug('Adding thread ' + str(thread))\r\n\tpool.append(thread)\r\n\tif run:\r\n\t\tthread.start()", "def add(self, thread: Thread):\n if thread.url in self.threads.keys():\n self.threads[thread.url].update(thread)\n else:\n self.threads[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call terminate() on all threads that have this method
def terminate(self, *args, **kwargs) -> 'ThreadCollection': for thread in self.threads: try: thread.terminate(*args, **kwargs) except AttributeError: pass return self
[ "def terminate(self):\n for t in self._threads:\n t.quit()\n self._thread = []\n self._workers = []", "def terminate(self):", "def terminate(self):\n self._pool.terminate()", "def terminate(self):\n self._running = False", "def kill_threads(self):\n print('Th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is at least one thread alive?
def is_alive(self) -> bool: return any(thread.is_alive() for thread in self.threads)
[ "def alive(self):\n return self._thread is not None", "def isAlive(self):\r\n if self.thread is None:\r\n return False\r\n else:\r\n return self.thread.isAlive()", "def is_alive(self):\r\n return self.thread.is_alive()", "def other_threads_are_active():\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a thread collection or a thread to this collection and return a new collection
def __add__(self, other: tp.Union['ThreadCollection', Thread, tp.Iterable[Thread]]): if isinstance(other, Thread): other = [other] elif isinstance(other, ThreadCollection): other = other.threads else: other = list(other) return ThreadCollection(self.th...
[ "def add(self, thread: Thread) -> 'ThreadCollection':\n self.threads.append(thread)\n return self", "def add_to_collection(self, name, collection):\n try:\n module = __import__(name)\n candidates = filter(\n lambda x: isinstance(x[1], Task),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform the given move on the board; color gives the color pf the piece to play (1=white,1=black)
def execute_move(self, move, color): (x, y) = move # Add the piece to the empty square. assert self[x][y] == 0 self[x][y] = color
[ "def execute_move(self, move, color):\n\n #Much like move generation, start at the new piece's square and\n #follow it on all 8 directions to look for a piece allowing flipping.\n\n # Add the piece to the empty square.\n # print(move)\n flips = [flip for direction in self.__direct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if user credentials are provided.
def _has_auth(creds: Dict[str, str]) -> bool: if creds.get("user") in [None, ""] or creds.get("passwd") in [None, ""]: warnings.warn("Credentials were not supplied. Public data access only.", NoAuthWarning) return False return True
[ "def check_credentials(credentials):", "def verify_credentials(cls):\r\n\r\n if not cls.username:\r\n raise ValueError(\"Username is empty.\")\r\n if not cls.password:\r\n raise ValueError(\"Password is empty.\")\r\n return True", "def has_credentials(self):\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dataframe with all available competitions and seasons. Returns pd.DataFrame A dataframe containing all available competitions and seasons. See
def competitions(self) -> DataFrame[Any]:
[ "def games(self, competition_id: int, season_id: int) -> DataFrame[Any]:", "def games(self, competition_id: int, season_id: int) -> DataFrame[GameSchema]:\n raise NotImplementedError", "def competitions(self) -> DataFrame[CompetitionSchema]:\n raise NotImplementedError", "def dataframe(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dataframe with all available games in a season.
def games(self, competition_id: int, season_id: int) -> DataFrame[Any]:
[ "def games(self, competition_id: int, season_id: int) -> DataFrame[GameSchema]:\n raise NotImplementedError", "def get_all_games(season):\n url = BASE_URL.format(season)\n json_data = requests.get(url, headers=HEADERS).json()\n all_games = json_data[\"resultSets\"][0][\"rowSet\"]\n return all_g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dataframe with both teams that participated in a game.
def teams(self, game_id: int) -> DataFrame[Any]:
[ "def get_teams_table(games_table: pd.DataFrame) -> pd.DataFrame:\n team_name_series = games_table[\"team\"].unique()\n teams_table = pd.DataFrame(data=team_name_series)\n teams_table = teams_table.reset_index()\n teams_table.columns = [\"id\", \"team\"]\n return teams_table", "def teams(self, game_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dataframe with all players that participated in a game.
def players(self, game_id: int) -> DataFrame[Any]:
[ "def players(self, game_id: int) -> DataFrame[PlayerSchema]:\n raise NotImplementedError", "def players(self):\n if self.players_cache is None:\n team_df = self.teams()\n self.players_cache = self.ea.players_endpoint(\n team_df[\"id\"].tolist())\n\n column...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dataframe with the event stream of a game.
def events(self, game_id: int) -> DataFrame[Any]:
[ "def events(self, game_id: int) -> DataFrame[EventSchema]:\n raise NotImplementedError", "def dataframe(self):\n frames = []\n for game in self.__iter__():\n df = game.dataframe\n if df is not None:\n frames.append(df)\n if frames == []:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is to help "mark" a time. (This has nothing to do with time signatures.) Once a time has been marked, it cannot be overwritten.
def mark(self, markName, markTime): if markName not in self._marks: self._marks[markName] = markTime
[ "def mark(self, slot=''):\n # Note: 'slot' has to be string type\n # we are not checking it here.\n self.timedict[slot] = time.time()", "def mark(self, slot=''):\n\n # Note: 'slot' has to be string type\n # we are not checking it here.\n\n self.timedict[slot] = time.time(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get ServerType rows filtered by parameters.
def get(cls, id=None, name=None): filters = dict() if id: cls.validate_id(id) filters.update({"id": id}) if name: cls.validate_name(name) filters.update({"name": name}) result = ServerType.query.filter_by(**filters).all() return ...
[ "def get_all_servers_types():\n ret = _get_list(\n lambda server: server.type if server.type not in ['vanilla.winter', 'vanilla.desert', 'pvp'] else False,\n lambda server: server.type_name\n )\n\n # Extra server type filters\n ret.append({\n 'value': 'pacific+edelweiss',\n '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add new ServerType row.
def add(cls, name): cls.validate_name(name) new_status = ServerType(name) DB.session.add(new_status) DB.session.commit() return new_status
[ "def add_type(self, typename, db):\n self._dbs[typename] = db\n return None", "def server_type(self, server_type):\n self._server_type = server_type", "def add_types(conn, cur, types):\n\n print 'Adding types...',\n \n for type in types:\n cur.execute('INSERT INTO types VALU...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete existing ServerType row.
def delete(cls, type_obj): DB.session.delete(type_obj) DB.session.commit()
[ "def delete_server(self, server_data):\n connection = self.create_connection()\n cursor = connection.cursor()\n try:\n sql_server = \"\"\"DELETE FROM servers WHERE name=:server_name\"\"\"\n cursor.execute(sql_server, server_data)\n connection.commit()\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the a list of projects ids as a json collection
def projects(): response = jsonify(projects_service.get_top_level_projects_ids()) return response
[ "def project_list_json(event_id):\n return jsonify(projects=request_project_list(event_id))", "def client_project_list(request, client_id):\n client = Client.objects.get(id=client_id)\n projects = Project.objects.filter(client=client.harvest_id)\n return HttpResponse(dumps(projects,indent=2, ensure_as...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the defined projects settings
def projects_settings(): return map_settings(settings_repository.settings)
[ "def project(window):\n data = window.project_data()\n if not data:\n return {}\n\n settings = data.get(\"settings\", False)\n if settings is False:\n settings = {}\n\n rsb_project_settings = settings.get(\"RSBIDE\", {})\n if not rsb_project_settings:\n rsb_project_settings = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initiates an upload operation if file is missing. Once initiated the client is then responsible for uploading the file to temporary location (returned as 'upload_url') and finalizing the upload with call to 'finishUpload'. If file is already in the store, returns ALREADY_UPLOADED status. This method is not intended to ...
def begin_upload(self, request): def error(msg): return BeginUploadResponse( status=BeginUploadResponse.Status.ERROR, error_message=msg) hash_algo = _HASH_ALGO_MAPPING[request.hash_algo] if not impl.is_valid_hash_digest(hash_algo, request.file_hash): return error('Invalid ha...
[ "def upload_file(self, file_to_upload):\n if self.drive:\n file_to_upload.Upload()\n else:\n self.create_drive_object()\n self.upload_file(file_to_upload)", "def upload_file(self):\n raise NotImplementedError", "def put_upload(self):\n # print \"start...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finishes pending upload or queries its status. Client should finalize Google Storage upload session first. Once GS upload is finalized and 'finishUpload' is called, the server starts hash verification. Uploading client will get 'VERIFYING' status response. It can continue polling on this method until server returns 'PU...
def finish_upload(self, request): service = impl.get_cas_service() if service is None: raise endpoints.InternalServerErrorException('Service is not configured') # Verify the signature if upload_session_id and grab the session. Broken # or expired signatures are treated in same way as missing uplo...
[ "def complete_upload(self):\r\n xml = self.to_xml()\r\n return self.bucket.complete_multipart_upload(self.key_name,\r\n self.id, xml)", "def complete(self):\n resp = self.s3.complete_multipart_upload(\n Bucket=self.target_bucket,\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function extracts all the desired characteristics of all new job postings of the title and location specified and returns them in single file.
def find_jobs_from(website, job_title, location, search_category, filename="results.xls"): jobs_list = [] if website == 'Indeed': job_soup = load_jobs_div(job_title, location) jobs_list, num_listings = extract_job_details( job_soup, search_category) return jobs_list
[ "def get_gulftalent_jobs(base_url):\n host_url = \"http://www.gulftalent.com\"\n soup = BeautifulSoup(urlopen(base_url).read())\n\n #open result.txt & write header\n written_file = open(\"result.txt\", \"a\")\n written_file.write(soup.title.string.strip() + \" (Updated : \" + time.strftime(\"%d-%b-%Y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
将图片转换为字符图片 小技巧 想要生成的图片中的字符能清晰可见: 参数scale不宜设置的过小,对于一般相片大小(如29763968)来说,0.2就还不错 其次要指定字体路径fontPath(不然字体大小不生效),将字体大小fontSize设置的大一点,比如36 最后参数keepSize应设置为False,这样,最终生成的图片会非常大,但把图片放大后字符也一样清晰
def makeImage( imgPath: str, savePath: str, chars: str = None, scale: float = 1, quality: int = 80, fontPath: str = "", fontSize: int = 14, horzSep: int = 2, vertSep: int = 2, keepRatio=True, keepSize=False, ): if chars is None: chars = "HR#PXCFJIv?!+^-:. " if...
[ "def __letter_to_image(self, letter, font):\n string = \" \"+unichr(letter) # some chars are not generating\n im = Image.new(\"L\", (100, 100), 255) # \"L\" -greyscale\n draw = ImageDraw.Draw(im)\n im = im.crop((0,0)+draw.textsize(string, font=font))\n draw.text((0,0), string, fill=\"black\", font=fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to calculate the initial conditions to pass to ODEINT by converting units. Principally, converting initial disc mass from solar masses to grams, and calculating an initial angular frequency from a spin period in milliseconds. Usage >>> init_conds(P, MdiscI)
def init_conds(P, MdiscI): Mdisc0 = MdiscI * Msol # Disc mass omega0 = (2.0 * np.pi) / (1.0e-3 * P) # Angular frequency return np.array([Mdisc0, omega0])
[ "def initialize_initial_condition(self):\n self.ic_ds=self.zero_initial_condition()\n self.set_initial_h_from_bc()", "def set_init_cond_func(vars_dict):\n S = vars_dict['Survtotalfrac'] # S_asx\n LarvDisp = vars_dict['Larvaldispersal']\n sexsp = int(vars_dict['sexsp'])\n total_init_recr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to pass to ODEINT which will calculate a disc mass and angular frequency for given time points. Usage >>> ODEs(y, t, B, MdiscI, RdiscI, epsilon, delta, n)
def ODEs(y, t, B, MdiscI, RdiscI, epsilon, delta, n=1.0, alpha=0.1, cs7=1.0, k=0.9): # Initial conditions Mdisc, omega = y # Constants Rdisc = RdiscI * 1.0e5 # Disc radius - cm tvisc = Rdisc / (alpha * cs7 * 1.0e7) # Viscous timescale - s mu = 1.0e15 * B * (R ** 3....
[ "def f1d(t,y,float_params,sigmaI): #sigmastep is an array\n \n ## y is Ntot0 ##\n\n # unpack parameters\n Nbar, Nstar, sigma0, nu_kin_mlyperus, DoverdeltaX2 = float_params \n\n # Ntot is passed in, Fqll calculated from Ntot\n Ntot0 = np.ascontiguousarray(y)\n Nqll0 = Nbar - Nstar * np.sin(2*np....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a value or value array to a new unit and return a copy if inplace=False
def _to( value: Union["Value", "ValueArray"], units: Union[Unit, str], inplace: bool ) -> Any: if value.units == units: return value if value.units is None: raise RuntimeError("Cannot convert with units=None") try: units = next( imp_unit for imp_unit in ...
[ "def test_inplace_set_value(self):\r\n dtype = self.dtype\r\n if dtype is None:\r\n dtype = theano.config.floatX\r\n\r\n shp = (100/4,1024)#100KB\r\n\r\n x = numpy.zeros(shp, dtype=dtype)\r\n x = self.cast_value(x)\r\n x_shared = self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is an energy equal to another? Compares only the value, with implicit unit conversion
def __eq__(self, other: Any) -> bool: tol_ha = 0.0000159 # 0.01 kcal mol-1 # A PotentialEnergy is not equal to a FreeEnergy, for example if isinstance(other, Value) and not isinstance(other, self.__class__): return False if isinstance(other, Value): other = oth...
[ "def __eq__(self, other):\n if set(self.comp) != set(other.comp):\n return False\n if abs(self.energy - other.energy) > 1e-6:\n return False\n for key in self.comp:\n if abs(self.unit_comp[key] - other.unit_comp[key]) > 1e-6:\n return False\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add another energy to this list, if it does not already appear
def append(self, other: Energy) -> None: for item in self: if other == item: logger.debug( f"Not appending {other} to the energies - " f"already present. Moving to the end" ) self.append(self.pop(self.index(item...
[ "def add_energy(self,e):\n assert type(e)==float\n self._energy+=e", "def add_food_to_bag(self):\n self.food_eaten.set(sum([species.food.get() for species in self.ecosystem]))", "def add_employee(self, emp):\n if emp not in self.employees: \n self.employees.append(emp)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Next type of energy in a list of energies
def _next(energies: Any, energy_type: Type): try: return next( energy for energy in energies if isinstance(energy, energy_type) ) except StopIteration: return None
[ "def add_energy(self,e):\n assert type(e)==float\n self._energy+=e", "def get_energies(element, emin, emax, fwhm_ev=1e-4, eedge = None, num=100,\n verbose=True):\n assert emax>emin, \"emax must be larger than emin.\"\n assert emin>0, \"emin must be larger than 0.\"\n fwhm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the last instance of a particular energy type in these list of energies
def last(self, energy_type: Type[Energy]) -> Optional[TypeEnergy]: return self._next(reversed(self), energy_type=energy_type)
[ "def get_highest_energy_index(self):\n energies = self.get_energies()\n valid_entries = [(i, e) for i, e in enumerate(energies) if e == e]\n highest_energy_index = max(valid_entries, key=lambda x: x[1])[0]\n return highest_energy_index", "def _next(energies: Any, energy_type: Type):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
First potential energy in this list
def first_potential(self) -> Optional[PotentialEnergy]: return self.first(energy_type=PotentialEnergy)
[ "def Find_Lowest_Energy_Structure_Electrostatics(self):\n n_Na = self.structure.composition['Na']\n n_S = self.structure.composition['S']\n n_O = self.structure.composition['O']\n n_N = self.structure.composition['N']\n n_Fe = self.structure.composition['Fe']\n\n n_Fe_reduc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a method string for a method and the keywords
def method_string( method: Optional["Method"], keywords: Optional["Keywords"], ) -> str: method_str = f"{method.name} " if method is not None else "unknown" method_str += keywords.bstring if keywords is not None else "" return method_str
[ "def MethodName(self) -> str:", "def format_method_signature(self, locals, code):\n\n res = \"\"\n is_args = code.co_flags & 4\n is_kwargs = code.co_flags & 8\n total_args = code.co_argcount\n if is_args:\n total_args += 1\n if is_kwargs:\n total_arg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert spec (string or filename) to ConfigObj
def convert_spec(spec): config = configobj.ConfigObj(configspec=spec) return config.configspec
[ "def get_configspec():\n\n lines = []\n\n for section, opts in option_spec.items():\n lines.append(\"[{section}]\".format(section=section))\n for name, attrs in opts.items():\n default = attrs.get(\"default\", \"\")\n the_type = attrs[\"type\"]\n args = [\"%r\" %...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a configobj to an OrderedHierarchicalMapping
def conf_to_ohm(conf, ohm=None, section_name=''): if conf is None: return HierarchicalOrderedDict() if ohm is None: ohm = HierarchicalOrderedDict() for key, value in conf.items(): if not section_name == '': new_key = (section_name + HierarchicalOr...
[ "def test_yaml_to_ordered_dict(self) -> None:\n raw_config = \"\"\"\n pre_deploy:\n hook2:\n path: foo.bar\n hook1:\n path: foo1.bar1\n \"\"\"\n config = yaml_to_ordered_dict(raw_config)\n self.assertEqual(list(config[\"pre_deploy\"].keys())...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert OrderedHierarchicalMapping to specification list The value_transform argument should be a function that transforms the values of the ohm to the entries of the spec list.
def ohm_to_spec_list(ohm, value_transform=lambda x: x): spec = [] level_start = "[" level_stop = "]" for key, value in ohm.items(): split_key = key.split(ohm.SECTION_SEPARATOR) index = None if len(split_key) > 1: for level, part in zip(count_up(1), split_key[:-1]): ...
[ "def map2list(mapping):\n # Check on mapping dictionary, with size=1:\n if not isinstance(mapping, dict):\n logging.error(\"Mapping type not dictionary but {}\".format(type(mapping)))\n return None, None\n if len(mapping) != 1:\n logging.error(\"Mapping dictionary unexpected length {},...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Yields a range of date.
def daterange(start_date, end_date): for n in range(int ((end_date - start_date).days)+1): yield start_date + timedelta(n)
[ "def iter_dates(start, end):\n one_day = timedelta(days=1)\n date = start\n while date <= end:\n yield date\n date += one_day", "def daterange(start_date, end_date):\n for n in range(int ((end_date - start_date).days)):\n yield start_date + dt.timedelta(n)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API to get temperature data. Gets maximum temperatures and dates from database.
def get_temperature_data(zone): zone = zone[1:len(zone)-1] temp_response = {} conn = sqlite3.connect(os.path.abspath('database.db')) # get temperatures data query = "Select temp_date, temp_max From temperature Left join fire_danger_zone on temperature.temp_station=fire_danger_zone.fdz_station Wher...
[ "def get_temperature(self):\n return (self.response.json()['main']['temp_min'], self.response.json()['main']['temp'],\n self.response.json()['main']['temp_max'])", "def temps():\n # Calculate the date 1 year ago from the last data point in the database\n latest = session.query(ME.date...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API to get rainfall data. Gets rainfall amount and dates from database.
def get_rainfall_data(zone): zone = zone[1:len(zone)-1] rain_response = {} conn = sqlite3.connect(os.path.abspath('database.db')) # get rainfall data query = "Select rain_date, rain_rainfall From rainfall Left join fire_danger_zone on rainfall.rain_station=fire_danger_zone.fdz_station Where fire_da...
[ "def rainfall_data():\n fn = os.path.join(os.path.dirname(__file__), \"data\", \"rainfall.csv\")\n df = pd.read_csv(fn)\n df.set_index(\"year\", inplace=True)\n return df", "def base_request(date):\n url = \"https://covid-19-data.p.rapidapi.com/report/totals\"\n params = {\n \"date-format...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API to get humidity data. Gets humidity and dates from database.
def get_humidity_data(zone): zone = zone[1:len(zone)-1] humidity_response = {} conn = sqlite3.connect(os.path.abspath('database.db')) # get humidity data query = "Select humidity_date, humidity_relative From humidity Left join fire_danger_zone on humidity.humidity_station=fire_danger_zone.fdz_stat...
[ "def humidity_sensor():\n return _get_sensor(\"Humidity\", \"humidity\")", "def humidity( self ):\n\t\tif self.measurement_mode == MODE_ONE_SHOT:\n\t\t\tself.read_all(REPEATABILITY_HIGH)\n\t\telse:\n\t\t\tself.read_all( None ) # Just Fetch Data (in PERIODIC_MODE)\n\t\treturn self._rh", "def get_humidity(inte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate Forest Fire. Gets FFDI and dates from databse.
def forest_fire_calculator(zone): drought_factor = 2 drought_factor = int(drought_factor) ffdi_response = {} conn = sqlite3.connect(os.path.abspath('database.db')) # get FFDI data query = "Select ffdi_date, ffdi_value From forest_fire_danger_index Left join fire_danger_zone on forest_fire_dang...
[ "def FFDI_calculator(zone, drought_factor):\n zone = zone[1:len(zone)-1]\n drought_factor = int(drought_factor[1:len(drought_factor)-1])\n ffdi_response = {}\n conn = sqlite3.connect(os.path.abspath('database.db'))\n\n # get FFDI data\n query = \"Select ffdi_date, ffdi_value From forest_fire_dange...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate for McAthur's FFFDI based on drought factor. Get FFDI and dates
def FFDI_calculator(zone, drought_factor): zone = zone[1:len(zone)-1] drought_factor = int(drought_factor[1:len(drought_factor)-1]) ffdi_response = {} conn = sqlite3.connect(os.path.abspath('database.db')) # get FFDI data query = "Select ffdi_date, ffdi_value From forest_fire_danger_index Left ...
[ "def get_FFDI(weather_df: DataFrame, wind_red: int = 3, flank=False) -> Series:\n if flank:\n wind_speed = 0\n else:\n wind_speed = weather_df[WIND_SPEED]\n\n ffdi = 2.0*np.exp(\n -0.450 + 0.987*np.log(weather_df[DF])\n -0.0345*weather_df[RH]\n +0.0338*weather_df[TEMP]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the notification schedule loads properly.
def test_notification_schedule(self): response = self.client.get(self.dashboard_url) self.assertEqual(response.status_code, 200)
[ "def test_load_bad_schedule(self):\n pass", "def test_create_schedule(self):\r\n pass", "def test_list_schedules(self):\n pass", "def test_load_schedule_data(schedule_wiki_storage_config, reddit_with_wiki):\n schedule_wiki_storage = ScheduleWikiStorage(\n schedule_wiki_storage_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test retriving the edit notification schedule form.
def test_get_edit_page(self): data = self.get_valid_data() notification = reminders.Notification.objects.create(**data) url = reverse('edit-notification', args=[notification.pk]) response = self.client.get(url) self.assertEqual(response.status_code, 200)
[ "def test_update_view_uses_correct_form(self):\n self.client.force_login(self.test_user)\n response = self.client.get(self.url)\n form = response.context.get('form')\n self.assertIsInstance(form, CalendarForm)", "def test_edit_workedhours_show(self):\n\n response = self.client.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test retriving the delete notification schedule form.
def test_get_delete_page(self): data = self.get_valid_data() notification = reminders.Notification.objects.create(**data) url = reverse('delete-notification', args=[notification.pk]) response = self.client.get(url) self.assertEqual(response.status_code, 200)
[ "def test_delete_schedule(self):\n response = self.client.open('/v1/schedule/{id}'.format(id=56),\n method='DELETE',\n content_type='application/json')\n self.assert200(response, \"Response body is : \" + response.data.decode('utf-8...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test the response from a registered user without any notifications
def test_registered_no_notifications(self): msg = self._send(self.reg_conn, '1') self.assertEqual(len(msg.responses), 1) self.assertEqual(msg.responses[0].text, self.app.no_reminders)
[ "def testNoFriendship(self):\r\n response_dict = self._tester.QueryUsers(self._cookie2, [self._user.user_id])\r\n self.assertEqual(response_dict['users'][0], {'labels': ['registered'], 'user_id': self._user.user_id})", "def test_get_users_eligible_for_fist_notification_with_no_result(self):\n # Given...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unconfirmed patients returned should be distinct.
def test_multiple_notifications_unconfirmed(self): appt_date = datetime.date.today() self.create_unconfirmed_notification(self.test_patient, appt_date) self.create_unconfirmed_notification(self.test_patient, appt_date) qs = Patient.objects.unconfirmed_for_date(appt_date) self.ass...
[ "def getUnconfirmedVolunteers(self, query):\n query = Volunteer.query(Volunteer.confirmed == False)\n return query", "def get_users_with_missing_data() -> Set[str]:\n users_data = {user[\"_source\"][\"VENDOR_UUID\"] for user in Handlers.elastic_handler.get_all_today_data(\n _type=\"status\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test email contains info for the appointment date.
def test_appointment_date(self): # Default for email appt_date = datetime.date.today() + datetime.timedelta(days=7) self.create_confirmed_notification(self.test_patient, appt_date) self.create_unconfirmed_notification(self.other_patient, appt_date) # run email job from ...
[ "def test_appointment_date(self):\n appt_date = datetime.date.today() + datetime.timedelta(days=7) # Default for email\n reminders.Patient.objects.filter(\n pk__in=[self.test_patient.pk, self.other_patient.pk]\n ).update(next_visit=appt_date)\n confirmed = self.create_confirme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test changing appointment date via callback kwarg.
def test_changing_date(self): days = 2 appt_date = datetime.date.today() + datetime.timedelta(days=days) confirmed = self.create_confirmed_notification(self.test_patient, appt_date) unconfirmed = self.create_unconfirmed_notification(...
[ "def test_update_calendar(self):\n pass", "def test_appointment_date(self):\n # Default for email\n appt_date = datetime.date.today() + datetime.timedelta(days=7) \n self.create_confirmed_notification(self.test_patient, appt_date)\n self.create_unconfirmed_notification(self.othe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Skip sending the email if there are not patients for this date.
def test_skip_if_no_patients(self): appt_date = datetime.date.today() + datetime.timedelta(days=5) confirmed = self.create_confirmed_notification(self.test_patient, appt_date) # run email job from aremind.apps.reminders.app import daily_email_callback daily_email_callback(self....
[ "def test_skip_if_no_patients(self):\n\n appt_date = datetime.date.today() + datetime.timedelta(days=5)\n reminders.Patient.objects.filter(\n pk__in=[self.test_patient.pk, self.other_patient.pk]\n ).update(next_visit=appt_date)\n confirmed = self.create_confirmed_notification(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test manually confirming a patient reminder.
def test_manually_confirm(self): data = {} response = self.client.post(self.url, data) self.assertRedirects(response, reverse('reminders_dashboard')) reminder = reminders.SentNotification.objects.get(pk=self.unconfirmed.pk) self.assertEqual(reminder.status, 'manual') sel...
[ "def test_email_reminder(self, logged_in, user, testapp):\n res = logged_in\n assert 'confirmation' in res\n with mail.record_messages() as outbox:\n assert len(outbox) == 0\n res.click('Click here')\n assert len(outbox) == 1\n assert 'Confirm your ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a string representing a single command, open a process, and return the Popen process object.
def process_run(cmd_string, stdin=None): process_object=subprocess.Popen(shlex.split(cmd_string), stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return process_object
[ "def popen(command):\n\tif kUseSubProcess:\n\t\t#print \"command\",command\n\t\treturn subprocess.Popen(\tcommand,\n\t\t\t\t\t\t\t\tshell=False, # needs to be True for Windows? needs to be False on UNIX\n\t\t\t\t\t\t\t\tstdin=subprocess.PIPE,\n\t\t\t\t\t\t\t\tstdout=subprocess.PIPE,\n\t\t\t\t\t\t\t\tstderr=subproce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }