query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
When multiple absolute results are stored at the 'baseline' and 'analyze' keys, this function computes their relative results and places them at the base level.
def produce_relative_audience(results_output, results_analyzed, results_baseline): data_analyzed = results_analyzed['audience_api'] data_baseline = results_baseline['audience_api'] data_compared = collections.defaultdict(dict) for group_name, grouping in data_analyzed.items(): if 'erro...
[ "def aggregate_results(baseline, *others):\n\n def aggregate_benchmark(key, results):\n if key in results and results[key] != 0.0:\n return results[key] / baseline[key]\n else:\n return float('nan')\n\n results = []\n for key in sorted(baseline.keys()):\n results....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add relevant data from a tweet to 'results'
def analyze_tweet(tweet, results): ###################################### # fields that are relevant for user-level and tweet-level analysis # count the number of valid Tweets here # if it doesn't have at least a body and an actor, it's not a tweet try: body = tweet["body"] userid ...
[ "def analyze_tweet(tweet,results):\n \n # tweet body information\n if \"body_term_count\" not in results:\n results[\"body_term_count\"] = SimpleNGrams(\n char_lower_cutoff=3\n ,n_grams=1\n ,tokenizer=\"twitter\"\n )\n results[\"body_ter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a scoring matrix from the file named filename.
def read_scoring_matrix(filename): scoring_dict = {} scoring_file = urllib2.urlopen(filename) ykeys = scoring_file.readline() ykeychars = ykeys.split() for line in scoring_file.readlines(): vals = line.split() xkey = vals.pop(0) scoring_dict[xkey] = {} for ykey, val i...
[ "def read_data(filename):\n # open feature file, read each line, and fill in the sparse matrix\n i, j, j_max = 0, 0, 0\n data = []\n row_ind = []\n col_ind = []\n with open(filename) as file:\n for line in file:\n for c in line.split():\n j, feature = c.split(':')\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a protein sequence from the file named filename.
def read_protein(filename): protein_file = urllib2.urlopen(filename) protein_seq = protein_file.read() protein_seq = protein_seq.rstrip() return protein_seq
[ "def ReadXeasyProtSeq(self, fileName, seqFileName):\n #for the XEASY files:\n import ReadXeasy\n if _DoesFileExist(fileName) == 0:\n return\n if _DoesFileExist(seqFileName) == 0:\n return\n\n #read the sequence:\n print 'reading the .prot file', seqFil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Composite the supplied configs into a single ``Config`` object.
def composite(configs, method="override"): if method not in ['override', 'update', 'append']: raise ConfigError( "Unrecognized composite method: " + str(method)) composite_config = Config() for config in configs: # make sure we have a config ob...
[ "def mergeConfig(self, *args, **kwargs):\n other = cherrypy.lib.reprconf.Config(*args, **kwargs)\n # Top-level keys are namespaces to merge, second level should get replaced\n for k, v in other.items():\n mergeFrom = self.get(k, {})\n mergeFrom.update(v)\n self[k] = mergeFrom", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a key, value pair to the config object.
def add(self, key, value): if key in self.keys(): raise ConfigError('Key "{k}" exists in config. Try "set()"'.\ format(k=key) ) else: self._set(key, value)
[ "def _add_config(self, key, value):\n if key in self.__config_keys:\n cfg = self.__configs.get(key)\n if not cfg:\n self.__configs[key] = [value]\n else:\n cfg.append(value)\n\n else:\n raise KeyError('Key not supported: [{}]'.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override values with the contents of another Config object.
def override(self, override_config): for key, new_value in override_config.iteritems(): if isinstance(new_value, Config): cur_value = self.get(key, None) if isinstance(cur_value, Config): cur_value.override(new_value) else: ...
[ "def mergeConfig(self, *args, **kwargs):\n other = cherrypy.lib.reprconf.Config(*args, **kwargs)\n # Top-level keys are namespaces to merge, second level should get replaced\n for k, v in other.items():\n mergeFrom = self.get(k, {})\n mergeFrom.update(v)\n self[k] = mergeFrom", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the contents of a stream as ordered Config objects.
def _ordered_load(stream): class OrderedLoader(Loader): pass # read parsed data pairs as Config objects OrderedLoader.add_constructor( resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: Config(loader.construct_pairs(node)) ) return load(stream, OrderedLoader)
[ "def ordered_load(stream, Loader=Loader, object_pairs_hook=OrderedDict):\n\n class OrderedLoader(Loader):\n pass\n\n def construct_mapping(loader, node):\n loader.flatten_mapping(node)\n return object_pairs_hook(loader.construct_pairs(node))\n\n OrderedLoader.add_constructor(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ipython magic function for running hylang code in ipython Use %hylang one line of code or %%hylang for a block or cell Note that we pass the AST directly to IPython.
def hylang(self, line, cell=None, filename='<input>', symbol='single'): global SIMPLE_TRACEBACKS source = cell if cell else line try: tokens = tokenize(source) except PrematureEndOfInput: print( "Premature End of Input" ) except LexException as e: ...
[ "def ipython_shell(ctx):\n data = ctx.obj # noqa\n embed()", "def load_ipython_extension(ipython):\n from .convenience import cmd, parse\n def magic(line, cell=None):\n \"\"\"Coconut IPython magic.\"\"\"\n if cell is None:\n code = line\n else:\n cmd(line) # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate Sphinx objects inventory version 2 at `basepath`/objects.inv.
def generate(self, subjects, basepath): path = os.path.join(basepath, 'objects.inv') self.msg('sphinx', 'Generating objects inventory at %s' % (path,)) with self._openFileForWriting(path) as target: target.write(self._generateHeader()) content = self._generateContent(sub...
[ "def test01_create_inventory_dryrun(self):\n out = self.run_ocfl_store(\"Inventory for new object with just v1\",\n ['--create', '--id', 'http://example.org/obj1', '--src', 'fixtures/1.0/content/cf1/v1'],\n text=\"Without an `--objdir` argumen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a datestamp in the format to be used throughout the task management system.
def _datestamp(): return str(datetime.date.today())
[ "def timestamp_as_string(self):\n return (\n f\"{self.timestamp.year}-{self.timestamp.month}-\"\n f\"{self.timestamp.day}-{self.timestamp.hour}-\"\n f\"{self.timestamp.minute}-{self.timestamp.second}\"\n )", "def _GetDateString():\n return datetime.utcnow().strfti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts energy in 1/cm to K
def E_K(E_inv_cm): E_hz = E_inv_cm*c # (1/cm)*(cm/s) E_ergs = h*E_hz # ergs return E_ergs/k # K
[ "def energy_to_temp(energy):\n return energy / kb('J/K')", "def temp_to_energy(temp):\n return temp * kb('J/K')", "def amu2kg(Mass):\n return (Mass / constants.Avogadro) / 1000", "def KE(self):\n\n if \"KE\" not in self.ds:\n var = xroms.KE(self.ds.rho0, self.speed)\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For two states 1 and 2, given the degeneracies g_1 and g_2 and energies E_1 and E_2 in 1/cm, returns the equilibrium population ratio of state 1 over state 2 at a temperature T.
def equilibrium_Boltzman_ratio(g_1,E_1,g_2,E_2,T): delta_E = E_1-E_2 if DEBUG: print "energy difference =",delta_E,"1/cm" print " =",c*delta_E,"hz" print " =",h*c*delta_E,"ergs" print " =",h*c*delta_E/k,"K" return (g_1/g_2)*M.exp(-delta_E/T)
[ "def dom_prob(g1, g2):\n\n if g1 in k or g2 in k:\n return 1\n elif g1 in m:\n if g2 in m:\n return .75\n else:\n return .5\n else:\n if g2 in m:\n return .5\n else:\n return 0", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given text that has been wrapped, unwrap it but preserve paragraph breaks.
def unwrap(text): # Split into lines and get rid of newlines and leading/trailing spaces lines = [line.strip() for line in text.splitlines()] # Join back with predictable newline character text = os.linesep.join(lines) # Replace cases where there are more than two successive line breaks while...
[ "def unwrap(text, wrapstr='\\n '):\n return text.replace(wrapstr, '').strip()", "def unwrapText(text):\n\n # Removes newlines\n text = text.replace(\"\\n\", \"\")\n\n # Remove double/triple/etc spaces\n text = text.lstrip()\n for i in range(10):\n text = text.replace(\" \", \" \")\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check for stale issues and close them if needed.
def process_issues(repository, warn_seconds, close_seconds, stale_label='Close?', keep_open_label='keep-open', closed_by_bot_label='closed-by-bot', max_issues=50, sleep=0, is_dryrun=False): i = 0 now = time.time() g = Github(os.environ.get('GITHUB_TOK...
[ "def close(self):\n\n # stop watchdog thread\n if self._auto_commit_watchdog is not None:\n with self._commit_lock:\n self._auto_commit_watchdog.is_closed = True\n\n retry_counter = 0\n while len(self._objects_batch) > 0 or len(self._reference_batch) > 0 or\\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the ISO root directory.
def task__iso_mkdir_root() -> types.TaskDict: return helper.Mkdir(directory=constants.ISO_ROOT, task_dep=["_build_root"]).task
[ "def create_iso(iso_name, archive_dir):\n try:\n controller_0 = sysinv_api.get_host_data('controller-0')\n except Exception as e:\n e_log = \"Failed to retrieve controller-0 inventory details.\"\n LOG.exception(e_log)\n raise CloneFail(e_log)\n\n iso_dir = os.path.join(archive_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate the ISO_ROOT with required files.
def task_populate_iso() -> types.TaskDict: return { "basename": "populate_iso", "actions": None, "doc": "Populate {} with required files.".format( utils.build_relpath(constants.ISO_ROOT) ), # Aggregate here the tasks that put files into ISO_ROOT. "task_dep...
[ "def main():\n parser = argparse.ArgumentParser()\n parser.add_argument('folder', type=str, help='Folder to ISOse')\n\n args = parser.parse_args()\n\n from io import BytesIO\n\n if not os.path.exists(args.folder):\n return \n lastname = os.path.split(args.folder)[-1]\n\n time_prefix = da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the SHA256 digest of the ISO.
def task__iso_digest() -> types.TaskDict: return helper.Sha256Sum( input_files=[ISO_FILE], output_file=config.BUILD_ROOT / "SHA256SUM", task_dep=["_iso_build", "_iso_implantisomd5"], ).task
[ "def code_sha256(self) -> str:\n file_hash = FileHash(hashlib.sha256())\n file_hash.add_file(self.archive_file)\n return base64.b64encode(file_hash.digest).decode()", "async def __get_sha256(self, data):\n\n m = hashlib.sha256()\n m.update(data)\n return m.hexdigest()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that takes an evaluation as parameter and will use multiple rules to detect if the evaluation is considered bad or not. It returns a bad_evaluation object in case one of the return positive.
def detect_bad_eval(evaluation): rules = [rule1, rule2, rule3] for index, rule in enumerate(rules, 1): if rule(evaluation): return create_bad_eval(evaluation, index) return False
[ "def evaluate_validation(self):\n self.model.eval()\n\n val_loss = 0.0\n val_losses = []\n val_accuracies = []\n\n with torch.no_grad():\n for data in self.val_set:\n X, labels = data[0].to(self.device), data[1].to(self.device)\n\n outputs ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save vacancies to database.
def save_vacancies(cls, vacancies: List[dict]): for vacancy in vacancies: Vacancy.objects.get_or_create(**vacancy)
[ "def save(self, context=None):\n updates = self.obj_get_changes()\n self.dbapi.update_bay(self.uuid, updates)\n\n self.obj_reset_changes()", "def save(self):\n for workunit in self.workunits.values():\n workunit.save()", "def submit_last_checkout(self):\n self.daily...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and return a standard namespace of simulated hardware.
def get_hw(): ns = HelpfulNamespace( fast_motor1=FastMotor(name='fast_motor1'), fast_motor2=FastMotor(name='fast_motor2'), fast_motor3=FastMotor(name='fast_motor3'), slow_motor1=SlowMotor(name='slow_motor1'), slow_motor2=SlowMotor(name='slow_motor2'), slow_motor3=Slow...
[ "def create_namespace(self):\n name = 'namespace-{random_string}'.format(random_string=random_str(5))\n\n namespace = client.V1Namespace(metadata=client.V1ObjectMeta(name=name))\n\n self.core_api.create_namespace(namespace)\n\n logger.info(\"Creating namespace: %s\", name)\n\n # s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decodes a bencoded value, raising a MalformedBencodeException on errors. key_encoding specifies an encoding to decode dict keys with, generally UTF8. Set it to None to keep the dictionary keys as bytestrings
def _bencode_decode(file_object, key_encoding='utf-8'): if isinstance(file_object, str): file_object = file_object.encode('utf8') if isinstance(file_object, bytes): file_object = BytesIO(file_object) file_object = ReadPositionFileWrapper(file_object) def create_ex(msg): msg += ...
[ "def decode_dictionary(encoded_dictionary):\n\n # First byte needs to be a \"d\" to signify that it's a Bencoding dictionary.\n if len(encoded_dictionary) == 0 or encoded_dictionary[0] != \"d\":\n raise BencodingDecodeException(\"Not a dictionary\")\n\n # Initialize a dictionary.\n start_position...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bencode any supported value (int, bytes, str, list, dict)
def _bencode(value, encoding='utf-8'): if isinstance(value, int): return _bencode_int(value, encoding=encoding) elif isinstance(value, (str, bytes)): return _bencode_bytes(value, encoding=encoding) elif isinstance(value, list): return _bencode_list(value, encoding=encoding) elif ...
[ "def encode(self, value: Any, failsafe: bool = False) -> Union[str, bytes]:\n raise NotImplementedError(\"Encoding not implemented\")", "def bstr(cls, arg):\n if is_unicode(arg):\n return arg.encode('utf-8')\n else:\n return arg", "def _to_binary(value) -> psycopg2.Bin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes a union of multiple knowledge bases\n
def union(kb_list): l = [k.facts for k in kb_list] k = KnowledgeBase(None, kb_list[0].entity_map, kb_list[0].relation_map) k.facts = np.concatenate(l, axis=0) logging.info("Created a union of {0} kbs. Total facts in union = {1}\n".format(len(kb_list), len(k.facts))) return k
[ "def union(self, domain):", "def union(self, x, y):\n self._link(self.find_set(x), self.find_set(y))", "def union(llist_a, llist_b):\n union_set = LinkedList()\n for llist in (llist_a, llist_b):\n node = llist.head\n while node is not None:\n if node.value not in union_set.node...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dumps the entity and relation mapping in a kb\n
def dump_kb_mappings(kb, kb_name): dump_dict = {} dump_dict["entity_map"] = kb.entity_map dump_dict["relation_map"] = kb.relation_map with open(kb_name+".ids.pkl", "wb") as f: pickle.dump(dump_dict, f) logging.info("Dumped entity and relation maps to {0}\n".format(kb_name))
[ "def print_model_map() -> None:\n print(_MODEL_MAP)", "def print_entities(self) -> None:\n for row in self.maze_data:\n for ent in row:\n print(ENTITY_NAME[row[ent]], end=\"\\t\")\n print(\"\\n\")", "def dump(self):\n print(\"ROB\".ljust(48, '=').rjust(80,'=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that generates a wordcloud for a givens sentiment from a dataframe containing a text column
def generate_wordcloud(data, mode='Tweet', sentiments='all'): df = data.copy() if sentiments=='positive': df = df[df.Sentiment.isin(['Positive', 'Extremely Positive'])] if sentiments=='negative': df = df[df.Sentiment.isin(['Negative', 'Extremely Negative'])] ...
[ "def wordcloud_analysis(df):\n\n # getting wordclouds\n # https://www.geeksforgeeks.org/generating-word-cloud-python/\n # removing all fullstops and storing the result in a temp variable\n temp = df.loc[:, 'impression'].str.replace(\".\", \"\").copy()\n words = \"\"\n for i in temp.values:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that generates the top n_grams from a text column of dataframe that correspond to a particular sentiment
def get_top_grams(dataframe, sentiment, n_grams=2, top=10): sentiments = ['Positive', 'Extremely Positive', 'Neutral', 'Negative', 'Extremely Negative'] if sentiments!='all': if sentiment=='positive': sentiments = ['Positive', 'Extremely Positive'] if sentiment=='neg...
[ "def get_top_ngrams(X_train, y_train, X_test, X_train_u):\r\n print(\"ngrams\")\r\n vectorizer = TfidfVectorizer()\r\n X_train = vectorizer.fit_transform(X_train)\r\n ch2 = SelectKBest(chi2, k=200)\r\n X_train_new = ch2.fit_transform(X_train, y_train)\r\n X_test = vectorizer.transform(X_test)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates weighted matrix with actual info from unweighted version
def _update_weighted_matrix(self) -> None: self.weighted_map = deepcopy(self.map) for connection in self.weighted_map: connections = self.weighted_map[connection] connections_count = sum(list(connections.values())) for key in self.weighted_map[connection]: ...
[ "def update(self):\n self.weight_mom[self.index] = self.sub_weight_mom\n self.weight[self.index] = self.sub_weight", "def get_weight_matrix(self):\n return self.W", "def update_weights(self):\n for layer in xrange(len(self.weights)):\n self.update_weights_layer(layer)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Picks the next word in Markov chain using discrete distributed weights.
def _pick_next_word(self, word: str) -> str: connections = self.weights[word] words = list(connections.keys()) probabilities = list(connections.values()) return np.random.choice(words, 1, p=probabilities)[0]
[ "def next_word(self):\n def highest_probability(a, b):\n if a.probability > b.probability:\n return a\n else:\n return b\n\n if len(self.proceeding_words) == 0:\n return None\n return reduce(highest_probability, self.proceeding_word...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Classic form if no search parameters are sent, otherwise process the parameters and redirect to the search results of a built query based on the parameters
def classic_form(): form = ClassicForm(request.args) query = form.build_query() if query: return redirect(_url_for('search', q=query, sort=form.sort.data)) else: return _render_template('classic-form.html', form=form, sort_options=current_app.config['SORT_OPTIONS'])
[ "def search():\n if not g.search_form.validate_on_submit():\n return redirect(url_for('index'))\n # Redirect to search_results function and pass search query\n return redirect(url_for('search_results', query=g.search_form.search.data))", "def search_form_full():", "def search_form(request):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cache only the template rendering so that other parts of the code get executed such as connecting to link_gateway to register clicks
def _cached_render_template(key, *args, **kwargs): try: rendered_template = redis_client.get(key) if rendered_template: rendered_template = rendered_template.decode('utf-8') except Exception: # Do not affect users if connection to Redis is lost in production if app.de...
[ "def render_from_cache(f, rendering_action):\n \n def _render_from_cache(action, self, *args, **kwargs):\n context = dict(\n tmpl_context = self._py_object.tmpl_context,\n app_globals = self._py_object.config['pylons.app_globals'],\n config = self._py_object.config,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper to render template with multiple default variables
def _render_template(*args, **kwargs): rendered_template = render_template(*args, **kwargs, environment=current_app.config['ENVIRONMENT'], base_url=app.config['SERVER_BASE_URL'], alert_message=current_app.config['ALERT_MESSAGE'], disable_full_ads_link=current_app.config['DISABLE_FULL_ADS_LINK']) return rendered...
[ "def override_template(*args, **kwargs):\n utils_override_template(*args, **kwargs)", "def render(self, template, **kw):\n t = jinja_env.get_template(template) \n self.response.out.write(t.render(kw))", "def render(model, template):\n\n iterables = find_iters(template)\n for variable_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decides if a click needs to be registered. Returns True if the requests is not from a bot and it has a UserAgent that starts with the word Mozilla.
def _register_click(): is_bot = session.get('auth', {}).get('bot', True) user_agent = request.headers.get('User-Agent') if not is_bot and user_agent and user_agent.startswith("Mozilla"): return True else: return False
[ "def is_interactive(request: Request):\n return any([u in request.headers['user-agent'] for u in ['Mozilla', 'Gecko', 'Trident', 'WebKit', 'Presto', 'Edge', 'Blink']])", "def can_fetch(self, useragent, url):\r\n _debug(\"Checking robots.txt allowance for:\\n user agent: %s\\n url: %s\" %\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export bibtex given an identifier
def _export(identifier): api = API() doc = api.abstract(identifier) if 'bibcode' in doc and doc['bibcode'] != identifier: target_url = _url_for('abs', identifier=doc['bibcode'], section='exportcitation') return redirect(target_url, code=301) if doc.get('export'): if 'bibcode' in ...
[ "def save_bibtex(self):\n if self.paper:\n # Add file link to bibtex\n file_type = 'PDF'\n bibtex_ads = self.bibtex_lines_to_string(self.bibtex)\n file_bibtex_string = ':{}:{}'.format(self.name, file_type)\n file_bibtex_string = '{' + file_bibtex_string ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Graphics for a given identifier
def _graphics(identifier): api = API() doc = api.abstract(identifier) if 'bibcode' in doc and doc['bibcode'] != identifier: target_url = _url_for('abs', identifier=doc['bibcode'], section='graphics') return redirect(target_url, code=301) if len(doc.get('graphics', {}).get('figures', []))...
[ "def draw_component(self):\n SCREEN.blit(self.text_img, (self.rect.x + 5, self.rect.y + 5))\n pygame.draw.rect(SCREEN, self.color, self.rect)", "def draw(o,image,pt):\n pass", "def draw(self) -> None:\n\n \"\"\"\n TODO: Add logic for handling multiple draw functions\n \"\"\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Metrics for a given identifier
def _metrics(identifier): api = API() doc = api.abstract(identifier) if 'bibcode' in doc and doc['bibcode'] != identifier: target_url = _url_for('abs', identifier=doc['bibcode'], section='metrics') return redirect(target_url, code=301) if int(doc.get('metrics', {}).get('citation stats', ...
[ "def get_image_metrics(id, name):\n metrics = find_metrics(id, name)\n return jsonify(metrics), 200", "def find_metrics(id, name):\n user = UserData.objects.raw({\"_id\": id}).first()\n names = user.image_name\n CPU_times = user.processing_time\n sizes = user.image_size\n upload_times = user....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build full ADS url from a core request
def _build_full_ads_url(request, url): full_url = "" params_dict = {} for accepted_param in ('q', 'rows', 'start', 'sort', 'p_'): if accepted_param in request.args: params_dict[accepted_param] = request.args.get(accepted_param) params = urllib.parse.urlencode(params_dict) if url:...
[ "def construct_url(context, request):", "def build(self, ):\n url = self.BASE_URL\n params = {}\n for name in self.parameters:\n if isinstance(self.parameters[name], (tuple, list)):\n params[name] = ','.join(self.parameters[name])\n continue\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Commit changes to the database Always returns True
def commit(self) -> bool: # if self.con: self.con.commit() return True
[ "def commit(self):\n\t\tself.dbConnection.commit()", "def _do_commit(self):\n self.backend.commit()", "def commit_db(self):\n\t\tself.conn.commit()\n\t\tself.conn.close()", "def commit(self, session):\n session.commit()", "def commit_db(self):\n if self.con:\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Object creation happens before character generation so it shouldn't be run again If you want to be able to extend characters after generation, please use a separate function and call it during character generation to ensure new characters get those features. Customizable stats should be generated in character generatio...
def at_object_creation(self): super(Character, self).at_object_creation() # would be valuable to have a character_update_health function which # manages max health and triggers death. self.db.health = 20 self.db.max_health = 40 class BodyPart(object): """ A...
[ "def __init__(self, script_object):\n super().__init__(pygame.Rect(script_object.x * RENDER_SCALE, script_object.y * RENDER_SCALE, 0, 0))\n self.script_path = script_object.properties[\"Script Path\"]\n self.__globals = dict()\n self.locals = dict()\n exec(open(self.script_path).r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare the inputs for submission for the given process, according to its spec. That is to say that when an input is found in the inputs that corresponds to an input port in the spec of the process that expects a `Dict`, yet the value in the inputs is a plain dictionary, the value will be wrapped in by the `Dict` class...
def prepare_process_inputs(process, inputs): prepared_inputs = wrap_bare_dict_inputs(process.spec().inputs, inputs) return AttributeDict(prepared_inputs)
[ "def test_preprocess_input_dict() -> None:\n input = json.dumps({\"inputs\": [\"test\"]})\n with pytest.raises(AssertionError):\n main.__process_input(input)", "def prepare_process_inputs(inputs, namespaces=None, exclude_parameters=None):\n prepared_inputs = AttributeDict()\n\n if namespaces is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrap bare dictionaries in `inputs` in a `Dict` node if dictated by the corresponding port in given namespace.
def wrap_bare_dict_inputs(port_namespace, inputs): from aiida.engine.processes import PortNamespace wrapped = {} for key, value in inputs.items(): if key not in port_namespace: wrapped[key] = value continue port = port_namespace[key] if isinstance(port, P...
[ "def prepare_process_inputs(inputs, namespaces=None, exclude_parameters=None):\n prepared_inputs = AttributeDict()\n\n if namespaces is None:\n namespaces = []\n\n if exclude_parameters is None:\n exclude_parameters = []\n\n no_dict = ['options', 'metadata', 'potential', 'parameters']\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a predicate to check in a diamondshaped area.
def generate_diamond(self, block, distance, height=None, distanceZ=None, with_test_function=False): # check parameters if distanceZ == None: distanceZ = distance if height == None: height = distance try: name = block.get('tag', block['block']) ...
[ "def is_triangle_diamond(x, y, i):\n size = b(i)\n xmax = size - y - 1\n return abs(x) <= xmax and (xmax + x) % 2 == 0", "def _elementwise_predicate(predicate, solution, constraint):\n for i in range(Bridge.HEIGHT):\n for j in range(Bridge.WIDTH):\n if not predicate(solut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Redirect to social medias page
def social_media(name): data = { 'twitter':'https://twitter.com/theazibom', 'linkedin':'https://www.linkedin.com/in/mrsh/', 'github':'https://github.com/azibom', 'devto':'https://dev.to/azibom', 'stack':'https://stackoverflow.com/users/13060981/azibom', 'stackoverflow...
[ "def redirect_from_posts_to_brightnews():\n\n return redirect(\"brightnews\")", "def profile_social_settings_redirect(request):\r\n return HttpResponseRedirect(reverse('profile_social_settings',\r\n args=[request.user,]))", "def post_facebook_registration(self, request):\n# return redirect(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates the full phonon document from an item
def process_item(self, item: Dict) -> Optional[Dict]: self.logger.debug("Processing phonon item for {}".format(item["mp_id"])) try: structure = Structure.from_dict(item["abinit_input"]["structure"]) abinit_input_vars = self.abinit_input_vars(item) phonon_properties ...
[ "def email_document(item, expa_podio_email_hook, podioApi):\n ans = \"\"\n hook = expa_podio_email_hook\n \n #Guarda los transformadores de variable simples\n transformer_dict = {}\n #Guarda los transformadores de variable complejos\n related_transformer_dict = {}\n transformers = hook.trans...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts the breaking of the acoustic and charge neutrality sum rules. Runs anaddb to get the values.
def get_sum_rule_breakings(self, item: dict) -> dict: structure = Structure.from_dict(item["abinit_input"]["structure"]) anaddb_input = AnaddbInput.modes_at_qpoint( structure, [0, 0, 0], asr=0, chneut=0 ) with tempfile.TemporaryDirectory() as workdir: ddb_path = ...
[ "def calc_bac(parameters, bonds, task):\n correction = 0.\n bacfile = parameters['bacdirectory'] + '/bac.txt'\n #bacfile = 'bac.txt'\n bacfile = io.read_file(bacfile)\n if task + '\\n' in bacfile:\n bacfile = bacfile.split(task + '\\n')[1].split('\\n\\n')[0]\n bacfile = bacfile.splitlin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates the AnaddbInput object to calculate the phonon properties. It also returns the list of qpoints labels for generating the PhononBandStructureSymmLine.
def get_properties_anaddb_input( self, item: dict, bs: bool = True, dos: str = "tetra", lo_to_splitting: bool = True, use_dieflag: bool = True, ) -> Tuple[AnaddbInput, Optional[List]]: ngqpt = item["abinit_input"]["ngqpt"] q1shft = [(0, 0, 0)] ...
[ "def get_pmg_bs(\n phbands: PhononBands, labels_list: List\n ) -> PhononBandStructureSymmLine:\n\n structure = phbands.structure\n\n n_at = len(structure)\n\n qpts = np.array(phbands.qpoints.frac_coords)\n ph_freqs = np.array(phbands.phfreqs)\n displ = np.array(phbands.p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a PhononBandStructureSymmLine starting from a abipy PhononBands object
def get_pmg_bs( phbands: PhononBands, labels_list: List ) -> PhononBandStructureSymmLine: structure = phbands.structure n_at = len(structure) qpts = np.array(phbands.qpoints.frac_coords) ph_freqs = np.array(phbands.phfreqs) displ = np.array(phbands.phdispl_cart) ...
[ "def set_band_structure(self, bands):\n self._band_structure = GruneisenBandStructure(\n bands,\n self._phonon.dynamical_matrix,\n self._phonon_plus.dynamical_matrix,\n self._phonon_minus.dynamical_matrix,\n delta_strain=self._delta_strain,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts the useful abinit input parameters from an item.
def abinit_input_vars(item: dict) -> dict: i = item["abinit_input"] data = {} def get_vars(label): if label in i and i[label]: return {k: v for (k, v) in i[label]["abi_args"]} else: return {} data["gs_input"] = get_vars("gs_inpu...
[ "def _process_parameter(self, item):\n a_param = nodes.Parameter()\n logger = logging.getLogger(self.__class__.__name__)\n\n # In a Full CWMP-DM XML, Parameters always have a @name, @access, and syntax\n a_param.set_name(item[\"@name\"])\n a_param.set_access(item[\"@access\"])\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the thermodynamic properties from a phonon DOS
def get_thermodynamic_properties( ph_dos: CompletePhononDos, ) -> Tuple[ThermodynamicProperties, VibrationalEnergy]: tstart, tstop, nt = 0, 800, 161 temp = np.linspace(tstart, tstop, nt) cv = [] entropy = [] internal_energy = [] helmholtz_free_energy = [] for t in temp: cv.app...
[ "def thermodynamics(pyom):\n advect_temperature(pyom)\n advect_salinity(pyom)\n\n if pyom.enable_conserve_energy:\n \"\"\"\n advection of dynamic enthalpy\n \"\"\"\n if pyom.enable_superbee_advection:\n advection.adv_flux_superbee(pyom,pyom.flux_east,pyom.flux_north,p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator function. Test connection and attempts to reconnect if not connected. Reinstitutes idle state
def __mpdconnect(fn): def wrapper(self,*args,**kwargs): # check if idle set result = True try: self.mpdc.noidle() except MPDConnectionError as e: self.mpdc.connect("localhost", 6600) result = False except: self.__printer('WEIRD... no idle was set..') ret = fn(self,*args,**kwa...
[ "def test_reconnect_all(self):\n pass", "def reuse_or_reconnect(self):\n if not self.isconnected():\n self.connect()", "def reconnect():\n disconnect()\n connect()", "def _reconnect(self):\n self._terminate()\n self._session_init()\n self._connect()", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plays first track of next folder and turns off random
def next_folder(): curr_pos = self.__pls_pos_curr() # update dir playlist positions if len(self.pls_dir_pos) == 0 and curr_pos >0: self.pls_gather_dir_pos() next_pos = self.__pls_pos_next_dir(curr_pos) try: self.mpdc.play(next_pos) except MPDCommandError as e: self.__printer("ERROR: {0}".f...
[ "def play_folder(self, play_folder):\n posixPath_list = list(pathlib.Path(play_folder).rglob(\"*.[mM][pP]3\"))\n if posixPath_list:\n filelist = [str(pp) for pp in posixPath_list]\n random.shuffle(filelist)\n print(\"\\rPlaying folder (%s) with %d files\" % (play_folde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate playlist for given MPD directory
def pls_pop_dir(self, location): self.__printer('Populating playlist, folder: {0}'.format(location)) try: #self.mpdc.command_list_ok_begin() self.mpdc.findadd('base',location) results = self.mpdc.status() # get count #results = self.mpdc.command_list_end() except: self.__printer('ERROR: folder ...
[ "def open_playlist(self):\n directory = filedialog.askdirectory(parent=self)\n if not directory:\n return\n for file in os.listdir(directory):\n if file.endswith(\".mp3\"):\n file_path = directory + \"/\" + file\n self.playlist_treeview.insert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate playlist with given list of streams
def pls_pop_streams(self, streams): self.__printer('Populating playlist') for stream in streams: self.mpdc.add(stream)
[ "def __init__(self):\n self.playlist_name = None\n self.playlist_video_ids = []", "def main(listing):\n\n util.printr(\"Begin streams.from_listing...\")\n\n # fetch the album listing\n with open(listing) as fptr:\n batch = json.load(fptr)\n\n # iterate over albums in the listing\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the playlist is populated (deprecate?)
def pls_is_populated(self): self.__printer('Checking if playlist is populated') self.mpdc.command_list_ok_begin() self.mpdc.status() results = self.mpdc.command_list_end() return results[0]['playlistlength']
[ "def test_no_playlist(self):\n lib = self.__generate(playlists_cnt=0)\n self.assertEqual(lib.getPlaylistNames(), [])\n self.assertNotEqual(lib.songs, {})", "def test_player_empty_playlist():\n window = PhotoFrame(Config(\"tests/test_empty.yml\"))\n window.setup()\n window.start()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return current playlist position
def __pls_pos_curr(self): status = self.mpdc.status() if 'song' in status: return status['song']
[ "def audacious_playlist_position(self):\n self.writeCommand('audacious_playlist_position')\n return self", "def current_position(self):\n try:\n pos, format = self.player.query_position(gst.FORMAT_TIME)\n except:\n position = 0\n else:\n position...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return playlist position of next directory
def __pls_pos_next_dir(self, current_pos=0): if current_pos == 0: return 1 if len(self.pls_dir_pos) == 0: return for dir_pos in self.pls_dir_pos: if dir_pos > current_pos: return dir_pos # wrap around return 1
[ "def next_folder():\t\n\t\tcurr_pos = self.__pls_pos_curr()\n\t\t\n\t\t# update dir playlist positions\n\t\tif len(self.pls_dir_pos) == 0 and curr_pos >0:\n\t\t\tself.pls_gather_dir_pos()\t\t\n\t\t\n\t\tnext_pos = self.__pls_pos_next_dir(curr_pos)\n\t\ttry:\n\t\t\tself.mpdc.play(next_pos)\n\t\texcept MPDCommandErro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter a generator of pages and return a new generator of pages where a given role is set to a user with a given cnetid.
def _get_pages_with_role_for_cnet(self, pages, cnetid, site_name, role): yield self.HEADER for page in pages: user = self._get_attr(page, role) user_cnetid = self._get_attr(user, 'cnetid') if user_cnetid == cnetid: yield self.get_row(page, cnetid, site...
[ "def _get_pages_with_any_role_for_cnet(self, pages, cnetid, site_name, role):\n yield self.HEADER\n for page in pages:\n page_maintainer = self._get_attr(page, 'page_maintainer')\n editor = self._get_attr(page, 'editor')\n content_specialist = self._get_attr(page, 'con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter a generator to return any page that has any role assigned to a user with a given cnetid.
def _get_pages_with_any_role_for_cnet(self, pages, cnetid, site_name, role): yield self.HEADER for page in pages: page_maintainer = self._get_attr(page, 'page_maintainer') editor = self._get_attr(page, 'editor') content_specialist = self._get_attr(page, 'content_speci...
[ "def _get_pages_with_role_for_cnet(self, pages, cnetid, site_name, role):\n yield self.HEADER\n for page in pages:\n user = self._get_attr(page, role)\n user_cnetid = self._get_attr(user, 'cnetid')\n if user_cnetid == cnetid:\n yield self.get_row(page, c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an attribute for an object if it exists otherwise return an empty string.
def _get_attr(self, obj, attr): if hasattr(obj, attr): # Since string attributes have a method called title if obj == '' and attr == 'title': return '' return getattr(obj, attr) return ''
[ "def get_attribute(self, att):\r\n if att in self.attributes:\r\n return self.attributes[att]\r\n else:\r\n return None", "def get(self, obj):\n return getattr(obj, self.attr)", "def getAttr(self,attr):\n try: return self.__getattribute__(attr)\n\texcept: return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats a filesystem path to a valid Sqlite URI. Under Windows, the backward slash \ must be replaced with forward slash /
def formatSqliteURI( path ): if (path is ':memory:'): return path return path.replace('\\','/').replace(':','|')
[ "def escape_path(full_path):\n if is_windows():\n full_path = full_path.replace(\"\\\\\", \"\\\\\\\\\")\n return full_path", "def to_fs_path(uri):\n # scheme://netloc/path;parameters?query#fragment\n scheme, netloc, path, _params, _query, _fragment = urlparse(uri)\n\n if netloc and path and ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes the corresponding filesystem db file
def deleteDb(cls, filepath): try: os.remove(filepath) except: pass
[ "def del_database():\n path = os.path.join(os.getcwd(), \"WorkTimer.db\")\n database.connection.close()\n os.system(f\"del /f {path}\")", "def wipe_database():\r\n dbpath = \"/\".join(__file__.split('/')[:-1] + ['samples.db'])\r\n os.system(\"rm -f {0}\".format(dbpath))", "def delete(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes the corresponding filesystem db file
def deleteDb(cls, filepath): try: os.remove(filepath) except: pass
[ "def del_database():\n path = os.path.join(os.getcwd(), \"WorkTimer.db\")\n database.connection.close()\n os.system(f\"del /f {path}\")", "def wipe_database():\r\n dbpath = \"/\".join(__file__.split('/')[:-1] + ['samples.db'])\r\n os.system(\"rm -f {0}\".format(dbpath))", "def delete(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve an xml elemnt by path mapped in the cfg.XML_DICT_MAP
def get_xml_element(root, element_name_or_path): if element_name_or_path.startswith('//'): return root.xpath(element_name_or_path, namespaces=cfg.TEI_NS) else: return root.xpath(cfg.XML_DICT_MAP[element_name_or_path][0], namespaces=cfg.TEI_NS)
[ "def get_dic_item(_dic, xpath):\n elem = _dic\n try:\n for x in split_path(xpath):\n elem = elem.get(x)\n return elem\n except KeyError:\n return None", "def find(self, key):\n return find(self.root, key)", "def _load_builtin_xml(xmlpath, parser):\n #First we n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return text of the first item of the list of items for the path. Useful for retieving an abstract and title.
def get_first_text (root, element_name_or_path): text_list = get_xml_element(root, element_name_or_path) if text_list: if isinstance(text_list[0], str): return str(text_list[0]) else: return text_list[0].text return ''
[ "def item_one(items):\n return items[0] if len(items) > 0 else ''", "def items(self) -> None:\n print(\"Item\\t\\t|\\tPath\")\n\n for item in self.path_list.items():\n print(item[0] + \"\\t|\\t\" + item[1])", "def _find_item_text(self, item):\n fh = open(self.TODO_TXT, 'r')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a dedicated cache location for pdf files
def create_cache(): if cfg.CACHE_PDF: os.makedirs(cfg.CACHE_PATH, exist_ok=True) os.makedirs(cfg.CACHE_UNREADABLE_PATH, exist_ok=True)
[ "def _create_cache(self):\n if self._cachepath: # user defined cache path.\n if not os.path.exists(self._cachepath):\n os.makedirs(self._cachepath) # create cache\n self.path = self._cachepath if self._cachepath else tempfile.mkdtemp()", "def file_cache(tmpdir):\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert pdf file to xml string using Grobid API.
def pdf_to_xml(pdf_path, pdf_content=None): if not pdf_content: if os.path.exists(pdf_path): with open(pdf_path, "rb") as pdf_file: pdf_content = pdf_file.read() # http://localhost:8070 url = cfg.GROBID_API_URL xml = requests.post(url, files={'input': pdf_content}) ...
[ "def xml(self, pdf_path, xml_path=None):\n return self.convert(pdf_path, xml_path, out_format=FORMAT_XML)", "def convert_pdf_to_xml(path):\n cmd = ['pdftohtml', '-xml', '-f', '1', '-l', '1',\n '-i', '-q', '-nodrm', '-hidden', '-stdout', path]\n # https://stackoverflow.com/questions/15374211...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Feedback static computation u = c(y,r,t) INPUTS
def c( self , y , r , t = 0 ): u = np.zeros(self.m) # Ref q_d = r # Feedback from sensors x = y [ q , dq ] = self.x2q( x ) # Error e = q_d - q de = - dq ie = self.e_int + e * self.dt ...
[ "def c( self , y , r , t = 0 ):\n \n u = np.zeros(self.m) \n \n # State feedback\n q = y[ 0 : self.dof ]\n dq = y[ self.dof : 2 * self.dof ]\n \n H = self.sys.H(q)\n C = self.sys.C(q,dq)\n d = self.sys.d(q,dq)\n g = self.sy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Petunia LED units have 5 red LEDs, 6 white LEDs and 1 blue LED, so the energy consumption estimate should reflect that.
def energy_consumption(self, weights): return (weights['a'] * red_channel_wattage) +(weights['b'] * white_channel_wattage) + (weights['c'] * blue_channel_wattage)
[ "def energyMultiplier(self) -> float:\n return self._getMultiplier('energy')", "def getEnergy(self) -> float:\n ...", "def thermal_conductivity(self):\n return 70.0 * units.watt / (units.meter * units.kelvin)", "def generationEnergy(self):\n return self.energy + BULLETKEFACTOR * self.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simulate plant utilization of the output radiance based on the model action spectrum The best possible quantum_yield would be if the action spectrum were flat 1.0. Then all radiance would be efficiently turned into product
def quantum_yield(self, action_spectrum): spectral_QY = action_spectrum * self.get_PAR_output() quantum_yield = np.mean(spectral_QY) # NOTE: Here's the Emerson Enhancement effect return quantum_yield
[ "def ProduceSpectrum(detuning, params, toPlot = True):\n\n\t# Use the input of the function to determine the polarisation of the input light.\n\tE_in = np.array([np.cos(params[\"Etheta\"]), np.sin(params[\"Etheta\"]), 0])\n\n\t# Determine the effect of the final polariser on the output field using a Jones matrix.\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AuthenticationTokenForm requires the user kwarg.
def get_form_kwargs(self, step=None): if step == 'token': return { 'user': self.get_user(), } return {}
[ "def login_form(self, formdata=None):\n return self.login_form_class(formdata)", "def get_parameters(user):\n return {TOKEN_FIELD_NAME: UrlAuthBackendMixin().create_token(user)}", "def test_album_create_view_get_form_kwargs_assigns_current_user(self):\n from imager_images.views import AlbumCrea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finish the wizard. Save all forms and redirect.
def done(self, form_list, **kwargs): # TOTPDeviceForm if self.get_method() == 'generator': for form in form_list: if callable(getattr(form, 'save', None)): form.save() # PhoneNumberForm if self.get_method() in ('call', 'sms'): ...
[ "def on_wizard_finish(self, wizard):\r\n pass", "def process(self): \n\t\tself.status = wx.ID_OK\n\t\tscripting.unregisterDialog(self.dialogName)\n\t\tself.Close()", "def post(self, *args, **kwargs):\n # Look for a wizard_goto_step element in the posted data which\n # contains a valid ste...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lookup the dist_normal_diag_ad_set_dim_map and return hash_value and hash_key
def dist_normal_diag_KLdiv_ad_set_dim_func(head, mean, scale): key = [] key.append(tuple(head.shape)) key.append(tuple(mean.shape)) key.append(tuple(scale.shape)) key.append(mean.dtype) hash_key = str(tuple(key)) if hash_key in dist_normal_diag_ad_set_dim_map.keys(): return ct_util....
[ "def _get_dsmap(self):\n return self.__dsmap", "def recompute_clusters(self, medoids=np.ndarray(2)):\n dict_of_clusters = {}\n reversed_dict_of_clusters = {}\n\n for i in xrange(self.number_of_classes):\n reversed_dict_of_clusters[i] = []\n for n_i in self.nodes:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
make an instance of FieldFixCount and return it
def instance(data): return FieldFixCount(data)
[ "def get_num_of_plain_fields(self):\n pass", "def get_field_count(start, *path):\n\n cursor = _get_cursor(start)\n\n (intermediateNode, _) = _traverse_path(cursor, path)\n if intermediateNode:\n # we encountered an array with variable (-1) indices.\n # this is only allowed when calli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
form model_name according to self.parameters['fitmodel']
def form_model_name(self): model_d = self.parameters['fitmodel'] model_name = '' if model_d['pulse']: model_name += 'pulse' model_name += '_' + model_d['model'] if model_d['constrained']: model_name += '_constrained' if model_d['conv']: ...
[ "def _get_model_name(self):\n sysinfo = SystemInfo()\n model_name = sysinfo.get_model_name()\n return model_name", "def get_model_name(args):\n hiddensizes = '_' + str(args.D_h_features)\n model_name = const.MODEL_DIRECTORY + str(args.id) + '_model' + hiddensizes + '.pth'\n analysis_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns (x, y) if nothing matched where x denotes number of pegs that have right color but wrong position y denotes number of pegs that have right color and position
def check_guess(self, guess): x = 0 y = 0 #search for pegs with right color and position remaining_guesses = [] remaining_patterns = [] for (ii,pi) in enumerate(self.pattern): if pi == guess[ii]: y += 1 else: remain...
[ "def locate_empty(self):\n for x in range(9):\n for y in range(9):\n if self.grid[x][y] == 0:\n return (x, y)\n \n return None", "def get_locations(new_photo_filename, fake_dice_roll):\n white_coordinates = np.ndarray((15, 2))\n black_coordin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compares the pair (a, b) with BTL scores if there is budget left else performs a random vote.
def compare(a, b, scores, count, Budget): if(count < Budget): if(random.uniform(0, scores[a-1]+scores[b-1]) < scores[a-1]): return False else: return True else: if(random.uniform(0, 1) < 0.5): return False else: return Tru...
[ "def bid_algorithm(budget_left, auction_id, last_bid, won, price_paid, last_two_aves,high_bid_warning, high_bid_count ):\n \n if high_bid_warning:\n if high_bid_count < 10:\n high_bid_count+=1\n return 0\n else:\n high_bid_count = 0\n high_bid_warning ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a single random elements from the Counter collection, weighted by count.
def counter_random(counter, filter=None): if filter is not None: counter = {k: v for k, v in counter.items() if filter(k)} if len(counter) == 0: raise Exception("No matching elements in Counter collection") seq = list(counter.keys()) cum = list(itertools.accumulate(list(counter.values())...
[ "def _gen_random(self, count_map):\n seq = [[k, v] for k, v in count_map.items()]\n cur_index = 0\n for elem in seq:\n count = elem[1]\n elem.extend([cur_index, cur_index + count])\n cur_index += count\n total_count = cur_index\n rand_index = rando...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get genomewide nucleotide frequencies
def getNucFreqs(fasta, nucleotides): out = np.zeros(len(nucleotides)) n = 0.0 f = open(fasta,'r') for line in f: if line[0]!='>': sequence = line.rstrip('\n').upper() out += [sequence.count(i) for i in nucleotides] n += len(sequence) f.close() return o...
[ "def getNucFreqsFromChunkList(chunks, fasta, nucleotides):\n out = np.zeros(len(nucleotides))\n n = 0.0\n handle = pysam.FastaFile(fasta)\n for chunk in chunks:\n sequence = handle.fetch(chunk.chrom, chunk.start, chunk.end)\n sequence = sequence.upper()\n out += [sequence.count(i) f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get nucleotide frequences within regions of genome
def getNucFreqsFromChunkList(chunks, fasta, nucleotides): out = np.zeros(len(nucleotides)) n = 0.0 handle = pysam.FastaFile(fasta) for chunk in chunks: sequence = handle.fetch(chunk.chrom, chunk.start, chunk.end) sequence = sequence.upper() out += [sequence.count(i) for i in nucl...
[ "def getNucFreqs(fasta, nucleotides):\n out = np.zeros(len(nucleotides))\n n = 0.0\n f = open(fasta,'r')\n for line in f:\n if line[0]!='>':\n sequence = line.rstrip('\\n').upper()\n out += [sequence.count(i) for i in nucleotides]\n n += len(sequence)\n f.close...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Same a point from self.log_prob using slice sampling.
def slice_sample(self, point, fixed_parameters, *args_log_prob): dimensions = len(point) if self.component_wise: dims = range(dimensions) npr.shuffle(dims) new_point = point.copy() for d in dims: if d not in self.ignore_index: ...
[ "def sample_from_log_prob(self, log_prob, mode='argmax'):\n \n \n prob=log_prob.exp()\n \n if mode == 'sample':\n #option 1 : sample\n bptt, bsz = log_prob.shape\n output=torch.zeros(bptt, bsz)\n for time_step in range(bptt):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample a new point by doing slice sampling, and only moving the point towards the direction vector.
def direction_slice(self, direction, point, fixed_parameters, *args_log_prob): upper = self.sigma * npr.rand() lower = upper - self.sigma llh = np.log(npr.rand()) + self.directional_log_prob(0.0, direction, point, fixed_parameters, *a...
[ "def slice_sample(self, point, fixed_parameters, *args_log_prob):\n dimensions = len(point)\n\n if self.component_wise:\n dims = range(dimensions)\n npr.shuffle(dims)\n new_point = point.copy()\n for d in dims:\n if d not in self.ignore_index:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deletes specified number of messages from channel if message is specified, message will be echoed by bot after prune
async def _prune(self, ctx, num_to_delete : int, *message): # tmp channel/server pointer chan = ctx.message.channel serv = ctx.message.guild #if num_to_delete > 100: # api only allows up to 100 # await ctx.send('Sorry, only up to 100') # TODO - copy thing done in # retur...
[ "async def clear(self, ctx, num=None, *args):\n if len(num) == 18:\n args = ('0', int(num))\n num = 100\n try:\n int(num)\n except ValueError:\n await ctx.send(f\"You need to put a number of messages. Type `;help clear` for information on syntax.\")\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
lists public roles avalible in the server
async def _list(self, ctx): # pull roles out of the config file serv = ctx.message.guild names = [] m_len = 0 available_roles = self.conf.get(str(serv.id), {}).get('pub_roles', []) # if no roles, say so if not available_roles: await ctx.send('no public ...
[ "def list(ctx):\n click.echo('Listing roles in {}:'.format(ctx.obj['ansible_dotfiles_path']))\n for item in os.listdir(os.path.join(ctx.obj['ansible_dotfiles_path'], 'roles')):\n print(item)", "def get_roles(self) -> List[str]:\n pass", "def listroles(self):\n\n request_string = f\"{s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes role from requester(if in list)
async def _unrequest(self, ctx, role : str): # attempt to find role that user specied for removal auth = ctx.message.author serv = ctx.message.guild role = dh.get_role(serv, role) guild_id = str(serv.id) role_id = str(role.id) # if user failed to find specify role, complain if not rol...
[ "async def remove(self, ctx, *, role_name):\n found_role = None\n for role in ctx.guild.roles:\n if role.name.lower() == role_name.lower():\n found_role = role\n if found_role:\n try:\n success = await \\\n self.bot.pg_utils...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
manage topic if a new_topic is specified, changes the topic otherwise, displays the current topic
async def _topic(self, ctx, *, new_topic = ''): # store channel in tmp pointer c = ctx.message.channel if new_topic: # if a topic was passed, # change it if user has the permisssions to do so # or tell user that they can't do that if perms.check_permissions(ctx.message, manage_c...
[ "async def ctopic(self, ctx, channel: typing.Optional[discord.TextChannel]=None, *, topic=None):\n\t\tchan = channel or ctx.channel\n\t\toldtopic = chan.topic\n\t\tif len(topic) > 512:\n\t\t\treturn await ctx.send(\"The new topic is too long! Channel topics must be between 0 and 512 characters.\")\n\t\tawait chan.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the function accepts the id of the user vk.com and returns an ordered list of ages and the number of people with these ages as friends with this user
def calc_age(uid): token = '3e99f55f3e99f55f3e99f55f573ee8ea8333e993e99f55f6001db2bdd828ae9b36ef12e' user_id_params = { 'v': '5.71', 'access_token': token, 'user_ids': uid, } user_id = requests.get('https://api.vk.com/method/users.get', params=user_id_params).json() users_f...
[ "def get_friends_same_age(self,user):\r\n friendsSameAge = set()\r\n for friend in self.setOfFriends:\r\n if friend.get_age() == user.get_age():\r\n name=friend.get_name()\r\n friendsSameAge.add(name)\r\n return friendsSameAge", "def number_of_friends(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a random direction
def get_random_direction(direction_set): return random.choice(direction_set)
[ "def pickDirection():\n turtle.right(random.randrange(-1*MAX_ANGLE(),MAX_ANGLE()))", "def generateDirection(self):\n screenWidth, screenHeight = self.screen.get_size()\n randX = randint(0, screenWidth)\n randY = randint(0, screenHeight)\n randomPoint = Vec2d(randX, randY)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if an Azure Cosmos DB SQL database exists
def cli_cosmosdb_sql_database_exists(client, resource_group_name, account_name, database_name): try: client.get_sql_database(resource_group_name, account_name, database_name) except HttpRespons...
[ "def checkExistence_DB(self):\n DBlist = self.client.list_database_names()\n if self.DB_NAME in DBlist:\n # print(f\"DB: '{self.DB_NAME}' exists\")\n return True\n # print(f\"DB: '{self.DB_NAME}' not yet present OR no collection is present in the DB\")\n return Fals...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an Azure Cosmos DB SQL container
def cli_cosmosdb_sql_container_create(client, resource_group_name, account_name, database_name, container_name, partition_key_path...
[ "def cli_cosmosdb_sql_container_create(client,\r\n resource_group_name,\r\n account_name,\r\n database_name,\r\n container_name,\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates an Azure Cosmos DB SQL container
def cli_cosmosdb_sql_container_update(client, resource_group_name, account_name, database_name, container_name, default_ttl=None, ...
[ "def cli_cosmosdb_sql_container_update(client,\r\n resource_group_name,\r\n account_name,\r\n database_name,\r\n container_name,\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if an Azure Cosmos DB SQL container exists
def cli_cosmosdb_sql_container_exists(client, resource_group_name, account_name, database_name, container_name): try: client.get_sql_container(resource_grou...
[ "def _test_blob_container_existence(self, connection) -> bool:\r\n if not connection:\r\n return False\r\n\r\n try:\r\n # Throws exception if container not available\r\n return bool(connection.get_container_client(self._container))\r\n\r\n except azure.core.exce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates or Updates an Azure Cosmos DB SQL stored procedure
def cli_cosmosdb_sql_stored_procedure_create_update(client, resource_group_name, account_name, database_name, co...
[ "def createProcedure(self):\n try:\n mycursor = self.mydb.cursor()\n mycursor.execute(\"DROP PROCEDURE IF EXISTS EmpDep;\")\n mycursor.execute(\"CREATE PROCEDURE EmpDep() BEGIN select * from Employees JOIN Department where Department.Dept_id=Employees.Dept_id; END\")\n self.mydb.commit()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates or Updates an Azure Cosmos DB SQL user defined function
def cli_cosmosdb_sql_user_defined_function_create_update(client, resource_group_name, account_name, database_name, ...
[ "def assignDBFn(pyExpression, sqliteFnName):\n stFn = \"\"\"def pyFn(i,v): return {fCd}\"\"\".format(fCd=pyExpression)\n exec stFn\n datConn.create_function(sqliteFnName, 2, pyFn)", "def createFunction(self) -> ghidra.program.model.listing.Function:\n ...", "def add_new_function(conn, function_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an Azure Cosmos DB SQL trigger
def cli_cosmosdb_sql_trigger_create(client, resource_group_name, account_name, database_name, container_name, trigger_name, ...
[ "def cli_cosmosdb_sql_trigger_update(client,\n resource_group_name,\n account_name,\n database_name,\n container_name,\n trigger_name,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates an Azure Cosmos DB SQL trigger
def cli_cosmosdb_sql_trigger_update(client, resource_group_name, account_name, database_name, container_name, trigger_name, ...
[ "def hello_firestore(data, context):\n trigger_resource = context.resource\n\n print(\"Function triggered by change to: %s\" % trigger_resource)\n\n print(\"\\nOld value:\")\n print(json.dumps(data[\"oldValue\"]))\n\n print(\"\\nNew value:\")\n print(json.dumps(data[\"value\"]))", "def cli_cosmo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an Azure Cosmos DB Gremlin database
def cli_cosmosdb_gremlin_database_create(client, resource_group_name, account_name, database_name, throughput=None, ...
[ "def cli_cosmosdb_database_create(client, database_id, throughput=None):\n return client.CreateDatabase({'id': database_id}, {'offerThroughput': throughput})", "def create_learning_databases():\n pg_client = DBClient()\n pg_client.setup_connection('postgres')\n cursor = pg_client.conn.curs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if an Azure Cosmos DB Gremlin database exists
def cli_cosmosdb_gremlin_database_exists(client, resource_group_name, account_name, database_name): try: client.get_gremlin_database(resource_group_name, account_name, database_name) ...
[ "def checkExistence_DB(self):\n DBlist = self.client.list_database_names()\n if self.DB_NAME in DBlist:\n # print(f\"DB: '{self.DB_NAME}' exists\")\n return True\n # print(f\"DB: '{self.DB_NAME}' not yet present OR no collection is present in the DB\")\n return Fals...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an Azure Cosmos DB Gremlin graph
def cli_cosmosdb_gremlin_graph_create(client, resource_group_name, account_name, database_name, graph_name, partition_key_path, ...
[ "def create_graph(self, graph_name):", "def cli_cosmosdb_gremlin_graph_update(client,\n resource_group_name,\n account_name,\n database_name,\n graph_name,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates an Azure Cosmos DB Gremlin graph
def cli_cosmosdb_gremlin_graph_update(client, resource_group_name, account_name, database_name, graph_name, default_ttl=None, ...
[ "def cli_cosmosdb_gremlin_graph_throughput_update(client,\n resource_group_name,\n account_name,\n database_name,\n graph_na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if an Azure Cosmos DB Gremlin graph exists
def cli_cosmosdb_gremlin_graph_exists(client, resource_group_name, account_name, database_name, graph_name): try: client.get_gremlin_graph(resource_group_na...
[ "def has_graph(self, name=''):\n\n try:\n graph = self.database.graph(name)\n graph.properties()\n return True\n except exceptions.GraphPropertiesError:\n return False", "def check_graph():\n return None", "def cli_cosmosdb_gremlin_database_exists(cli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }