query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Queue a client as solving an operation
def enqueue(self, sid: str) -> Optional[str]: # Check if there's operations left to solve. if len(self.operations) == 0: return # Pop an operation from the local list. # Note that this don't actually change # the data held in the database. operation = self.o...
[ "def queue():\n\n # Check if the client is connected.\n if not session.is_connected():\n return dict(ok=False, error=\"Client not connected\")\n\n # Add the operation to the local queue.\n operation = manager.enqueue(session.get_sid())\n\n # If the local list of operation to solve is empty the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Webapp index. Usually there is some sort of frontend, but in this situation it just redirects to the entry point of the api.
def index(): return redirect(api)
[ "def main():\n return redirect('/index') # redirect /index", "def index():\n return application.send_static_file(\"index.html\"), 200", "def index():\n return render_template('index.html'), 200", "def index_redirect():\n redirect('/ardublockly/index.html')", "def index():\n return app.send_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queue a client as solving an operation
def queue(): # Check if the client is connected. if not session.is_connected(): return dict(ok=False, error="Client not connected") # Add the operation to the local queue. operation = manager.enqueue(session.get_sid()) # If the local list of operation to solve is empty the Mmanager.enqueu...
[ "def enqueue(self, sid: str) -> Optional[str]:\n\n # Check if there's operations left to solve.\n if len(self.operations) == 0:\n return\n\n # Pop an operation from the local list.\n # Note that this don't actually change\n # the data held in the database.\n oper...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a move for game through interactively asking the user for input.
def interactive_strategy(game: Any) -> Any: move = input("Enter a move: ") return game.str_to_move(move)
[ "def interactive_strategy(game: Game) -> Any:\n move = input(\"Enter a move: \")\n return game.str_to_move(move)", "def ask_move():\n user_input = input('Make a move(ex. b2 b3) or Q to quit: ')\n return user_input", "def interactive_strategy(game: Any) -> Any:\n move = input(\"Enter a move: \")\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
validate method Queries the facebook GraphAPI to fetch the user info
def validate(auth_token): try: graph = facebook.GraphAPI(access_token=auth_token, version="3.0") profile = graph.request('/me?fields=id,name,email') return profile except: message = "The token is invalid or expired." return message
[ "def get_user_info(instaname):\r\n user_id=get_user_id(instaname) #calling get_user_id() fucntion and getting insta id\r\n if user_id==None:\r\n print colored(\"ID dont exist\",\"red\") #print when id is null\r\n else:\r\n try:\r\n request_url = (BASE_URL + \"users/%s/?...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test that CentroidRescaler's compute_centroids agrees with _slow_compute_centroids on random instances of varying size
def test_compute_centroids(n_instances=10): for _ in range(n_instances): coords, group_inds = _generate_random_instance() # assert compute_centroids agrees with _slow_compute_centroids rescaler = CentroidRescaler(group_inds) fast_centroids = rescaler.compute_centroids(coords) ...
[ "def _evaluate_centroids(self):\n\n for c in self.centroids:\n _prev_cent = self._prev_centroids[c]\n _curr_cent = self.centroids[c]\n\n if self._euclidean_distance(_prev_cent, _curr_cent) > self.tol:\n return\n self._optimized = True", "def test_latti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test some of the utility calculations, e.g. coherence limit
def test_rb_utils(self): t1 = 100. t2 = 100. gate2Q = 0.5 gate1Q = 0.1 twoq_coherence_err = rb.rb_utils.coherence_limit(2, [t1, t1], [t2, t2], gate2Q) oneq_coherence_err = rb.rb_utils.coherence_limit(1, [t1], ...
[ "def test_check_cost():", "def test_positive_electrode_potential_profile(self):\n\n # TODO: add these when have averages", "def test_analytical_vs_numerical():\n pass", "def test_get_speed_limit():\n center = Coordinates(1 , 1)\n radius = 10\n speed_limit = 20\n\n assert get_speed_limit(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The encoding string to be used, extracted from the HTML and
def encoding(self): if self._encoding: return self._encoding # Scan meta tags for charset. if self._html: self._encoding = html_to_unicode(self.default_encoding, self._html)[0] # Fall back to requests' detected encoding if decode fails. try: ...
[ "def _get_encoding(cls, page, contents=None):\r\n plist = page.headers.getplist()\r\n if plist:\r\n key, value = plist[-1].split('=')\r\n if key.lower() == 'charset':\r\n return value\r\n if contents:\r\n try:\r\n return xml.dom.min...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Property setter for self.encoding.
def encoding(self, enc): self._encoding = enc
[ "def set_encoding(self, encoding):\n pass", "def setEncoding(self,value):\n self.PDFreactorConfiguration.in1[\"encoding\"] = value", "def setTextEncoding(self, encoding):\n self._textEncoding = encoding", "def set_data_encoding(self, encoding):\n self._data_encoding = encoding", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The full text content (including links) of the
def full_text(self): return self.lxml.text_content()
[ "def get_text():", "def get_main_content(self):\n content, content_type = self.get_attachment('html')\n if not content:\n content, content_type = self.get_attachment('txt')\n return cid_links(content), content_type", "def get_fulltext_of_work(work):\n\n\ttext_html_string = work.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rewrites attributes if it have an srcset type attribute which prevents rendering of img from its original src attribute url.
def _remapImages(self): if self.lxml is None: raise RuntimeError("Couldn't rewrite images for the url %s" % self.url) set_url = re.compile(r'((?:https?:\/|)[\w\/\.\\_-]+)') for elem in self.lxml.xpath('.//img[@*]'): _keys = elem.attrib.keys() LOGGER.debug("...
[ "def fix_images_encode(self, url, soup, file_descriptor):\n\t\t# Open output file, read lines, and begin parsing to replace all incomplete img src URLs\n\t\tprint(\"[+] Proceeding with updating IMG tag src attributes using: {}\".format(url))\n\t\tprint(\"[+] The src attrbitues that will be modified:\")\n\t\ttry:\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the html of the page to a default or specified file.
def save_html(self, file_name=None, raw_html=True): if raw_html: with open(file_name or self.url_obj.file_path, 'wb') as fh: fh.write(self.raw_html) else: self.lxml.getroottree().write(file_name or self.url_obj.file_path, method="html")
[ "def save(self):\n with open(self.html_file(), 'w') as file:\n file.write(self.html)", "def save(self):\n html_file = '{}/{}.html'.format(self.web_dir, self.title)\n f = open(html_file, 'wt')\n f.write(self.doc.render())\n f.close()", "def saveHtml(path: str, filena...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send new AI to API, if successful redirects to second step using AIID as a parameter, if not raises a error message and redirect back to the form.
def form_valid(self, form): ai = form.save( token=self.request.session.get('token', False), aiid=self.kwargs.get('aiid', '') ) # Check if save was successful if ai['status']['code'] in [200, 201]: level = messages.SUCCESS redirect_url = H...
[ "def start_flow(api_url):\n authorization_url, state = client.authorization_url(authorization_base_url)\n webbrowser.open(authorization_url)\n redirect_response = input('Input redirect url:')\n client.fetch_token(token_url, client_secret=client_secret, authorization_response=redirect_response)\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update context adding import form
def get_context_data(self, **kwargs): context = super(AIUpdateView, self).get_context_data(**kwargs) context['import_form'] = ImportAIForm return context
[ "def import_files(self, event:tk.Tk):\n open_import_dialog(self)", "def importar():\n\n template = 'categorias/importar/form-importar.html'\n categorias = MagCategorias.by(parent_id=2)\n form = ImportarCategoriaForm()\n config = ConfigMagento.by_id(1)\n has_cat_default = config.categoria_def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update context with Intents list and Entities formsets
def get_context_data(self, **kwargs): context = super(IntentsEditView, self).get_context_data(**kwargs) # Get entities entities = get_entities_list( self.request.session.get('token', False), self.kwargs['aiid'] ).get('entities') # Custom entities goes f...
[ "def update_context(self, intent):\n for tag in intent['__tags__']:\n if 'entities' not in tag:\n continue\n context_entity = tag['entities'][0]\n if self.context_greedy:\n self.context_manager.inject_context(context_entity)\n elif con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the form or entities_formset is invalid, render the invalid form.
def form_invalid(self, form, formsets): return self.render_to_response( self.get_context_data(form=form, formsets=formsets) )
[ "def form_invalid(self, form):\n print form.errors\n return self.render_to_response(self.get_context_data(form=form))", "def form_invalid(self, form):\n return self.render_to_response(self.get_context_data(form=form))", "def form_invalid(self, form):\n return self.render_to_response(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Custom post for handling both Intent form and Entities entities_formset
def post(self, request, *args, **kwargs): # Get entities entities = get_entities_list( self.request.session.get('token', False), self.kwargs.get('aiid') ).get('entities') intents = [intent['intent_name'] for intent in get_intent_list( self.request.se...
[ "def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n update_form = UpdateFormSet(self.request.POST)\n if (form.is_valid() and update_form.is_valid()):\n return self.form_va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find if a (left, right) pair is already in the list
def lookup(self, left, right): for val in self.find_left(left): if right == val: return True return False
[ "def __contains__(self, pair):\n aVal, bVal = pair\n return aVal in self._forwardMap and \\\n bVal in self._forwardMap.__getitem__(aVal)", "def isPair(a, b):\n pairs = {}\n pairs[\"A\"] = set([\"U\"])\n pairs[\"U\"] = set([\"A\", \"G\"])\n pairs[\"G\"] = set([\"C\", \"U\"]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all ids in dictionary where
def find(where, ids): if not ids: return if not isinstance(ids, (set, list, tuple)): ids = [ids] for key in ids: if key in where: for i in where[key]: yield i
[ "def _matchedIndexedIds(self, condition_dict):\n ids = None\n for field, condition in condition_dict.items():\n if ids is None: # 用于生成第一个id 的 set()\n ids = self._filterIndexedIds(field, condition)\n elif len(ids) > 0:\n ids &= self._filterIndexedIds...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find left values given a list of ids
def find_left(self, ids): return self.find(self.forward, ids)
[ "def _getLeft(self, list, index) :\n search = list[index:] + list[:index]\n search.reverse() # List reordered to be in the order we want to search\n for x in range(len(search)) :\n if search[x] == 1 :\n return (index - 1 - x) % len(list)\n if DEBUG : print \"no ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set debug (left, right) debug values for the structure
def set_debug(self, left, label, right): # lowercase left and right keys if is_str(left): left = left.lower() if is_str(right): right = right.lower() # remove duplicates in the debug structure # - duplicates in the structure itself are # - handled ...
[ "def set_debug(self, debug):\n self.debug = debug", "def test_nested_values(self):\n self.build()\n lldbutil.run_to_source_breakpoint(\n self, \"// break here\", lldb.SBFileSpec(\"main.c\")\n )\n self.runCmd(\"settings set auto-one-line-summaries false\")\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get debug information for a given key
def get_debug(self, key): # lowercase key if possible if is_str(key): key = key.lower() # return debug information if isinstance(key, list): return "type(list)" try: return self.debug[key] except KeyError: return "not-availa...
[ "def get_details(self, key):\r\n print({\"id:\" : self.register[key][0], \"path:\" : self.register[key][1]})", "def info(self, key):\n return self.execute_command(self.INFO_CMD, key)", "def output_debug_info(self):", "def debuggingInfo(self, debugStr=\"DEBUG: \"*30):\n print debugStr", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the input_types argument
def _parse_input_types(self, input_types): res_input_types = [] if isinstance(input_types, str): input_types = [input_types] if isinstance(input_types, list): for input_type in input_types: if isinstance(input_type, (tuple, list)): if n...
[ "def _read_args(self, types):\n self._read_ignored_tokens(False)\n start = self._offset\n args = {}\n if self._document_str[self._offset] == '(':\n self._offset += 1\n self._read_ignored_tokens(False)\n while self._document_str[self._offset] != ')':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Core method for looking up all keys in batch (iterator)
def key_lookup_batch(self, batchiter): pass
[ "def keys_iterator(keyspace, table_name):\n \n keys = keys_for_table(keyspace, table_name)\n row_keys = keys['row_keys']\n clustering_keys = keys['clustering_keys']\n columns = keys['columns']\n\n\n try:\n key_str = \", \".join(str(r) for r in row_keys)\n key_where_str = \"\"\"AN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs a nested lookup of doc using a period (.) delimited list of fields. This is a nested dictionary lookup.
def _nested_lookup(doc, field): value = doc keys = field.split(".") try: for k in keys: value = value[k] except KeyError: return None return str(value)
[ "def nested_lookup(doc, field):\n value = doc\n keys = field.split(\".\")\n try:\n for k in keys:\n if isinstance(value, (list, tuple)):\n # assuming we have a list of dict with k as one of the keys\n stype = set([type(e) for e in value])\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Property method for getting id_priority_list
def id_priority_list(self): return self._id_priority_list
[ "def PriorityList(self):\n if self.force_auto_sync:\n self.get('PriorityList')\n return self._PriorityList", "def id_priority_list(self, value):\n # pylint: disable=W0201\n self._id_priority_list = value\n self.input_types = self.sort_input_by_priority_list(self.input...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Property method for setting id_priority_list and sorting input_types and output_types.
def id_priority_list(self, value): # pylint: disable=W0201 self._id_priority_list = value self.input_types = self.sort_input_by_priority_list(self.input_types) self.output_types = self.sort_output_by_priority_list(self.output_types)
[ "def sort_input_by_priority_list(self, input_types):\n # construct temporary id_priority_list with extra elements at the end\n id_priority_list = self._expand_priority_order([x[0] for x in input_types])\n input_types = sorted(input_types, key=lambda e: self._priority_order(id_priority_list, e[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorder the given input_types to follow a priority list. Inputs not in the priority list should remain in their given order at the end of the list.
def sort_input_by_priority_list(self, input_types): # construct temporary id_priority_list with extra elements at the end id_priority_list = self._expand_priority_order([x[0] for x in input_types]) input_types = sorted(input_types, key=lambda e: self._priority_order(id_priority_list, e[0])) ...
[ "def sort_output_by_priority_list(self, output_types):\n # construct temporary id_priority_list with extra elements at the end\n id_priority_list = self._expand_priority_order(output_types)\n output_types = sorted(output_types, key=lambda e: self._priority_order(id_priority_list, e))\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorder the given output_types to follow a priority list. Outputs not in the priority list should remain in their given order at the end of the list.
def sort_output_by_priority_list(self, output_types): # construct temporary id_priority_list with extra elements at the end id_priority_list = self._expand_priority_order(output_types) output_types = sorted(output_types, key=lambda e: self._priority_order(id_priority_list, e)) return out...
[ "def sort_input_by_priority_list(self, input_types):\n # construct temporary id_priority_list with extra elements at the end\n id_priority_list = self._expand_priority_order([x[0] for x in input_types])\n input_types = sorted(input_types, key=lambda e: self._priority_order(id_priority_list, e[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expand the self.id_priority_list to also include elements in id_list that are not in the priority list. These elements are added to the priority list in the order that they appear in the id_list.
def _expand_priority_order(self, id_list): res = self.id_priority_list.copy() for key in id_list: if key not in self.id_priority_list: res.append(key) return res
[ "def id_priority_list(self, value):\n # pylint: disable=W0201\n self._id_priority_list = value\n self.input_types = self.sort_input_by_priority_list(self.input_types)\n self.output_types = self.sort_output_by_priority_list(self.output_types)", "def id_priority_list(self):\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the priority order of an input_type following a id_priority_list. This list, first defined in DataTransformMDB is used to reorder the input_types so that their order matches the id types listed in id_priority_list. If an id type is not in that list then the input_type will be placed at the end of the list in ...
def _priority_order(id_priority_list, elem): assert isinstance(id_priority_list, list) # match id types with id priority for index, id_elem in enumerate(id_priority_list): if elem == id_elem: return index # the id type is not in id_priority_list so it will be ...
[ "def sort_input_by_priority_list(self, input_types):\n # construct temporary id_priority_list with extra elements at the end\n id_priority_list = self._expand_priority_order([x[0] for x in input_types])\n input_types = sorted(input_types, key=lambda e: self._priority_order(id_priority_list, e[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
virtual method for edge lookup. Each edge class is responsible for its own lookup procedures given a keylookup_obj and an id_strct
def edge_lookup(self, keylookup_obj, id_strct, debug=False): # pylint: disable=E1102, R0201, W0613 yield NotImplemented("This method must be overridden by the base class.")
[ "def fk_lookup(self, table, identifier, arg, exc=False):\n\n key = '%s_%s' % (table, identifier)\n if key not in self.fkcache:\n self.fkcache[key] = {}\n\n with self.source_connection.cursor() as cr:\n cr.execute('SELECT %s, id '\n 'FROM %...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setter for the logger variable
def logger(self, value): self._state["logger"] = value
[ "def set_logger(self, logger): \n self.logger = logger", "def set_logger(self, logger):\n self.log = logger", "def logger(self, value):\n pass", "def set_logger(self, log):\n self.log = log", "def SetLogger(logger):\n global Log\n\n Log = logger", "def set_logger(self, lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs a nested lookup of doc using a period (.) delimited list of fields. This is a nested dictionary lookup.
def nested_lookup(doc, field): value = doc keys = field.split(".") try: for k in keys: if isinstance(value, (list, tuple)): # assuming we have a list of dict with k as one of the keys stype = set([type(e) for e in value]) if not stype: ...
[ "def _nested_lookup(doc, field):\n value = doc\n keys = field.split(\".\")\n try:\n for k in keys:\n value = value[k]\n except KeyError:\n return None\n\n return str(value)", "def normalize_dotted_fields(document):\n if isinstance(document...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the tokens needed to authenticate the access to any API the service might provide. Tumblr uses a pair of OAuthToken consisting on a oauth_token and oauth_token_secret. instance must be a UserSocialAuth instance.
def tokens(cls, instance): token = super(TumblrOAuth, cls).tokens(instance) if token and 'access_token' in token: token = dict(tok.split('=') for tok in token['access_token'].split('&')) return token
[ "def tokens(cls, instance):\r\n token = super(ReadabilityBackend, cls).tokens(instance)\r\n if token and 'access_token' in token:\r\n # Split the OAuth query string and only return the values needed\r\n token = dict(\r\n filter(\r\n lambda x: x[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of item types and subtypes.
def getTypesList(): return Gw2Spidy._request('types')['results']
[ "def getItemTypes(self):\r\n print (\"-\"*50)\r\n print (\"Processing item types request...\")\r\n all_types = []\r\n resources = \"itemtypes\"\r\n allowed_results = 10\r\n max_results = \"maxResults=\" + str(allowed_results)\r\n result_count = -1\r\n start_in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of crafting disciplines.
def getDisciplinesList(): return Gw2Spidy._request('disciplines')['results']
[ "def get_portfolio_disciplines(self):\n from savoy.contrib.portfolio.models import Role\n disciplines = self.project_role.all()\n return [ role.discipline for role in disciplines if role.discipline not in disciplines ]", "def __ui_list_disciplines(self):\n try:\n print(str(self.__discip...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of item rarities.
def getRaritiesList(): return Gw2Spidy._request('rarities')['results']
[ "def get_reagent_item_list(self) -> DBRecList:\n raise NotImplementedError('not implemented')", "def listRestock(self):\n #TODO return a list of items that need restocking\n #hint: Need to loop through the stocklist\n pass", "def rewards(self):\n return [sample.reward for sample i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of all items.
def getAllItemsList(): return Gw2Spidy._request('all-items', 'all')['results']
[ "def get_all(self,empty=True):\n with self.lock:\n items = self.items\n if empty: self.items = []\n return items", "def get_items(self):\n return self.item_list", "def items(self):\r\n return self.backend.all_items()", "def all(cls):\n app.logger.info(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of all items of a certain type.
def getItemsOfType(typeId): return Gw2Spidy._request('all-items', str(typeId))['results']
[ "def allItemsByType(self, itemType):\n if itemType.value not in self.__inventory__:\n return []\n return self.__inventory__[itemType.value]", "def get_items_of_type(self, item_type):\n return (item for item in self.items if item.get_type() == item_type)", "def get_item_list(metab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the data of a particular item. High frequency of update.
def getItemData(itemId): return Gw2Spidy._request('item', str(itemId))['result']
[ "def data(self, index):\n return self._itemData", "def Item(self) -> CounterData:", "def __getitem__(self, item):\n return self._state[\"data\"].get(item, None)", "def __getitem__(self, item):\r\n return self._state[\"data\"].get(item, None)", "def get_data_item(self):\n raise ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of all buy offers for a certain item.
def getItemBuyListings(itemId, allPages = False): return Gw2Spidy._paginatedRequest(allPages, 'listings', str(itemId), 'buy')
[ "def offers(self):\n return list(self._data)", "def get_item_prices(item_name):\r\n \r\n payload = dict()\r\n payload.update({'_nkw': item_name})\r\n payload.update({'LH_Sold': '1'})\r\n payload.update({'LH_Complete': '1'})\r\n payload.update({'_fosrp': '1'})\r\n payload.update({'_ipg'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of all sell offers for a certain item.
def getItemSellListings(itemId, allPages = False): return Gw2Spidy._paginatedRequest(allPages, 'listings', str(itemId), 'sell')
[ "def offers(self):\n return list(self._data)", "def get_offers():\n\n _logger.info(\"Start getting offers from tracker...\")\n\n response = requests_manager.get(\n requests.Session(),\n settings.TRACKER_URL,\n params={\"page\": \"Offers\", \"api_key\": settings.BINOM_API_KEY, \"g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search items by name. Might be slow, not recommended.
def searchItems(name, allPages = False): return Gw2Spidy._paginatedRequest(allPages, 'item-search', name)
[ "def items_contains_name(items, name):\n ret = 0\n # Loops all items and saves the searched one\n for x in range(len(items)):\n if items[x]['name'] == name:\n ret = x\n return ret", "def get_items_by_name(request, name):\n try:\n items = Items.objects.filter(titulo__icontai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of all crafting recipes for a certain discipline.
def getRecipesOfDiscipline(disciplineId, allPages = False): return Gw2Spidy._paginatedRequest(allPages, 'recipes', str(disciplineId))
[ "def getRecipes(self):\n return self._recipes", "def all_recipes():\n\n recipes = crud.get_recipes()\n ingredients = crud.get_ingredients()\n cleanses = crud.get_cleanses()\n recipe_ingredients = crud.get_recipe_ingredients()\n\n return render_template('recipes.html', recipes=recipes, ingred...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the data of a particular recipe.
def getRecipeData(recipeId): return Gw2Spidy._request('recipe', str(recipeId))
[ "def get_recipe(self, _id):\n raise NotImplementedError()", "def recipe(self):\n return self.__recipe", "def find_recipe(self, recipe_id):\n return self.find_doc('recipe', 'name', self.get_unique_recipe_name(recipe_id))", "def get_recipe(cls, recipeid):\n\n recipe = Recipe.query.fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle paginated requests, downloading all pages if requested.
def _paginatedRequest(allPages, *args): data = [] currentPage = 0 while True: newData = Gw2Spidy._request(*(args + (str(currentPage),))) if not allPages: return newData['results'] data.extend(newData['results']) currentPage = curren...
[ "def paginated_handling(self) -> global___Snippet.PaginatedResponseHandling:", "def _scrolling_request(self, path, method='GET', body=None, headers=None):\n assert 'pagination' in body\n paginated_view = body\n url = '{}{}'.format(self._url_base, path)\n headers = self._headers() if he...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a request on the GW2Spidy API.
def _request(*args): url = 'http://www.gw2spidy.com/api/v0.9/json/' + '/'.join(args) r = urllib2.Request(url, headers=Gw2Spidy.headers) if 'Cookie' not in Gw2Spidy.headers: resp = urllib2.urlopen(r) if 'set-cookie' in resp.headers: Gw2Spidy.headers['Cookie'] = resp.headers['set-cookie'].split(';',...
[ "async def request(self, **kwargs):\n # Flatten req dict to params dict\n flattened_params = self.__flatten_dict(kwargs)\n # Generate full query string and request signature\n signed_request = self.__signer.sign_request(flattened_params)\n # Headers\n headers = {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a chunk containing 'data', returning a string that is framed and (optionally, default) compressed. This data should be concatenated to the tail end of an existing Snappy stream. In the absence of any internal buffering, no data is left in any internal buffers, and so unlike zlib.compress, this method returns everyt...
def add_chunk(self, data, compress=None): if not self._header_chunk_written: self._header_chunk_written = True out = [struct.pack("<L", _IDENTIFIER_CHUNK + (len(_STREAM_IDENTIFIER) << 8)), _STREAM_IDENTIFIER] else: ...
[ "def compress(self, data):\n\n compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, +15) \n compressed_data = compress.compress(data) \n compressed_data += compress.flush()\n return compressed_data", "def compress(data, compresslevel=9):\n comp = BZ2Compressor(co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
All pending input is processed, and a string containing the remaining uncompressed output is returned. After calling flush(), the decompress() method cannot be called again; the only realistic action is to delete the object.
def flush(self): if self._buf != b"": raise UncompressError("chunk truncated") return b""
[ "def decompress(self, data):\n decompressor = zlib.decompressobj(-zlib.MAX_WBITS)\n data = decompressor.decompress(data) + decompressor.flush()\n return data", "def handle_string():\n input_string = receive_String()\n print(\"Before compression: \" + input_string + \"\\n\")\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a copy of the decompression object. This can be used to save the state of the decompressor midway through the data stream in order to speed up random seeks into the stream at a future point.
def copy(self): copy = StreamDecompressor() copy._buf, copy._header_found = self._buf, self._header_found return copy
[ "def _get_data_stream_decompressor():\n wbits = +15\n return zlib.decompressobj(wbits)", "def decompress(self, data):\n decompressor = zlib.decompressobj(-zlib.MAX_WBITS)\n data = decompressor.decompress(data) + decompressor.flush()\n return data", "def decompress(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an incoming filelike object and an outgoing filelike object, reads data from src, compresses it, and writes it to dst. 'src' should support the read method, and 'dst' should support the write method. The default blocksize is good for almost every scenario.
def stream_compress(src, dst, blocksize=_STREAM_TO_STREAM_BLOCK_SIZE): compressor = StreamCompressor() while True: buf = src.read(blocksize) if not buf: break buf = compressor.add_chunk(buf) if buf: dst.write(buf)
[ "def copyfileobj(src, dst, length=None):\r\n BUFSIZE = pipebuf.PIPE_BUF_BYTES\r\n\r\n if length == 0:\r\n return\r\n if length is None:\r\n shutil.copyfileobj(src, dst, BUFSIZE)\r\n return\r\n\r\n blocks, remainder = divmod(length, BUFSIZE)\r\n for b in xrange(blocks):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an incoming filelike object and an outgoing filelike object, reads data from src, decompresses it, and writes it to dst. 'src' should support the read method, and 'dst' should support the write method. The default blocksize is good for almost every scenario.
def stream_decompress(src, dst, blocksize=_STREAM_TO_STREAM_BLOCK_SIZE): decompressor = StreamDecompressor() while True: buf = src.read(blocksize) if not buf: break buf = decompressor.decompress(buf) if buf: dst.write(buf) decompressor.flush() # makes sure the stream ...
[ "def stream_compress(src, dst, blocksize=_STREAM_TO_STREAM_BLOCK_SIZE):\r\n compressor = StreamCompressor()\r\n while True:\r\n buf = src.read(blocksize)\r\n if not buf: break\r\n buf = compressor.add_chunk(buf)\r\n if buf: dst.write(buf)", "def copyfileobj(fsrc, fdst, length=16*...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is what is run when invoking snappy via the commandline. Try python m snappy help
def cmdline_main(): import sys if (len(sys.argv) < 2 or len(sys.argv) > 4 or "--help" in sys.argv or "-h" in sys.argv or sys.argv[1] not in ("-c", "-d")): print("Usage: python -m snappy <-c/-d> [src [dst]]") print(" -c compress") print(" -d ...
[ "def help(self):\n\n print(\"\"\"minimum-cli v0.4\nxminimum == bin/cli.py\n\nxmake == bin/makefile.py\nuse command xmake --help to learn more\n\n\"\"\")", "def print_help(self):\n print \"--uuid \\t<uuid of system> (use 'system-list' on the Hemlock server)\"\n print \"--client \\t <name of cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Full sorting of the order list. Uses the natural ordering of the orders, with the additional constraints of the before/after ordering.
def full_sort(orders: list or tuple) -> list: # We set up the topo sort to include the "before" and "after" objects # as another element in the sort. These are injected into the to-be # sorted list, and removed at the end. # Setup the topo sort. input_list = list(orders...
[ "def make_custom_sort(orders):\n orders = [{k: -i for (i, k) in enumerate(reversed(order), 1)} for order in orders]\n def process(stuff):\n if isinstance(stuff, dict):\n l = [(k, process(v)) for (k, v) in stuff.items()]\n keys = set(stuff)\n order = max(orders, key=lamb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the most appropriate SqlString instance, starting with the first platform value.
def get_for_platform( self, platforms: str or list or tuple) -> None or SqlString: if isinstance(platforms, str): platforms = [platforms] for plat in platforms: plat = plat.strip().lower() for sql in self.__sql_set: assert isinstan...
[ "def get_sequencing_platform(self):\n platform = self.data[\"platform\"]\n if platform == \"miseq\":\n platform = \"MiSeq\"\n elif platform == \"hiseq4000\":\n platform == \"HiSeq4000\"\n elif platform == \"hiseq2000\":\n platform == \"HiSeq2000\"\n else:\n raise...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the hello page on wildlife REST APIs usages ``GET``
def hello(): usage_msg = "<br/>\n".join(["Welcome to WildLife: The REST APIs for " "ZooKeeper!<br/>", hello.__doc__.replace("\n", "<br/>\n")]) return make_response(usage_msg, 200)
[ "def index():\n response = jsonify(\n {'message':'Hello, RESTful API development!'}\n )\n \n return response, 200", "def get(self, request):\n return JsonResponse({\"response\": \"Hello World !\"})", "def GET(self):\n pass", "async def hello(self) -> httpx.Response:\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the basic information of a specific cluster
def detail_cluster(cluster_name, znode): _cluster_info = dict() _cluster_info.update(app.clusters[cluster_name].__dict__) _cluster_info.pop("auth_data", None) _cluster_info["connection"] = app.managers[cluster_name]._client.state resp = Response(json.dumps(_cluster_info), status...
[ "def getClusterInfo(self):\n pass", "def get_cluster_details(cluster):\n out = run_cmd(f\"ibmcloud ks cluster get --cluster {cluster} -json\")\n return json.loads(out)", "def get_cluster_info(self) -> Dict[str, Any]:\n pass", "def get_cluster_details(cluster):\n cmd = f\"ocm describe cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a znode in a specific cluster
def cluster_create_znode(cluster_name, znode, headers=None): _zclient = get_client(cluster_name, headers or request.headers) acl_config = wildutils.ACLConfig(headers or request.headers) data = request_data(request) real_path_list = list() for (_znode, _zdata) in data.items...
[ "def test_create_cluster_network(self):\n pass", "def Create(ctx,\n mvip,\n svip,\n rep_count,\n username,\n password,\n nodes,\n accept_eula = None,\n attributes = None):\n \"\"\"\"\"\"\n \"\"\"Note: You need to log into...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the root children of a specific cluster
def cluster_list_children(cluster_name, znode, headers=None): return cluster_znode_children(cluster_name, "/", headers=headers or request.headers)
[ "def get_children(cluster):\n if is_leaf(cluster):\n raise TypeError(\"a leaf cluster has no children\")\n else:\n return cluster[1]", "def cluster_znode_children(cluster_name, znode, headers=None):\n\n _zclient = get_client(cluster_name,\n headers or request.header...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the znode data including the znodeStat, update the znode data and delete the znode
def cluster_znode(cluster_name, znode, headers=None): _zclient = get_client(cluster_name, headers or request.headers) if request.method == "GET": zdata = _zclient.get(znode) data = {"data": zdata[0], "znodeStat": wildutils.convert_zstat(zdata[1])} ...
[ "def get_and_delete(self,node):\n try:\n (data,stat) = zookeeper.get(self.handle, node, None)\n zookeeper.delete(self.handle, node, stat[\"version\"])\n return data\n except zookeeper.NoNodeException:\n # Someone deleted the node in between our get and delete\n return None\n except...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get or update the acls of a znode in a specific cluster
def cluster_znode_acls(cluster_name, znode, headers=None): _zclient = get_client(cluster_name, headers or request.headers) if request.method == "GET": acls = _zclient.get_acls(znode)[0] return make_response(str(acls), 200) if request.m...
[ "def cluster_znode(cluster_name, znode, headers=None):\n\n _zclient = get_client(cluster_name,\n headers or request.headers)\n if request.method == \"GET\":\n zdata = _zclient.get(znode)\n data = {\"data\": zdata[0],\n \"znodeStat\": wildutils.convert_zsta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get only the data of a znode in a specific cluster
def cluster_znode_data(cluster_name, znode, headers=None): zdata_resp = cluster_znode(cluster_name, znode, headers=headers) zdata = json.loads(zdata_resp.get_data()) resp = Response(zdata["data"], status=200, ...
[ "def get_nodes_in_cluster(self, context, cluster_id):", "def detail_cluster(cluster_name, znode):\n\n _cluster_info = dict()\n _cluster_info.update(app.clusters[cluster_name].__dict__)\n _cluster_info.pop(\"auth_data\", None)\n _cluster_info[\"connection\"] = app.managers[cluster_name]._client.state\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the children of a znode in a specific cluster
def cluster_znode_children(cluster_name, znode, headers=None): _zclient = get_client(cluster_name, headers or request.headers) zchildren = _zclient.get_children(znode) return make_response(str(zchildren), 200)
[ "def cluster_list_children(cluster_name, znode, headers=None):\n\n return cluster_znode_children(cluster_name,\n \"/\",\n headers=headers or request.headers)", "def get_children(cluster):\n if is_leaf(cluster):\n raise TypeError(\"a le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Closes the monochromator connection.
def closeinstance(self): if self.status != "not connected": m = self.serial m.close() result = "out.monochrom: Closed monochromator connection." return result else: pass
[ "def close_connection(self):\n try:\n ljm.close(self.connection_handle)\n except LJMError:\n pass", "async def close(self) -> None:\n\n # for conn_handle in self._conn_handles:\n # await agent.agent_close_connection(conn_handle)\n # self._conn_handles.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scans from start (nm) to end (nm) in steps of stepsize (nm). Sleeps for sleeptime seconds at each wavelength. Writes list of wavelengths to file filename
def scan(self, start, end, stepsize, sleeptime, filename='test.txt'): if self.status != "not connected": self.gowave(start) time.sleep(5) wave = start while wave <= end: time.sleep(sleeptime) self.gowave(wave + stepsize) ...
[ "def runWavelengthDependency():\n RunData([getFiles(mintime=(15, 39, 58), maxtime=(15, 47, 58), folder='data/30Jul/')[0],], out='I600nmwave',\n wavelength='l600')\n RunData([getFiles(mintime=(17, 48, 35), maxtime=(17, 56, 03), folder='data/30Jul/')[0],], out='I700nmwave',\n wavelength='l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens ('O') or closes ('C') the monochromator shutter.
def shutter(self, state): if self.status != "not connected": m = self.serial m.write("shutter " + str(state) + "\r\n") r = m.read(100) if state == 'O': st = "open" else: st = "closed" result = "out.monochrom:...
[ "def cehs():\n\tcloseEHShutter()", "def openShutter(self):\r\n\r\n if not self.qopenShutter():\r\n self.toggleShutter()", "def closeShutter(self):\r\n\r\n if self.qopenShutter():\r\n self.toggleShutter()", "def shclose():\n\tsh('c')", "def shutter(self, typ, mode, ext_clo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the authentication header.
def auth_header(self): return self._auth_header
[ "def get_auth_header(self):\n if not self.verify():\n return None\n\n auth_val = self.encode_auth_header_val()\n if not auth_val:\n return None\n\n return {'Authorization': auth_val.replace('\\n', '')}", "def get_auth_header(request):\n try:\n auth = req...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve blink parameters from login response.
def setup_params(self, response): self.login_url = self.login_handler.login_url ((self.region_id, self.region),) = response["region"].items() self._host = "{}.{}".format(self.region_id, BLINK_URL) self._token = response["authtoken"]["authtoken"] self._auth_header = {"Host": self....
[ "def get_login_credentials(self, responses):\n html = responses[0].body\n login_re = re.compile(r'var username1=\"(.*)\";')\n login = utils.re_first_capture(login_re, html)\n password_re = re.compile(r'var password1=\"(.*)\";')\n password = utils.re_first_capture(password_re, html...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve a camera list for each onboarded network.
def get_cameras(self): response = api.request_homescreen(self) try: all_cameras = {} for camera in response["cameras"]: camera_network = str(camera["network_id"]) camera_name = camera["name"] camera_id = camera["id"] ...
[ "def get_cameras(self):\n nCams = ctypes.c_int()\n self.call(\"is_GetNumberOfCameras\", ptr(nCams))\n nCams = nCams.value\n print(\"Found %d camera(s)\" % nCams)\n if nCams > 0:\n self._cam_list = create_camera_list(nCams)\n self.call(\"is_GetCameraList\", pt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge all sync camera dicts into one.
def merge_cameras(self): combined = CaseInsensitiveDict({}) for sync in self.sync: combined = merge_dicts(combined, self.sync[sync].cameras) return combined
[ "def update_camera_dict():\n global camera_dict\n camera_dict = r.hgetall(\"video_dict\")\n for i in camera_dict: \n tmp = camera_dict[i].decode(\"utf-8\")\n tmp = json.loads(tmp)\n if tmp['video_url'] == '0': \n tmp['video_url'] = 0\n camera_dict[i] = tmp", "def ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Samples new noise and stores it in `self.noise`.
def _sample_new_noise(self, *, tf_sess=None): if self.framework == "tf": tf_sess.run(self.tf_sample_new_noise_op) elif self.framework == "tf2": self._tf_sample_new_noise_op() else: for i in range(len(self.noise)): self.noise[i] = torch.normal( ...
[ "def noise(self, noise):\n\n self._noise = noise", "def add_noise(self, noise):\n if noise > 0.0:\n for key in self.counts:\n self.counts[key] *= 1.0 + noise * np.random.random_sample()", "def add_noise(self):\n self.noise = np.random.poisson(lam=self.lam, size=self.image.shape)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates tfop that assigns the stored noise to weights. Also used by tfeager.
def _tf_add_stored_noise_op(self): add_noise_ops = list() for var, noise in zip(self.model_variables, self.noise): add_noise_ops.append(tf1.assign_add(var, noise)) ret = tf.group(*tuple(add_noise_ops)) with tf1.control_dependencies([ret]): return tf.no_op()
[ "def _tf_remove_noise_op(self):\n remove_noise_ops = list()\n for var, noise in zip(self.model_variables, self.noise):\n remove_noise_ops.append(tf1.assign_add(var, -noise))\n ret = tf.group(*tuple(remove_noise_ops))\n with tf1.control_dependencies([ret]):\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the current action noise from the model parameters.
def _remove_noise(self, *, tf_sess=None): # Make sure we only remove noise iff currently noisy. assert self.weights_are_currently_noisy is True # Removes the stored noise from the model's parameters. if self.framework == "tf": tf_sess.run(self.tf_remove_noise_op) eli...
[ "def reset_noise(self):\n self.advantage_hidden_layer.reset_noise()\n self.advantage_layer.reset_noise()\n self.value_hidden_layer.reset_noise()\n self.value_layer.reset_noise()", "def _tf_remove_noise_op(self):\n remove_noise_ops = list()\n for var, noise in zip(self.mod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a tfop for removing noise from the model's weights. Also used by tfeager.
def _tf_remove_noise_op(self): remove_noise_ops = list() for var, noise in zip(self.model_variables, self.noise): remove_noise_ops.append(tf1.assign_add(var, -noise)) ret = tf.group(*tuple(remove_noise_ops)) with tf1.control_dependencies([ret]): return tf.no_op()
[ "def _remove_noise(self, *, tf_sess=None):\n # Make sure we only remove noise iff currently noisy.\n assert self.weights_are_currently_noisy is True\n\n # Removes the stored noise from the model's parameters.\n if self.framework == \"tf\":\n tf_sess.run(self.tf_remove_noise_op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform the call on the pointer in a request to evaluate the remote plan
def __call__(self, *args, **kwargs): result_ids = [sy.ID_PROVIDER.pop()] response = self.request_execute_plan(self.location, result_ids, *args) return response
[ "def test_execute_plan_remotely(hook, start_remote_worker):\n\n @sy.func2plan(args_shape=[(1,)])\n def my_plan(data):\n x = data * 2\n y = (x - 2) * 10\n return x + y\n\n x = th.tensor([-1, 2, 3])\n local_res = my_plan(x)\n\n server, remote_proxy = start_remote_worker(id=\"test_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Requests plan execution. Send a request to execute the plan on the remote location.
def request_execute_plan( self, location: "sy.workers.BaseWorker", response_ids: List[Union[str, int]], *args, **kwargs, ) -> object: plan_name = f"plan{self.id}" # args, _, _ = hook_args.unwrap_args_from_function( # plan_name, args, {} # )...
[ "def request_execute_plan(\n self,\n location: \"sy.workers.BaseWorker\",\n response_ids: List[Union[str, int]],\n *args,\n **kwargs,\n ) -> object:\n args = [args, response_ids]\n command = (\"execute_plan\", self.ptr_plans[location.id], args, kwargs)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is an alias to fetch_plan, to behave like a pointer
def get(self, deregister_ptr: bool = True): copy = not deregister_ptr plan = self.owner.fetch_plan(self.id_at_location, self.location, copy=copy) return plan
[ "def plan(self) -> global___Plan:", "def get_plan(self, sql, types):\r\n\r\n t = (sql, tuple(types))\r\n if t in self.plan_map:\r\n pc = self.plan_map[t]\r\n # put to the end\r\n self.plan_list.remove(pc)\r\n self.plan_list.append(pc)\r\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse params config from json file
def parse_json(params_path): with open (params_path) as f: params = json.load(f) return params
[ "def load_params(filename):\n with open(filename) as f:\n content = ''.join(f.readlines())\n #print content\n return json.loads(content)", "def load_params_from_file(self, fn):\n f = file(fn, 'r')\n params = json.load(f)\n return params", "def parse_json_confing(config_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse HTML fragments from the given HTML fragment string.
def parse_fragments(html_string, safe_tags=None, safe_attrs=None): for f in html.fragments_fromstring(html_string): cf = clean_fragment(f, safe_tags=safe_tags, safe_attrs=safe_attrs) if cf is not None: yield cf
[ "def parse(html):\n\n return BeautifulSoup(html, 'html.parser')", "def parse_html(html: str, parser: FragmentParser = None) -> Node:\n parser = parser or FragmentParser()\n parser.feed(html)\n return parser.root", "def parse(html, encoding='utf-8'):\n if isinstance(html, unicode):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clean an HTML fragment subtree of unsafe tags and attrs.
def clean_fragment(subtree, safe_tags=None, safe_attrs=None): if isinstance(subtree, str): return E('p', subtree) if safe_tags is None: safe_tags = default_safe_tags if safe_attrs is None: safe_attrs = default_safe_attrs if subtree.tag not in safe_tags: if callable(subt...
[ "def clean_html(input):\n p = HTMLParser(tree=treebuilders.getTreeBuilder(\"dom\"))\n dom_tree = p.parseFragment(input)\n walker = treewalkers.getTreeWalker(\"dom\")\n stream = walker(dom_tree)\n\n s = HTMLSerializer(omit_optional_tags=False)\n return \"\".join(s.serialize(stream))", "def saniti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds API requests to construct Target VPN Gateways.
def CreateRequests(self, args): target_vpn_gateway_ref = self.TARGET_VPN_GATEWAY_ARG.ResolveAsResource( args, self.resources, scope_lister=compute_flags.GetDefaultScopeLister(self.compute_client, self.project)) network_ref = self....
[ "def create_gateway(env, netUrl, loc, type, index, token, **kargs):\n # Create AWS GW(s)\n url = 'https://gateway.' + env + '.netfoundry.io/rest/v1/dataCenters'\n # find dc id based on location code\n datacenters = nfreq(url, \"get\", token)['_embedded']['dataCenters']\n dcId = None\n for dc in da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the sum of the first n positive integer numbers.
def integer_sum(n): sum = 0 k = 0 # INVARIANT # The sum of far is equal to the sum of the first k integer numbers # VARIANT: n-k # while (k!=n): k += 1 sum += k return sum
[ "def sumOfFirstNIntegers(x,n):\n if(n <= 0):\n return n \n\n return n + sumOfFirstNIntegers(x, n-1)", "def sum_of_nth( n ):\n if n > 0:\n return sum( range(n + 1) )\n else:\n return 0", "def sum_to(n):\n ss = 0\n for v in range(n + 1):\n ss = ss + v\n return ss", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a vendored and modified version of the Django create_sql method We do this so that we can monkey patch in the unique index statement onto the schema_editor while we create the statement for this index, and then revert it to normal. We should remove this as soon as Django natively supports UniqueConstraints with...
def create_sql(self, model, schema_editor, using='', **kwargs): include = [model._meta.get_field(field_name).column for field_name in self.include] condition = self._get_condition_sql(model, schema_editor) if self.expressions: index_expressions = [] for expression in self...
[ "def apply_patch():\n assert BaseDatabaseSchemaEditor is not None\n\n def _create_unique_sql(self, *args, **kwargs):\n from django.db.backends.ddl_references import IndexName\n\n statement = orig_create_unique_sql(self, *args, **kwargs)\n\n if statement is not None:\n index_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use this method when we want to recover a user.
def recover(self): self.deleted = False self.save() self.history.create(user_id=self.pk, action=user_history.RECOVERY)
[ "def recover_password(self):\n\n if \"login\" not in self.params and \"recovery_code\" not in self.params:\n return html.login.recover_password\n\n if \"recovery_code\" not in self.params:\n user = mdb.users.find_one({\"login\": self.params[\"login\"].value.lower().strip()})\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hard delete all user related data. But keeps the user record itself intact.
def hard_delete_user_related_data(self): from contentcuration.viewsets.common import SQCount # Hard delete invitations associated to this account. self.sent_to.all().delete() self.sent_by.all().delete() editable_channels_user_query = ( User.objects.filter(editable_c...
[ "def db_delete_user_data(self):\n util.log(\"Clearing all user data\", util.LogLevel.Info)\n self.db.db_clear_data_user()\n util.log(\"Done\", util.LogLevel.Info)", "def delete_user(self):\n User.user_details.remove(self)", "def delete_all_users(self):\n\n User.query.delete()"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a storage URL for the given content filename.
def generate_storage_url(filename, request=None, *args): path = generate_object_storage_name(os.path.splitext(filename)[0], filename) # There are three scenarios where Studio might be run as: # # 1. In normal kubernetes, nginx will proxy for us. We'll know we're in kubernetes when the # environmen...
[ "def create_url(filename):\n # remove slashes to avoid double slashes in the URL\n # keep the first slash in the MEDIA_URL\n media_url = django_settings.MEDIA_URL.rstrip('/')\n gallery_path = settings.CONF['path'].strip('/')\n return '/'.join([media_url, gallery_path, filename])", "def url_for(file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a primary secret token for the current channel using a proquint string. Creates a secondary token containing the channel id. These tokens can be used to refer to the channel to download its content database.
def generate_new_token(cls): token = proquint.generate() # Try 100 times to generate a unique token. TRIALS = 100 for __ in range(TRIALS): token = proquint.generate() if SecretToken.exists(token): continue break # after TRIALS ...
[ "def CreateChannelToken(self):\n logging.info(\"Create channel: \" + self.user)\n return channel.create_channel(self.user)", "def create_token():\n credentialManager.delete('token')\n Git()", "def assign_new_token():\n\n\tfrom hashlib import sha256\n\n\tapi_token = server.request.headers.get('X-API-...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the current channel object to be public and viewable by anyone. If bypass_signals is True, update the model in such a way that we prevent any model signals from running due to the update. Returns the same channel object.
def make_public(self, bypass_signals=False): if bypass_signals: self.public = True # set this attribute still, so the object will be updated Channel.objects.filter(id=self.id).update(public=True) # clear the channel cache delete_public_channel_cache_keys() ...
[ "async def open_private_channel(self) -> 'dt_channel.Channel':\n if self.discriminator == \"0000\":\n raise CuriousError(\"Cannot open a private channel with a webhook\")\n\n # First, try and access the channel from the channel cache.\n original_channel = self._bot.state.find_channel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all public channels. If defer_nonmain_trees is True, defer the loading of all trees except for the main_tree.
def get_public_channels(cls, defer_nonmain_trees=False): if defer_nonmain_trees: c = (Channel.objects .filter(public=True) .exclude(deleted=True) .select_related('main_tree') .prefetch_related('editors') .defer('tra...
[ "def get_channels():\n all_channels = channels\n emit(\"channels_all\", all_channels)", "def download_public_channels(slack, outdir):\n for channel in slack.channels():\n if channel['is_member']:\n history = slack.channel_history(channel=channel)\n path = os.path.join(outdir,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prunes history records by keeping the most recent actions for each channel and type, and deleting all other older actions
def prune(cls): keep_ids = cls.objects.distinct("channel_id", "action").order_by("channel_id", "action", "-performed").values_list("id", flat=True) cls.objects.exclude(id__in=keep_ids).delete()
[ "def prune(self):\n \n # Compute the oldest timestamp allowed.\n max_history = float(self.config['max_history'])\n now = datetime.datetime.now()\n delta = datetime.timedelta(seconds=max_history)\n oldest = now - delta\n\n self.logger.debug('Removing older than {}s (i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When `settings.IS_CONTENTNODE_TABLE_PARTITIONED` is `False`, this always returns a queryset filtered by pk. When `settings.IS_CONTENTNODE_TABLE_PARTITIONED` is `True` and a ContentNode for `pk` exists, this returns a queryset filtered by `pk` AND `tree_id`. If a ContentNode does not exist for `pk` then an empty queryse...
def filter_by_pk(cls, pk): query = ContentNode.objects.filter(pk=pk) if settings.IS_CONTENTNODE_TABLE_PARTITIONED is True: tree_id = cache.get(CONTENTNODE_TREE_ID_CACHE_KEY.format(pk=pk)) if tree_id: query = query.filter(tree_id=tree_id) else: ...
[ "def get_queryset(self):\n qs = super(CollectionItemDocument, self).get_queryset()\n\n # qs = qs.select_related('period_node').prefetch_related('images')\n\n filters = []\n for field in ['title']:\n for language in ['en', 'nl']:\n filters.extend(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all ContentNodes with a given title. If limit_to_children_of is passed in with an id, only look at all the children of the node with that id.
def get_nodes_with_title(cls, title, limit_to_children_of=None): if limit_to_children_of: root = cls.objects.get(id=limit_to_children_of) return root.get_descendants().filter(title=title) return cls.objects.filter(title=title)
[ "def get_matching_titles(title: str, children: list) -> List[int]:\n return get_index_where(lambda x: getattr(x, \"title\", None) == title, children)", "def get_children(self, cont: typing.Union[str, Type(None)]) -> List[str]:\n s = requests.Session()\n\n url = \"https://en.wikipedia.org/w/api.ph...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If self is NOT an original contentnode (in other words, a copied contentnode) and a contentnode with same content_id exists then we update self's content_id.
def make_content_id_unique(self): is_node_original = self.original_source_node_id is None or self.original_source_node_id == self.node_id node_same_content_id = ContentNode.objects.exclude(pk=self.pk).filter(content_id=self.content_id) if (not is_node_original) and node_same_content_id.exists():...
[ "def update_contentnode_content_id(self):\n if self.contentnode and self.preset.thumbnail is False:\n self.contentnode.make_content_id_unique()", "def on_update(self):\n self.contentnode.make_content_id_unique()", "def updateUniqueId(self, node):\n node.setUniqueId(True)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Guess the format preset of a filename based on its extension. Return None if format is unknown.
def guess_format_preset(cls, filename): _, ext = os.path.splitext(filename) ext = ext.lstrip(".") f = FormatPreset.objects.filter( allowed_formats__extension=ext, display=True ) return f.first()
[ "def _infer_file_format(\n file_format: Optional[str], filename: str\n) -> Optional[str]:\n if file_format is not None:\n return file_format\n suffix = epath.Path(filename).suffix\n if suffix.startswith('.'):\n return suffix[1:]\n return None", "def get_file_format(path):\n\n for ext in EXTENSION_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the FormatPreset object with that exact name. Returns None if that format preset is not found.
def get_preset(cls, preset_name): try: return FormatPreset.objects.get(id=preset_name) except FormatPreset.DoesNotExist: return None
[ "def scheming_get_preset(preset_name):\n schemas = scheming_get_presets()\n if schemas:\n return schemas.get(preset_name)", "def guess_format_preset(cls, filename):\n\n _, ext = os.path.splitext(filename)\n ext = ext.lstrip(\".\")\n f = FormatPreset.objects.filter(\n a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When an exercise is updated of a contentnode, update its content_id if it's a copied contentnode.
def on_update(self): self.contentnode.make_content_id_unique()
[ "def update_contentnode_content_id(self):\n if self.contentnode and self.preset.thumbnail is False:\n self.contentnode.make_content_id_unique()", "def make_content_id_unique(self):\n is_node_original = self.original_source_node_id is None or self.original_source_node_id == self.node_id\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When an exercise is deleted from a contentnode, update its content_id if it's a copied contentnode.
def delete(self, *args, **kwargs): self.contentnode.make_content_id_unique() return super(AssessmentItem, self).delete(*args, **kwargs)
[ "def update_contentnode_content_id(self):\n if self.contentnode and self.preset.thumbnail is False:\n self.contentnode.make_content_id_unique()", "def on_update(self):\n self.contentnode.make_content_id_unique()", "def test_delete_part():\n content_parts = ContentPartRepository(DB)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns just the filename of the File in storage, without the path e.g. abcd.mp4
def filename(self): # TODO(aron): write tests for this return os.path.basename(self.file_on_disk.name)
[ "def get_file_name(self):\n return str(self.get_file())", "def get_name(self):\n if self.file_path is None:\n return \"Noname\"\n\n file_name = os.path.basename(self.file_path)\n return file_name", "def filename(self):\n filename, ext = os.path.splitext(self.file.na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the file is attached to a contentnode and is not a thumbnail then update that contentnode's content_id if it's a copied contentnode.
def update_contentnode_content_id(self): if self.contentnode and self.preset.thumbnail is False: self.contentnode.make_content_id_unique()
[ "def make_content_id_unique(self):\n is_node_original = self.original_source_node_id is None or self.original_source_node_id == self.node_id\n node_same_content_id = ContentNode.objects.exclude(pk=self.pk).filter(content_id=self.content_id)\n if (not is_node_original) and node_same_content_id.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }