query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Read the file to look for new entries
def _read_new_entries(self, is_first_read: bool) -> bool: new_text = self.watched_file.read() if new_text: for entry_txt in new_text.split("\n"): if entry_txt: self._register_entry(entry_txt, is_first_read) return len(new_text) > 0
[ "def _read_existing(self):\n\n print(\"Reading file entries of previously created csv file...\")\n with open(self._output_file, 'r', encoding='utf-16') as previous_file:\n # Dismiss the csv header row\n next(previous_file)\n\n for line in previous_file:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs all the tasks, watching for file update and running timed events (blocking) Stops on KeyboardInterrupts
def run(self): while True: try: if not self._read_new_entries(False): time.sleep(0.1) self._update_all_tasks() except KeyboardInterrupt: break
[ "def run_inner(self):\n for event in self.inotify.event_gen():\n self.process_inotify_event(event)", "def run_forever(self):\n try:\n while True:\n # blocking untill a task comes available\n # timeout specified, else Keyboard interupts are ignored\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
4.1.5 [PATCH] //learningstore/gls/resource/delete/library/{id}/ 收藏夹删除或恢复
def patch_mylibrary_id_deleted(self, id, delete): url = "/learning-store/gls/resource/delete/library/" + id self.http_obj.set_header(self.header) res = self.http_obj.patch(url, "") return res
[ "def delete_mylibrary_id(self, id):\n\n # url = \"/learning-store/gls/resource/delete/library/\" + id\n url = \"/learning-store/gls/collections/\" + id\n self.http_obj.set_header(self.header)\n res = self.http_obj.delete(url)\n return res", "def delete_library(self, library_id):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
4.3 [DELETE] //learningstore/gls/resource/delete/library/{id}/ 收藏夹删除 /gls/collections/{collection_id} 删除的是collection
def delete_mylibrary_id(self, id): # url = "/learning-store/gls/resource/delete/library/" + id url = "/learning-store/gls/collections/" + id self.http_obj.set_header(self.header) res = self.http_obj.delete(url) return res
[ "def delete_collection(request, collection_id):\n collection = PanelsCollection.objects.get(id=collection_id)\n collection.delete()\n\n # refer to a collection by its title in messaging\n messages.warning(request, f'Collection: (\"{collection.title}\") was successfully deleted!' )\n return redirect('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
4.10. 统计某个用户my library中资源个数 GET
def get_resourceid_count(self, userId): url = "/learning-store/gls/users/" + userId + "/resources/count" self.http_obj.set_header(self.header) res = self.http_obj.get(url) return res
[ "def count(cls, client) :\n try :\n obj = nshttpprofile()\n option_ = options()\n option_.count = True\n response = obj.get_resources(client, option_)\n if response :\n return response[0].__dict__['___count']\n return 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
默认type=single 4.13 [post] /gls/resources/{resource_id}/reviews
def post_resource_reviews(self, resource_id, userId, userName): url = "/learning-store/gls/resources/" + str(resource_id) + "/reviews" params = { "userId": userId, "userName": userName } params = json.dumps(params) self.http_obj.set_header(self.header) ...
[ "def post_resource_reviews_v1_04(self, resource_id, userId, userName):\n url = \"/learning-store/gls/resources/\" + str(resource_id) + \"/reviews?type=multiple\"\n params = {\n \"userId\": userId,\n \"userName\": userName,\n \"avgItems\":\n [{\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
4.15 [put] /gls/resources/reviews/{id} 修改评论
def put_user_review_of_a_resource(self, id, resource_id, rating, userId): content = "修改评论评价语" url = "/learning-store/gls/resources/reviews/" + id + '?resource_id=' + resource_id params = {"content": content, "rating": rating, "userId": userId, ...
[ "def put_user_review_of_a_resource_v1(self, id, resource_id, rating, userId):\n content = \"修改评论评价语\"\n url = \"/learning-store/gls/resources/reviews/\" + id + '?type=multiple&resource_id=' + resource_id\n params = {\n \"content\": \"this is very good resource ,I like it ,thank you f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
改造接口 type=multiple 4.13 [post] /gls/resources/{resource_id}/reviews
def post_resource_reviews_v1_02(self, resource_id, userId, userName): url = "/learning-store/gls/resources/" + str(resource_id) + "/reviews?type=multiple" params = { "userId": userId, "userName": userName, "avgItems": [{ "code": "ea...
[ "def post_resource_reviews_v1_04(self, resource_id, userId, userName):\n url = \"/learning-store/gls/resources/\" + str(resource_id) + \"/reviews?type=multiple\"\n params = {\n \"userId\": userId,\n \"userName\": userName,\n \"avgItems\":\n [{\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
改造接口 type=multiple 4.13 [post] /gls/resources/{resource_id}/reviews
def post_resource_reviews_v1_04(self, resource_id, userId, userName): url = "/learning-store/gls/resources/" + str(resource_id) + "/reviews?type=multiple" params = { "userId": userId, "userName": userName, "avgItems": [{ "code": "ov...
[ "def post_resource_reviews_v1_02(self, resource_id, userId, userName):\n url = \"/learning-store/gls/resources/\" + str(resource_id) + \"/reviews?type=multiple\"\n params = {\n \"userId\": userId,\n \"userName\": userName,\n \"avgItems\":\n [{\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
改造接口 type=multiple 4.15 [put] /gls/resources/reviews/{id} 修改评论
def put_user_review_of_a_resource_v1(self, id, resource_id, rating, userId): content = "修改评论评价语" url = "/learning-store/gls/resources/reviews/" + id + '?type=multiple&resource_id=' + resource_id params = { "content": "this is very good resource ,I like it ,thank you for suporting" + ...
[ "def put_user_review_of_a_resource(self, id, resource_id, rating, userId):\n content = \"修改评论评价语\"\n url = \"/learning-store/gls/resources/reviews/\" + id + '?resource_id=' + resource_id\n params = {\"content\": content,\n \"rating\": rating,\n \"userId\": user...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
改造接口 type=multiple 4.16 [GET] /gls/users/{user_id}/resources/{resource_id}/reviews
def get_user_review_v1(self, user_id, resource_id): url = "/learning-store/gls/users/" + user_id + "/resources/" + resource_id + "/reviews?type=multiple" self.http_obj.set_header(self.header) res = self.http_obj.get(url) return res
[ "def post_resource_reviews_v1_02(self, resource_id, userId, userName):\n url = \"/learning-store/gls/resources/\" + str(resource_id) + \"/reviews?type=multiple\"\n params = {\n \"userId\": userId,\n \"userName\": userName,\n \"avgItems\":\n [{\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
改造接口 type=multiple 4.17 [get] /gls/resources/{resource_id}/reviews?offset={offset}&limit={limit}
def get_user_review_of_specific_resource_v1(self, resource_id, offset, limit): url = "/learning-store/gls/resources/" + resource_id + "/reviews?offset=" + offset + "&limit=" + limit self.http_obj.set_header(self.header) res = self.http_obj.get(url) return res
[ "def fetch_reviews(self, rb_id, start=0, max_results=25):\r\n return self.api_call('/api/review-requests/%s/reviews/?start=%s&max-results=%s'\r\n % (rb_id, start, max_results))['reviews']", "def reviews(self, **kwargs):\n\n path = self._get_movie_id_path('reviews')\n resp ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
改造接口 type=multiple 4.18 [get] /gls/resources/{resource_id}/ratings/number
def get_number_of_rating_v1(self, resource_id): url = "/learning-store/gls/resources/" + resource_id + "/ratings/number?type=multiple" self.http_obj.set_header(self.header) res = self.http_obj.get(url) return res
[ "def review_rating(review):\n return review[1]", "def get_ratings(self):\n return self.ratings", "def api_ratings ():\n\n session = core.Session()\n\n try:\n course_id = flask.request.args.get('course_id')\n\n # Load the course (to check that it exists) and the ratings\n cou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A plugin for healpix probability maps. Allows for joint fitting of positions on the sky. Coordinate system is assumed to be Celestial. this can be changed in the future.
def __init__(self, name, healpix_map, coord='C'): assert coord.upper() in _allowed_coords, 'coord must be G or C' self._coord = coord.upper() self._map = healpix_map # the map should be filled with probabilities # and we will be using the log of them. Let's # go ahead...
[ "def bndy_plasma(self):\n self.ne[0], self.ne[-1] = 1e11, 1e11\n self.ni[0], self.ni[-1] = 1e11, 1e11\n self.nn[0], self.nn[-1] = 1e11, 1e11\n self.Te[0], self.Te[-1] = 0.1, 0.1\n self.Ti[0], self.Ti[-1] = 0.01, 0.01\n # self.coll_em[0], self.coll_em[-1] = 1e5, 1e5\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the likelihood model for the plugin
def set_model(self, model): # attach the model to the object self._likelihood_model = model # the position for the point source is freed for key in self._likelihood_model.point_sources.keys(): self._likelihood_model.point_sources[key].position.ra.free = True sel...
[ "def set_model(self, likelihood_model_instance):\n pass", "def set_likelihood(self):\n\n likelihoodkwargs = self.roq_kwargs.copy()\n likelihoodkwargs[\"usetempo2\"] = self.usetempo2\n\n self.likelihood = TargetedPulsarLikelihood(\n data=self.hetdata,\n priors=self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a HEALPixMapLike from a file name
def from_healpix_file(cls, name, filename, coord='C', **kwargs): hp_map = hp.read_map(filename, **kwargs) return cls(name, hp_map, coord=coord)
[ "def create_image_from_fits_file(fname):\n hdulist = pf.open(fname)\n return create_image_from_hdulist(hdulist)", "def hershey_load(glyph_file_name, map_file_name=None):\n glyphs = {}\n font = []\n width = 40\n height = 45\n first = 32\n last = 127\n\n # Read the glyphs file\n with o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluates the dialogue created by the model. First we load the user goal of the dialogue, then for each turn generated by the system we look for keywords. For the Inform rate we look whether the entity was proposed. For the Success rate we look for requestables slots
def _evaluateGeneratedDialogue( self, dialog, goal, real_requestables, counts, soft_acc=False, same_eval_as_cambridge=False ): # for computing corpus success #'id' requestables = self.requestables # CHECK IF MATCH HAPPENED provided_requestables = {} venue_off...
[ "def _evaluateGeneratedDialogue(self, dialog, goal, realDialogue, real_requestables, soft_acc=False):\n\n random.seed(0)\n\n # for computing corpus success\n requestables = ['phone', 'address', 'postcode', 'reference', 'id']\n\n # CHECK IF MATCH HAPPENED\n provided_requestables = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses user goal into dictionary format.
def _parseGoal(self, goal, true_goal, domain): goal[domain] = {} goal[domain] = {'informable': {}, 'requestable': [], 'booking': []} if 'info' in true_goal[domain]: if domain == 'train': # we consider dialogues only where train had to be booked! if 'bo...
[ "def _parseGoal(self, goal, true_goal, domain):\n goal[domain] = {}\n goal[domain] = {'informable': {}, 'requestable': [], 'booking': []}\n if 'info' in true_goal[domain]:\n if domain == 'train':\n # we consider dialogues only where train had to be booked!\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to figure out alphabet of a particular number
def get_alphabet(number): return chr(number + 96)
[ "def letter_num(num: int):\n if abs(num) > 26 or num == 0:\n let = ord('a') + 26 - 1\n else:\n let = ord('a') + abs(num) - 1\n return chr(let)", "def alphabetic_value(name):\n return sum([ord(x) - 64 for x in name])", "def prefer_alphabet(i):\n if 0 <= i <= 25:\n return chr(i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check devices category having the ID_INPUT_TOUCHSCREEN property
def _test_DELL_INSPIRON3521_TOUCHSCREEN(self): devices = self.parse("DELL_INSPIRON3521_TOUCHSCREEN") self.assertEqual(len(devices), 59) # Check the Accelerometer device category/product self.assertEqual(devices[36].category, "TOUCHSCREEN") self.assertEqual(devices[36].product, "E...
[ "def _find_devices_win(self):\n self._find_xinput()\n self._detect_gamepads()\n self._count_devices()\n if self._raw_device_counts['keyboards'] > 0:\n self.keyboards.append(Keyboard(\n self,\n \"/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd\"))\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify we have exactly one of each device given in the list, and that product name, category, bus, vendor_id and product_id match. The list contains a tuple with product name, category, bus, vendor and product.
def verify_devices(self, devices, expected_device_list): # See this bug, that prompted for closer inspection of # devices and IDs: # https://bugs.launchpad.net/checkbox/+bug/1211521 for device in expected_device_list: # Match by product and vendor ID indices = [id...
[ "def _check_dev_type(devices, dev_list):\n\n if devices is not None:\n for device in devices:\n if device in dev_list: # List element is one of the available devices.\n continue\n else:\n raise RuntimeError(\"At least one of the specified devices is not...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return binary classification tracks.
def load_binary_clf_tracks() -> typing.List[Track]: return [ Track( name="Phishing", dataset=datasets.Phishing(), metric=metrics.Accuracy() + metrics.F1(), ), Track( name="Bananas", dataset=datasets.Bananas(), metric=me...
[ "def get_tracks(self):\n raise NotImplementedError", "def _get_tracks(self):\n raise NotImplementedError", "def tracks(self):\n if self._tracks is None:\n self._tracks = self._get_tracks()\n return self._tracks", "def get_tracks(num=1):\n pass", "def tracks(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retrieve a list from the datastore. If none found, fall through to content/lists dir.
def get_list(self): list_id = self.request.path[1:] if len(list_id) <= 0: list_id = INDEX_LIST_ID lst = List.gql("where id=:1", list_id).get() if lst is not None: q = Page.all() q.filter('list_id =', list_id) if not users.is_current_user_ad...
[ "def get(self, id: int = None, order_by: models.OrderBy = None, order_dir: models.OrderDir = None):\n order_dir = order_dir.value if order_dir else None\n order_by = order_by.value if order_by else None\n\n if not id:\n resp = self.api.get('lists', {'order_by': order_by, 'order_dir':...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate a urlsafe string for a given headline
def get_slug(self, headline): exclude = set(string.punctuation) s = ''.join(ch for ch in headline if ch not in exclude) return s.lower().replace(" ", "-")
[ "def header_link(title):\n # This doesn't handle multiple titles with the same text in the\n # same file, but usually that's not a problem. GitHub makes\n # links like the-title, the-title-1, the-title-2 etc.\n result = ''\n for character in title:\n if character in string.whitespace:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate a page object from an entry dict (usu originating in yaml)
def get_page_from_entry(self, entry): page = Page() if '_uri' not in entry or entry['_uri'] is None: prefix = '' if '_list_id' not in entry or entry['_list_id'] is None else ('/' + entry['_list_id']) entry['_uri'] = prefix + "/" + self.get_slug(entry['_headline']) page.lo...
[ "def create(dictionary, modelManager = None):\n page = Page()\n page._modelManager = modelManager\n\n #the following keys will have a special handling so we must overwrite the values by the following conditions\n\n if 'space' in dictionary:\n page.space = Space.Space()\n page.space.key = d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the genes table and reads the genes from the file fn_genes File with the information for the Genes
def create_genes_table(self, fn_genes): log.info("Creating table with information about the genes ...") gene_record = GeneParser.GeneRecord() names = gene_record.fields_names types = gene_record.fields_types if len(names) != len(types): raise ValueError, "The number o...
[ "def genes_file_creation(input_folder):\n file_paths = {}\n for file_name in os.listdir(input_folder):\n file_paths[file_name] = input_folder + '/' + file_name\n\n df = pa.DataFrame()\n \n for file_name in file_paths:\n df_temp = pa.read_csv(file_paths[file_name], sep='\\t', hea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store a set of BLAST results in the database Results_list A list of pairs (identifier, blast results). The identifier is the gene id. Blast results is an istance of BlastResult.
def store_blast_results(self, results_list): data = [] for gene_id, r in results_list: data.append([gene_id] + r.get_formatted_for_db()) self.store_data(self.BlastResultsTable, data)
[ "def insert_blast_results(all_shards, args, state, log):\n with db.connect(state['blast_db']) as cxn:\n db.aux_db(\n cxn,\n args['temp_dir'],\n state['blast_db'],\n state['query_target'])\n\n for shard in all_shards:\n shard = basename(shard)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the table to store the scaffold assigments
def create_scaffold_assignments_table(self): log.info("Creating table to store Scaffold genus assignments ...") self.create_table(self.ScaffoldsAssignmentsTable ,self.ScaffoldAssignmentsFields, self.ScaffoldAssignmentsTypes)
[ "def create_table(self):\n pass", "def create_table(self):\n return None", "def create_tables():\n db.create_all()", "def __create_presentations_table(self, schema=PRESENTATIONS_SCHEMA_310):\r\n log.info(\"table created\")\r\n QtSql.QSqlQuery(schema)", "def create_book_lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates and fills a table with the sequences of the scaffols fn_scaffolds A file in FASTA format with the sequences of all the Scaffolds
def fill_scaffolds_table(self,fn_scaffolds, overwrite=True): scaffold_record_pattern = re.compile("(.+?)\s+(.+?)\s+(.+)") tables_names = self.get_tables_names() log.info("Creating and filling table of scaffolds ...") if overwrite and self.ScaffoldsTable in tables_names: self....
[ "def createScaffoldAbundanceProfiles(scaffFilePath, scaffPred, profilesDir, databaseFile, taxonomicRanks, minScaffLen):\n seqIdToBp = fas.getSequenceToBpDict(scaffFilePath)\n seqIdToTaxonId = csv.predToDict(scaffPred)\n taxonomy = Taxonomy(databaseFile, taxonomicRanks)\n errorIdToCount = {}\n entryLi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the coverage values to the table containing the Scaffolds fn file with the coverage information. It is expected to be a csv file with the first column naming the scaffold and the second one containing the coverage. The firs line of the file (the title) is discarded
def add_scaffold_coverage(self, fn): if not self.table_exists(self.ScaffoldsTable): raise ValueError("Cannot add scaffold coverage. The table with the scaffolds does "\ "not exist") cnames = self.get_table_column_names(self.ScaffoldsTable) if not "coverage" in cnames:...
[ "def get_project_test_coverage(self) -> None:\n print_statistics = {}\n total_number_columns = 0\n number_columns_without_tests = 0\n\n for model_name in self.dbt_tests.keys():\n columns = self.dbt_tests[model_name]\n\n model_number_columns = 0\n model_co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Puts all the scaffolds assigned to a genus together and retunrs a dictionary of sequences. The function reads the database to recover the genus given each of the assigned scaffolds. Scaffolds having the same genus are concatenated. The concatenated frankenstein sequences can be used to calculate kmer signatures for eac...
def get_genera_sequences_from(self, table): log.info("Joining the sequences of all the scaffolds with the same genus") if not self.table_exists(table): raise ValueError("The database does not have table {0}".format(table)) # Get all the scaffolds assigned sql_command = """SEL...
[ "def fill_scaffolds_table(self,fn_scaffolds, overwrite=True):\n scaffold_record_pattern = re.compile(\"(.+?)\\s+(.+?)\\s+(.+)\")\n tables_names = self.get_tables_names()\n log.info(\"Creating and filling table of scaffolds ...\")\n if overwrite and self.ScaffoldsTable in tables_names:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the kmer spectrums for the scaffolds The sequences of the scaffolds are read from the database and their spectrums are stored as a new column k The size of the kmers
def add_scaffold_spectrums(self,kmer_size): log.debug("Adding a column with the k-mer spectrums to the scaffolds table") if not self.table_exists(self.ScaffoldsTable): raise ValueError("Cannot add k-mer spectrums. Scaffolds table does not exist") if not "spectrum" in self.get_table_...
[ "def get_kf_kms(self):\n kfkms = np.array([ self.kf / (ss.velfac * 3.085678e24/ss.units.UnitLength_in_cm) for ss in self.spectrae])\n return kfkms", "def codonfreqs_kmerdf(kmertable): \n codon_counts_kmer = np.zeros(( len(codons_nonstop) ))\n for kmer in kmertable['kmer']:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the alarm target is the cloudwatch forwarder
def is_health_monitor_alarm(alarm): is_health_alarm = False if len(alarm["OKActions"]) > 0: action = alarm["OKActions"][0] is_health_alarm = "cloudwatch_forwarder" in action return is_health_alarm
[ "def is_alarm():\n return _alarm", "def checkUpstreamScheduler():", "def _isalarm(self):\n return self.dp.state()==PyTango.DevState.ALARM", "def schedule_cloudwatch_event(event):\n try:\n source = event[\"source\"]\n detail_type = event[\"detail-type\"]\n\n return source == \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set state of all configured alarms to the state value
def reset_all_alarm_states(state): valid_states = ["OK", "ALARM"] if state in valid_states: for region in REGIONS: alarms = get_alarms(region) for alarm in alarms: alarm_name = alarm["AlarmName"] is_health_alarm = is_health_monitor_alarm(alarm) ...
[ "def set_alarm_state(AlarmName=None, StateValue=None, StateReason=None, StateReasonData=None):\n pass", "async def set_armed_state(self, state: int) -> None:\n _LOGGER.debug(f\"setting {self.name} to {ArmedState(state).name}\")\n await self.vivintskyapi.set_alarm_state(self.id, self.partition_id,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the state value associated with a list of tf.Variables. This state is commonly going to be a NamedTuple that contains some mapping between variables and the state associated with those variables. This state could be a moving momentum variable tracked by the optimizer.
def get_state(self, var_list): raise NotImplementedError()
[ "def get_state_variable_names(self):\n svnames = self._L2run.state_vector.state_vector_name\n return svnames", "def vars(self):\n return [Var(i,self.dims[i]) for i in range(self.nvar)] # TODO: use stored state info (=1 sometimes)", "def variables(self):\n return (\n tf.nest.pack_sequ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of the NNCF operations which were added to the NNCF network.
def nncf_operations(self) -> List[NNCFOperation]: return [op for hook in getattr(self, "_hooks") for op in hook.operations]
[ "def operations(self):\r\n return self._operations_list", "def operation_list(self):\n return self._operation_modes", "def get_operations(self):\n raise NotImplementedError(\n 'operation get_operations(...) not yet implemented')", "def get_all_operations(self):\n raise N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns input signature of the model.
def input_signature(self) -> InputSignature: return self._input_signature
[ "def input_signature(self):\n return self._function_spec.input_signature", "def structured_input_signature(self):\n return self._func_graph.structured_input_signature", "def input_signature(self):\n return _my_preamble_pilot_swig.my_preamble_detector_sptr_input_signature(self)", "def input_signat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls the model on new inputs and returns the outputs as tensors. We call the model inside the tracing context to add the NNCF operations to the graph of the model.
def call(self, inputs, **kwargs): xs = self._apply_post_hooks_for_inputs(inputs) with get_current_context().enter(in_call=True, wrap_ops=True, model=self): outputs = self._model(xs, **kwargs) return outputs
[ "def forward(self, inputs):\r\n #print (len(inputs))\r\n out = self.fc1(inputs)\r\n out = self.fc2(out)\r\n self.out = out\r\n return out\r\n #raise NotImplementedError('Implement the forward method of the model')\r", "def evaluate(self, trained_model, model_input, *args,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts the list of the NNCF operations according to the target point.
def insert_at_point(self, point: TFTargetPoint, ops: List[NNCFOperation]) -> None: ops_weights = {op.name: op.create_variables(self) for op in ops} hook = Hook(ops, point, ops_weights) hooks = getattr(self, "_pre_hooks") if hook.is_pre_hook else getattr(self, "_post_hooks") # TODO(andrey...
[ "def add_cups(self, target_idx, cups_to_insert):\n part_a = self.cups[0 : target_idx + 1]\n part_b = self.cups[target_idx + 1 :]\n print(f\"cups: {self.cups} part_a[{part_a}], part_b[{part_b}]\")\n self.cups = part_a + cups_to_insert + part_b", "def insert_operations_in_head(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies posthooks to inputs.
def _apply_post_hooks_for_inputs(self, inputs): input_name_to_post_hook_map = { hook.target_point.op_name: hook for hook in getattr(self, "_hooks") if hook.target_point.op_type_name == "Placeholder" } if not input_name_to_post_hook_map: return inp...
[ "def process_inputs(self, inputs):", "def _pre_kernel_post_inputs(self):\n pass", "def call(self, inputs, **kwargs):\n xs = self._apply_post_hooks_for_inputs(inputs)\n with get_current_context().enter(in_call=True, wrap_ops=True, model=self):\n outputs = self._model(xs, **kwargs)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The number of commands in the pool (an integer).
def num_commands(self): return len(self.commands)
[ "def size():\r\n\treturn len(pool)", "def count(self):\n return len(self.commands)", "def count(self):\n return len(self._commands)", "def command_count(self):\n return len(self.commands)", "def nr_commands(self) -> int:\n return sum(module.nr_commands for module in self._modules...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The number of commands in the pool that have already finished, including retries (an integer).
def num_finished(self): return sum(cmd.is_finished_with_retries for id, cmd in self.commands)
[ "def size():\r\n\treturn len(pool)", "def getWaitingTaskCount():", "def get_number_executors(self):\n with self.__threads_lock:\n return self.__number_executors", "def count(cls, resq):\n return int(resq.redis.llen('resque:failed'))", "def count(self):\n return len(self._comm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The number of commands in the pool that failed (an integer).
def num_failed(self): return sum(cmd.failed for id, cmd in self.commands)
[ "def _get_n_executed(self):\n return self.n_statements - self.n_missing", "def count(cls, resq):\n return int(resq.redis.llen('resque:failed'))", "def size():\r\n\treturn len(pool)", "def count(self):\n return len(self.commands)", "def count(self):\n return len(self._commands)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A set of running command groups.
def running_groups(self): return set( cmd.group_by for id, cmd in self.commands if cmd.is_running and cmd.group_by is not None )
[ "def get_cli_groups():\n\n return get_component(CLIPackage.COMPONENT_NAME).get_cli_groups()", "def list_groups(self):\n pass", "def list_groups(args):\n\n for group in get_groups(args):\n print(group)", "def _run_group_cmds(self, commands, group):\n for cmd in commands[group]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Keep spawning commands and collecting results until all commands have run.
def run(self): # Start spawning processes to execute the commands. timer = Timer() logger.debug("Preparing to run %s with a concurrency of %i ..", pluralize(self.num_commands, "command"), self.concurrency) try: with self.get_spinner(t...
[ "def wait(self):\n for command in self.commands:\n command.wait()", "def collect(self):\n num_collected = 0\n for identifier, command in self.commands:\n if identifier not in self.collected and command.is_finished:\n try:\n command.wait(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collect the exit codes and output of finished commands.
def collect(self): num_collected = 0 for identifier, command in self.commands: if identifier not in self.collected and command.is_finished: try: command.wait(check=False if self.delay_checks else None) except ExternalCommandFailed as e: ...
[ "def finalize_process(proc):\r\n try:\r\n proc.wait()\r\n except GitCommandError,e:\r\n # if a push has rejected items, the command has non-zero return status\r\n # a return status of 128 indicates a connection error - reraise the previous one\r\n if proc.poll() == 128:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An error message that explains which commands failed unexpectedly (a string).
def error_message(self): summary = format("%i out of %s failed unexpectedly:", self.pool.num_failed, pluralize(self.pool.num_commands, "command")) details = "\n".join(" - %s" % cmd.error_message for cmd in self.commands) return summary + "\n\n" +...
[ "def command_failed_error(cmd):\n\n output_1 = colored(' - Error: Failed to run command ', 'red')\n output_2 = command(cmd)\n return output_1 + output_2 + '\\n'", "def error_exit(self, msg):\n wrappedmsg = textwrap.fill(msg, 78)\n fullmsg = \"%s\\n%s\" % (wrappedmsg, self.get_usage_command(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the username for the webprofile
def reset_webprofileusername(username): try: url = HOST + '/profile/username' r = requests.delete(url, headers=headers) return r.json() except requests.exceptions.RequestException as e: print("Something went wrong. Could not delete webprofile username:", e)
[ "def reset_web_profile_username(self, username):\n endpoint = '/profile/username'\n return self.delete_request(endpoint)", "def update_username(self):\n self.var_username.set(MainForm.logged_user)\n self.var_user_profile.set(MainForm.user_profile)", "def change_username(self, name):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns (SQL query, query parameters) that will aggregate from a UCR source to an aggregate table.
def aggregate_query(self): raise NotImplementedError
[ "def app_agg_SQL(source_table):\n\tSQL_base =\"\"\"SELECT\n\t\tyear\n\t\t,state\n\t\t,county\n\t\t,CONCAT(state, county) AS fips\n\t\t,ROUND(AVG(amount::INTEGER),2) AS loan_average_app\n\t\t,ROUND(AVG(income::INTEGER),2) AS income_average_app\n\t\t,COUNT(concat(agency, rid)) AS count_app\n\t\t,SUM(amount::INTEGER) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used for backend migrations from one data source to another. Returns (SQL query, query parameters) that will return any rows that are inconsistent from the old data to the new.
def compare_with_old_data_query(self): raise NotImplementedError
[ "def dbdiff(old, new):\r\n # TODO: check the comparison and add the previous value(s) into the diff table\r\n dir = \"C:/Users/Volodymyr.Turbayevsk/Desktop/Docs/programming/R/indicators/zipDBCopy/\"\r\n logging.info(old + '->' + new)\r\n engine = create_engine('sqlite:///' + dir + old + '.sqlite')\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compares data from the complementary feeding forms aggregate table to the the old child health monthly UCR table that current aggregate script uses
def compare_with_old_data_query(self): month = self.month.replace(day=1) return """ SELECT agg.case_id FROM "{child_health_monthly_ucr}" chm_ucr FULL OUTER JOIN "{new_agg_table}" agg ON chm_ucr.doc_id = agg.case_id AND chm_ucr.month = agg.month AND agg.state_id = chm_ucr....
[ "def compare_with_old_data_query(self):\n month = self.month.replace(day=1)\n return \"\"\"\n SELECT agg.case_id\n FROM \"{child_health_monthly_ucr}\" chm_ucr\n FULL OUTER JOIN \"{new_agg_table}\" agg\n ON chm_ucr.doc_id = agg.case_id AND chm_ucr.month = agg.month AND agg.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compares data from the complementary feeding forms aggregate table to the the old child health monthly UCR table that current aggregate script uses
def compare_with_old_data_query(self): month = self.month.replace(day=1) return """ SELECT agg.case_id FROM "{child_health_monthly_ucr}" chm_ucr FULL OUTER JOIN "{new_agg_table}" agg ON chm_ucr.doc_id = agg.case_id AND chm_ucr.month = agg.month AND agg.state_id = chm_ucr....
[ "def compare_with_old_data_query(self):\n month = self.month.replace(day=1)\n return \"\"\"\n SELECT agg.case_id\n FROM \"{child_health_monthly_ucr}\" chm_ucr\n FULL OUTER JOIN \"{new_agg_table}\" agg\n ON chm_ucr.doc_id = agg.case_id AND chm_ucr.month = agg.month AND agg.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether 2digit numbers num and den share a nonzero digit
def share_nonzero_digit(num, den): num_str = str(num) den_str = str(den) if "0" in num_str and "0" in den_str: return False return num_str[0] in den_str or num_str[1] in den_str
[ "def exactly_two_same_digits(num):\n output = False\n digits = [int(i) for i in str(num)]\n for i, dig in enumerate(digits[:-2]):\n if i == 0:\n if dig == digits[i + 1] and dig != digits[i + 2]:\n output = True\n else:\n if (dig != digits[i - 1] \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For two 2digit numbers num and den sharing a nonzero digit, determines whether these digits can cancel and maintain the value of num/den
def can_cancel(num, den): num_str = str(num) den_str = str(den) if num_str[0] == den_str[0] and den_str[1] != "0": return num / den == int(num_str[1]) / int(den_str[1]) elif num_str[0] == den_str[1] and den_str[0] != "0": return num / den == int(num_str[1]) / int(den_str[0]) elif num...
[ "def share_nonzero_digit(num, den):\n num_str = str(num)\n den_str = str(den)\n if \"0\" in num_str and \"0\" in den_str:\n return False\n return num_str[0] in den_str or num_str[1] in den_str", "def cancelOut(self):\n if(abs(self.numerator) > abs(self.denominator)): #depending on which ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> copy_matrix([[1, 2], [3, 4]]) [[1, 2], [3, 4]] >>> copy_matrix([[1, 2, 3], [4, 5, 6]]) [[1, 2, 3], [4, 5, 6]] >>> copy_matrix([[1, 2], [3, 4], [5, 6], [7, 8]]) [[1, 2], [3, 4], [5, 6], [7, 8]] >>> m = [[1, 0, 0], [0, 2, 0], [0, 0, 3]] >>> copyofm = copy_matrix(m) >>> copyofm [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
def copy_matrix(matrix): import numpy as np copy_of_m = np.copy(matrix) return copy_of_m
[ "def deepercopy(matrix):\n if isinstance(matrix[0], int) or isinstance(matrix[0], float):\n newmat = [0 for x in range(len(matrix))]\n for i in range(len(matrix)):\n newmat[i] = matrix[i]\n return newmat\n else:\n newmat = [0 for x in range(len(matrix))]\n for i i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> m = [[0, 0], [0, 0]] >>> add_row(m) [[0, 0], [0, 0], [0, 0]] >>> n = [[3, 2, 5], [1, 4, 7]] >>> add_row(n) [[3, 2, 5], [1, 4, 7], [0, 0, 0]] >>> n [[3, 2, 5], [1, 4, 7]]
def add_row(matrix): import numpy as np shape = np.shape(matrix) if matrix is np.zeros(shape): return matrix.append(np.zeros(shape[0]))
[ "def add_row(matrix):\n\tl = len(matrix[0])\n\ttemp = matrix[:]\n\ttemp += [[0]*l]\n\treturn temp", "def add_row(M, a, i1, i2):\n P = zeros(*M.shape)\n P[i2, i1] = 1\n return M + a * P * M", "def add_row(self, row):\n ...", "def matrix_add():", "def add_rows(self, *rows):\n if self.__...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 0) 19 >>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 1) 22 >>> row_times_column([[1, 2], [3, 4]], 1, [[5, 6], [7, 8]], 0) 43 >>> row_times_column([[1, 2], [3, 4]], 1, [[5, 6], [7, 8]], 1) 50
def row_times_column(m1, row, m2, column): pass
[ "def row_times_column(m1, row, m2, column):\n\tsum = 0\n\tfor i in range(len(m1[0])):\n\t\tsum += (m2[i][column] * m1[row][i])\n\treturn sum", "def row_to_column_helper(self, col_num, rows):\n columns = []\n for i in range(col_num):\n column = []\n # generate each column\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> matrix_mult([[1, 2], [3, 4]], [[5, 6], [7, 8]]) [[19, 22], [43, 50]] >>> matrix_mult([[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 1], [2, 3]]) [[31, 19], [85, 55]] >>> matrix_mult([[7, 8], [9, 1], [2, 3]], [[1, 2, 3], [4, 5, 6]]) [[39, 54, 69], [13, 23, 33], [14, 19, 24]]
def matrix_mult(m1, m2): pass
[ "def matrix_mult(m1, m2):\n\ttemp = []\n\tfor i in range(len(m1)):\n\t\te = []\n\t\tfor j in range(len(m2[0])):\n\t\t\te.append(row_times_column(m1,i,m2,j))\n\t\ttemp.append(e)\n\treturn temp", "def matrix_mult( m1, m2 ):\n temp = new_matrix(len(m1), len(m2[0]))\n for row in range(len(temp)):\n for c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> m = [[3, 4, 6]] >>> transpose(m) [[3], [4], [6]] >>> m [3, 4, 6] >>> m = [[3, 4, 6], [1, 5, 9]] >>> transpose(m) [[3, 1], [4, 5], [6, 9]]
def transpose(m): pass
[ "def transpose(M):\n if not isinstance(M, list) or \\\n any(not isinstance(row, list) for row in M):\n raise Exception('Invalid Input')\n else:\n rows = len(M)\n if rows == 0: # null matrix, empty\n return M\n cols = max(list(len(row) for row in M))\n if cols ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method must be called immediately after the class is instantiated. It instantiates the serial interface and then performs auto pin discovery. It is intended for use by pymata3 applications that do not use asyncio coroutines directly.
def start(self): # check if user specified a socket transport if self.ip_address: self.socket = PymataSocket(self.ip_address, self.ip_port, self.loop) self.loop.run_until_complete((self.socket.start())) # set the read and write handles self.read = self.so...
[ "async def start_aio(self):\n\n # pick the desired transport and then setup read and write to\n # point to the correct method for the transport\n\n # check if user specified a socket transport\n if self.ip_address:\n self.socket = PymataSocket(self.ip_address, self.ip_port, se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method must be called immediately after the class is instantiated. It instantiates the serial interface and then performs auto pin discovery. It is intended for use by applications that directly uses asyncio.
async def start_aio(self): # pick the desired transport and then setup read and write to # point to the correct method for the transport # check if user specified a socket transport if self.ip_address: self.socket = PymataSocket(self.ip_address, self.ip_port, self.loop) ...
[ "def start(self):\n\n # check if user specified a socket transport\n if self.ip_address:\n self.socket = PymataSocket(self.ip_address, self.ip_port, self.loop)\n self.loop.run_until_complete((self.socket.start()))\n # set the read and write handles\n self.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the last data update for the specified analog pin.
async def analog_read(self, pin): return self.analog_pins[pin].current_value
[ "def _sensor_last_update(self):\n return self._cam.get_attributes(self._sensor, self._channel)[3]", "def getLastSensorData(self):\n return self._latestSensorData", "async def digital_read(self, pin):\n return self.digital_pins[pin].current_value", "def getLastUpdate():\n swDB = switchd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the last data update for the specified digital pin.
async def digital_read(self, pin): return self.digital_pins[pin].current_value
[ "def getLastUpdate():\n swDB = switchdb.DB()\n lastupdate = swDB.getLastUpdate()\n swDB.close()\n return lastupdate", "def get_last_update(self):\n return self.ticker.all().order_by('-created').first()", "def getLastSensorData(self):\n return self._latestSensorData", "def getLastData...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disables analog reporting for a single analog pin.
async def disable_analog_reporting(self, pin): command = [PrivateConstants.REPORT_ANALOG + pin, PrivateConstants.REPORTING_DISABLE] await self._send_command(command)
[ "def disable_analog_reporting(self, pin):\n self._analog_pins_directly[pin].disable_analog_reporting()", "def disable_digital_reporting(self, pin):\n port = pin // 8\n self._ports_directly[port].disable_digital_reporting()", "def disable_reporting(self):\n self.reporting = False\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables analog reporting. By turning reporting on for a single pin,
async def enable_analog_reporting(self, pin): command = [PrivateConstants.REPORT_ANALOG + pin, PrivateConstants.REPORTING_ENABLE] await self._send_command(command)
[ "def enable_analog_reporting(self, pin):\n self._analog_pins_directly[pin].enable_analog_reporting()", "def enable_digital_reporting(self, pin):\n port = pin // 8\n self._ports_directly[port].enable_digital_reporting()", "def enable_reporting(self):\n self.reporting = True\n m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method requests and returns a Firmata capability query report
async def get_capability_report(self): if self.query_reply_data.get( PrivateConstants.CAPABILITY_QUERY) is None: await self._send_sysex(PrivateConstants.CAPABILITY_QUERY, None) while self.query_reply_data.get( PrivateConstants.CAPABILITY_RESPONSE) is N...
[ "def capability_response(self, data):\n self.capability_query_results = data", "def query_upgrade_capability(self):\n self.response = self.request('GET', self.capability_endpoint, \"\")\n self.log.debug(self.response.status)\n response = self.response.read()\n capability_schema ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method retrieves a pin state report for the specified pin
async def get_pin_state(self, pin): pin_list = [pin] await self._send_sysex(PrivateConstants.PIN_STATE_QUERY, pin_list) while self.query_reply_data.get( PrivateConstants.PIN_STATE_RESPONSE) is None: await asyncio.sleep(self.sleep_tune) pin_state_report = self....
[ "def pin_state(self, pin):\n port_num = self._convert_pin_port(pin)\n if port_num:\n value = gpio.input(port_num)\n return value", "def get(self, pin):\n\t\treturn self.accounts.get(pin, None)", "def getPin(self):\r\n return self.pin", "def read_pin(self, port, pin)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method retrieves the PyMata version number
async def get_pymata_version(self): return PrivateConstants.PYMATA_VERSION
[ "def get_version():\n return magpy.get_version()", "def get_version(self):\n return self.api_version", "def get_version_number():\n with open('version.py', 'r') as file_stream:\n line = file_stream.readline().split()\n version_number = line[2].replace('\\'', '')\n return versio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method requests the read of an i2c device. Results are retrieved by a call to i2c_get_read_data(). or by callback. If a callback method is provided, when data is received from the device it will be sent to the callback method. Some devices require that transmission be restarted (e.g. MMA8452Q accelerometer). Use C...
async def i2c_read_request(self, address, register, number_of_bytes, read_type, cb=None, cb_type=None): if address not in self.i2c_map: # self.i2c_map[address] = [None, cb] self.i2c_map[address] = {'value': None, 'callback': cb, ...
[ "async def i2c_read_request(self, address, register, number_of_bytes,\n read_type, cb=None):\n if address not in self.i2c_map:\n self.i2c_map[address] = {'value': None, 'callback': cb}\n if register is None:\n data = [address, read_type, number_of_by...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method will call the Tone library for the selected pin. It requires FirmataPlus to be loaded onto the arduino If the tone command is set to TONE_TONE, then the specified tone will be played. Else, if the tone command is TONE_NO_TONE, then any currently playing tone will be disabled.
async def play_tone(self, pin, tone_command, frequency, duration): # convert the integer values to bytes if tone_command == Constants.TONE_TONE: # duration is specified if duration: data = [tone_command, pin, frequency & 0x7f, (frequency >> 7) & 0x7f, ...
[ "async def play_tone(self, pin, tone_command, frequency=440, duration=0):\n if tone_command == Constants.TONE_TONE:\n self.Tone.play_tone(pin, frequency, duration)\n if tone_command == Constants.TONE_NO_TONE:\n self.Tone.stop_tone(pin)", "def note(self,\n tone):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a Sysex reset command to the arduino
async def send_reset(self): try: await self._send_command([PrivateConstants.SYSTEM_RESET]) except RuntimeError: exit(0)
[ "def sensor_reset():\n print(\"Sending reset signal to sensor\")\n PMS_RESET.value(0)\n time.sleep(0.5)\n PMS_RESET.value(1)\n time.sleep(1.0)", "async def send_reset(self):\n try:\n await self._send_command([PrivateConstants.SYSTEM_RESET])\n except RuntimeError:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method sends the desired sampling interval to Firmata.
async def set_sampling_interval(self, interval): data = [interval & 0x7f, (interval >> 7) & 0x7f] await self._send_sysex(PrivateConstants.SAMPLING_INTERVAL, data)
[ "def sampling_interval(self, milis):\n # minimum sampling interval supported is 10ms\n if milis > 16383:\n milis = 16383\n self.board.send_sysex(pyfirmata.SAMPLING_INTERVAL,\n bytearray([milis % 128, milis >> 7]))", "def record_data(self, no_of_samples,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure the pins,ping interval and maximum distance for an HCSR04 type device. Single pin configuration may be used. To do so, set both the trigger and echo pins to the same value. Up to a maximum of 6 SONAR devices is supported If the maximum is exceeded a message is sent to the console and the request is ignored.
async def sonar_config(self, trigger_pin, echo_pin, cb=None, ping_interval=50, max_distance=200, cb_type=None): # if there is an entry for the trigger pin in existence, just exit if trigger_pin in self.active_sonar_map: return if max_distance > 200: ...
[ "async def sonar_config(self, trigger_pin, echo_pin, cb=None,\n ping_interval=50, max_distance=350):\n # if there is an entry for the trigger pin in existence, just exit\n if trigger_pin in self.active_sonar_map:\n return\n\n if max_distance > 350:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move a stepper motor for the number of steps at the specified speed This is a FirmataPlus feature.
async def stepper_step(self, motor_speed, number_of_steps): if number_of_steps > 0: direction = 1 else: direction = 0 abs_number_of_steps = abs(number_of_steps) data = [PrivateConstants.STEPPER_STEP, motor_speed & 0x7f, (motor_speed >> 7) & 0x7f, (...
[ "def move_set_speed(self, speed):\n # self.motor_set_speed(MOTOR_LEFT, speed)\n # self.motor_set_speed(MOTOR_RIGHT, speed)\n self.move_speed = speed\n print(\"move_speed is now:\", self.move_speed)", "def forward(self, speed, seconds=None):\n # Set motor speed and move both forw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize Pixy and enable Pixy block reporting. This is a FirmataPlusRB feature.
async def pixy_init(self, max_blocks=5, cb=None, cb_type=None): if cb: self.digital_pins[PrivateConstants.PIN_PIXY_MOSI].cb = cb # Pixy uses SPI. Pin 11 is MOSI. if cb_type: self.digital_pins[PrivateConstants.PIN_PIXY_MOSI].cb_type = cb_type data = [PrivateConstants.PIX...
[ "async def pixy_init(self, max_blocks=5, cb=None):\n if cb:\n self.digital_pins[PrivateConstants.PIN_PIXY_MOSI].cb = cb # Pixy uses SPI. Pin 11 is MOSI.\n data = [PrivateConstants.PIXY_INIT, max_blocks & 0x7f]\n await self._send_sysex(PrivateConstants.PIXY_CONFIG, data)", "async ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends the setServos Pixy command. This method sets the pan/tilt servos that are plugged into Pixy's two servo ports.
async def pixy_set_servos(self, s0, s1): data = [PrivateConstants.PIXY_SET_SERVOS, s0 & 0x7f, (s0 >> 7) & 0x7f, s1 & 0x7f, (s1 >> 7) & 0x7f] await self._send_sysex(PrivateConstants.PIXY_CONFIG, data)
[ "async def pixy_set_servos(self, s0, s1):\n data = [PrivateConstants.PIXY_SET_SERVOS, s0 & 0x7f, (s0 >> 7) & 0x7f, s1 & 0x7f, (s1 >> 7) & 0x7f]\n await self._send_sysex(PrivateConstants.PIXY_CONFIG, data)", "def _PlotVelocity(self, servos):\n return self.CreatePlot(servos, 'Velocity', 'Velocity',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends the setBrightness Pixy command. This method sets the brightness (exposure) of Pixy's camera.
async def pixy_set_brightness(self, brightness): data = [PrivateConstants.PIXY_SET_BRIGHTNESS, brightness & 0x7f, (brightness >> 7) & 0x7f] await self._send_sysex(PrivateConstants.PIXY_CONFIG, data)
[ "async def pixy_set_brightness(self, brightness):\n data = [PrivateConstants.PIXY_SET_BRIGHTNESS, brightness & 0x7f, (brightness >> 7) & 0x7f]\n await self._send_sysex(PrivateConstants.PIXY_CONFIG, data)", "def setBrightness(self, *args):\n return _yarp.IFrameGrabberControls_setBrightness(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends the setLed Pixy command. This method sets the RGB LED on front of Pixy.
async def pixy_set_led(self, r, g, b): data = [PrivateConstants.PIXY_SET_LED, r & 0x7f, (r >> 7) & 0x7f, g & 0x7f, (g >> 7) & 0x7f, b & 0x7f, (b >> 7) & 0x7f] await self._send_sysex(PrivateConstants.PIXY_CONFIG, data)
[ "async def pixy_set_led(self, r, g, b):\n data = [PrivateConstants.PIXY_SET_LED, r & 0x7f, (r >> 7) & 0x7f, g & 0x7f, (g >> 7) & 0x7f, b & 0x7f,\n (b >> 7) & 0x7f]\n await self._send_sysex(PrivateConstants.PIXY_CONFIG, data)", "def turn_on_led(self):\r\n self.command = self.com...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private message handler method. It is a message handler for the analog mapping response message
async def _analog_mapping_response(self, data): self.query_reply_data[PrivateConstants.ANALOG_MAPPING_RESPONSE] = \ data[1:-1]
[ "def analog_mapping_response(self, data):\n self.analog_mapping_query_results = data", "def on_response_received(self, message):", "def response_handling(self) -> global___Snippet.SimpleResponseHandling:", "def handle(self, response_stream):", "def map_callback(self,msg):\n self.map = np.array...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private message handler method. It is a message handler for capability report responses.
async def _capability_response(self, data): self.query_reply_data[PrivateConstants.CAPABILITY_RESPONSE] = data[1:-1]
[ "async def get_capability_report(self):\n if self.query_reply_data.get(\n PrivateConstants.CAPABILITY_QUERY) is None:\n await self._send_sysex(PrivateConstants.CAPABILITY_QUERY, None)\n while self.query_reply_data.get(\n PrivateConstants.CAPABILITY_RESP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private message handler method. It handles pixy data messages.
async def _pixy_data(self, data): if len(self.digital_pins) < PrivateConstants.PIN_PIXY_MOSI: # Pixy data sent before board finished pin discovery. # print("Pixy data sent before board finished pin discovery.") return # strip off sysex start and end data = da...
[ "async def _pixy_data(self, data):\n if len(self.digital_pins) < PrivateConstants.PIN_PIXY_MOSI:\n # Pixy data sent before board finished pin discovery.\n # print(\"Pixy data sent before board finished pin discovery.\")\n return\n\n # strip off sysex start and end\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private message handler method. It handles replies to i2c_read requests. It stores the data for each i2c device address in a dictionary called i2c_map. The data may be retrieved via a polling call to i2c_get_read_data(). It a callback was specified in pymata.i2c_read, the raw data is sent through the callback
async def _i2c_reply(self, data): # remove the start and end sysex commands from the data data = data[1:-1] reply_data = [] # reassemble the data from the firmata 2 byte format address = (data[0] & 0x7f) + (data[1] << 7) # if we have an entry in the i2c_map, proceed ...
[ "def i2c_reply(self, data):\n\n reply_data = []\n address = (data[0] & 0x7f) + (data[1] << 7)\n register = data[2] & 0x7f + data[3] << 7\n reply_data.append(register)\n for i in range(4, len(data), 2):\n data_item = (data[i] & 0x7f) + (data[i + 1] << 7)\n rep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private message handler method. It handles pin state query response messages.
async def _pin_state_response(self, data): self.query_reply_data[PrivateConstants.PIN_STATE_RESPONSE] = data[1:-1]
[ "async def get_pin_state(self, pin):\n pin_list = [pin]\n await self._send_sysex(PrivateConstants.PIN_STATE_QUERY, pin_list)\n while self.query_reply_data.get(\n PrivateConstants.PIN_STATE_RESPONSE) is None:\n await asyncio.sleep(self.sleep_tune)\n pin_state_rep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private message handler method. This method handles the sysex 'report firmware' command sent by Firmata (0x79). It assembles the firmware version by concatenating the major and minor version number components and the firmware identifier into a string. e.g. "2.3 StandardFirmata.ino"
async def _report_firmware(self, sysex_data): # first byte after command is major number major = sysex_data[1] version_string = str(major) # next byte is minor number minor = sysex_data[2] # append a dot to major number version_string += '.' # append mi...
[ "async def _report_firmware(self, sysex_data):\n # first byte after command is major number\n firmware_report_iterator = iter(sysex_data)\n\n major = sysex_data[1]\n version_string = str(major)\n\n # next byte is minor number\n minor = sysex_data[2]\n\n # append a do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private message handler method. This method reads the following 2 bytes after the report version command (0xF9 non sysex). The first byte is the major number and the second byte is the minor number.
async def _report_version(self): # get next two bytes major = await self.read() version_string = str(major) minor = await self.read() version_string += '.' version_string += str(minor) self.query_reply_data[PrivateConstants.REPORT_VERSION] = version_string
[ "async def _report_firmware(self, sysex_data):\n # first byte after command is major number\n major = sysex_data[1]\n version_string = str(major)\n\n # next byte is minor number\n minor = sysex_data[2]\n\n # append a dot to major number\n version_string += '.'\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private utility method. When a data change message is received this method checks to see if latching needs to be processed
async def _check_latch_data(self, key, data): process = False latching_entry = self.latch_map.get(key) if latching_entry[Constants.LATCH_STATE] == Constants.LATCH_ARMED: # Has the latching criteria been met if latching_entry[Constants.LATCHED_THRESHOLD_TYPE] == \ ...
[ "def check_sync(self):\r\n if not self.awaiting_sync:\r\n return True\r\n self.check_ack_queue()\r\n return not self.awaiting_sync", "def should_poll(self):\r\n return self._command_state is not None", "def should_poll(self):\n return self._command_state is not None...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private utility method. This method attempts to discover the com port that the arduino is connected to.
def _discover_port(self): # if MAC get list of ports if sys.platform.startswith('darwin'): locations = glob.glob('/dev/tty.[usb*]*') locations = glob.glob('/dev/tty.[wchusb*]*') + locations locations.append('end') # for everyone else, here is a list of possibl...
[ "def find_port():\n coms = []\n open_ports = []\n\n # native_com_list = list_ports.comports(True)\n\n for port in range(1, 256):\n com_check = \"COM\" + str(port)\n try:\n s = serial.Serial(com_check)\n s.close()\n open_ports.append(com_check)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private utility method. This method formats a capability report if the user wishes to send it to the console. If log_output = True, no output is generated
def _format_capability_report(self, data): if self.log_output: return else: pin_modes = {0: 'Digital_Input', 1: 'Digital_Output', 2: 'Analog', 3: 'PWM', 4: 'Servo', 5: 'Shift', 6: 'I2C', 7: 'One Wire', 8...
[ "def _format_capability_report(self, data):\n\n\n\n pin_modes = {0: 'Digital_Input', 1: 'Digital_Output',\n 2: 'Analog', 3: 'PWM', 4: 'Servo',\n 5: 'Shift', 6: 'I2C', 7: 'One Wire',\n 8: 'Stepper', 9: 'Encoder'}\n x = 0\n pin = 0\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private utility method. This method process latching events and either returns them via callback or stores them in the latch map
async def _process_latching(self, key, latching_entry): if latching_entry[Constants.LATCH_CALLBACK]: # auto clear entry and execute the callback if latching_entry[Constants.LATCH_CALLBACK_TYPE]: await latching_entry[Constants.LATCH_CALLBACK] \ ([key, l...
[ "async def _process_latching(self, key, latching_entry):\n if latching_entry[Constants.LATCH_CALLBACK]:\n # auto clear entry and execute the callback\n if inspect.iscoroutinefunction(latching_entry[Constants.LATCH_CALLBACK]):\n await latching_entry[Constants.LATCH_CALLBAC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private utility method. This method sends a sysex command to Firmata.
async def _send_sysex(self, sysex_command, sysex_data=None): if not sysex_data: sysex_data = [] # convert the message command and data to characters sysex_message = chr(PrivateConstants.START_SYSEX) sysex_message += chr(sysex_command) if len(sysex_data): ...
[ "def syst_cmd(self):\n print_debug(\"Executing SYST\")\n command = \"SYST\\r\\n\"\n msg_rec = self.send_and_log(self.s, command)\n return msg_rec", "def send_system_exclusive(self, value=\"\"):\n msg = parse_sysex_string(value)\n\n if (msg and msg.startswith(b'\\xF0') and...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a private utility method. This method accumulates the requested number of bytes and then returns the full command
async def _wait_for_data(self, current_command, number_of_bytes): while number_of_bytes: next_command_byte = await self.read() current_command.append(next_command_byte) number_of_bytes -= 1 return current_command
[ "def SendBufferSize(self) -> int:", "def ReceiveBufferSize(self) -> int:", "def getCommandQueueSize(self, REQUEST=None):\r\n size = len(self._commands)\r\n return size", "def _command_length(self, cmd, opcode, program_counter):\n if opcode == data_spec_constants.DSG_END_SPEC:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark a view function as excluded from CommonMiddleware's APPEND_SLASH redirection.
def no_append_slash(view_func): # view_func.should_append_slash = False would also work, but decorators are # nicer if they don't have side effects, so return a new function. @wraps(view_func) def wrapper_view(*args, **kwargs): return view_func(*args, **kwargs) wrapper_view.should_append_sl...
[ "def auth_middleware_exempt(view_func):\n view_func._auth_middleware_exempt = True\n return view_func", "def auth_exempt(view_func):\n def wrapped_view(*args, **kwargs):\n return view_func(*args, **kwargs)\n wrapped_view.auth_exempt = True\n return wraps(view_func)(wrapped_view)", "def csr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts information contained in the extended xyz format
def extended_xyz_parse(xyz_d): s_properties = ['rot_A', 'rot_B', 'rot_C', 'dipole', 'polarizability', 'homo', 'lumo', 'band_gap', 'ese...
[ "def read_xyz(filename):\n #print('Reading geom from:'),filename\n atoms = []\n coordinates = []\n\t\n xyz = open(filename)\n n_atoms = int(xyz.readline())\n title = xyz.readline()\n for line in xyz:\n\tif len(line.strip()) == 0:\n\t\tpass\n\t\tbreak\t\n\tatom,x,y,z = line.split()\n\tatoms.appe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a coulomb matrix representing the ASE atoms object
def to_coulomb_m(mol, max_size=23): mol = to_ase(mol) atomic_nos = mol.get_atomic_numbers() positions = mol.get_positions() bohr_positions = positions/Bohr no_atoms = len(mol) coulomb_m = np.zeros([no_atoms, no_atoms]) for i in range(no_atoms): for j in range(no_atoms): ...
[ "def _create_atoms(data, section=\"initial\"):\n cell_data = data[section][\"primitive_cell\"]\n cell_vectors = []\n for n in \"a b c\".split():\n assert cell_data[\"cell_vectors\"][n][\"units\"] == \"angstrom\"\n cell_vectors.append(cell_data[\"cell_vectors\"][n][\"magnitude\"])\n ccoords...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a coulomb matrix representing the molecule passed in mol if an additional array is passed this is added on to the end of the vector
def to_coulomb_vec(mol, max_size=23, addition=None): cm = to_coulomb_m(mol, max_size=max_size) cm_vec = cm[np.tril_indices(cm.shape[0])] if addition: cm_vec = np.hstack([cm_vec, addition]) return cm_vec
[ "def to_coulomb_m(mol, max_size=23):\n mol = to_ase(mol)\n atomic_nos = mol.get_atomic_numbers()\n positions = mol.get_positions()\n bohr_positions = positions/Bohr\n no_atoms = len(mol)\n coulomb_m = np.zeros([no_atoms, no_atoms])\n\n for i in range(no_atoms):\n for j in range(no_atoms)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an mdtraj trajectory object corresponding to snapshots from an openMM simulation to a list of ASE objects each corresponding to one frame
def to_ase_frames(traj): unit_conversion = u.nanometer.conversion_factor_to(u.angstrom) symbols = ([a.element.symbol for a in traj.topology.atoms]) sim_positions = [frame_coords*unit_conversion for frame_coords in traj.xyz] frames = [] for frame_positions in sim_positions: fra...
[ "def analyse_trajectory(self):\n xc = np.reshape(self.data.fractional_trajectory[:, self.dimension], ((self.data.timesteps),\n self.data.total_atoms))\n\n trajectories = np.split(self.data.fractional_trajectory, self.data.timesteps)\n trajectories = np.asarray(trajectorie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generated ensemble of solvated molecules
def generate_solvated_ensemble(orig_mol, mol_id, solvent_mol, solvent_id, n_solvent, ensemble_size): #joblib fails, multiprocessing + pool.map fails # maybe need to try using partial + pool.map? # e.g. http://stackoverflow.com/questions/16542261/python-multiprocessing-pool-with-map-async #from job...
[ "def make_ensemble(structures: typing.List[pd.AtomGroup]):\n ensemble = pd.buildPDBEnsemble(structures, subset=\"calpha\")\n ensemble.iterpose()\n return ensemble", "def __init__(self, nr_molecules, surface_size):\n self.molecules = []\n for i in range(nr_molecules):\n self.try_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Searches through a .tar.bz2 file extracting data from all .log files that match string argument 'calc_type'. Then pickles the total list of extracted data
def extract_bz2(tar_bz_f, calc_type): # we give the gaussian calculator a label that includes the directory the # log file is contained in, this does not affect the parsing process but # generate a warning as it is not an expected form for the label. To avoid # the profusion of warning messages in ...
[ "def process_tar_archive(tar_file_name):\n with tarfile.open(tar_file_name,'r') as tar:\n tar_log_files = tar.getnames()\n queue_log_subset = pd.concat([ pd.read_csv(tar.extractfile(log),delim_whitespace=True).assign(\n Date=datetime.datetime.strptime(log.split('.')[0],'%...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves a pytorch tensor to numpy
def _torch_to_numpy(tensor): return tensor.detach().cpu().numpy()
[ "def numpy2tensor(x):\n result = torch.from_numpy(x)\n # result = torch.tensor(x)\n\n\n return result", "def to_numpy(tensor):\n return x.data.cpu().numpy()", "def torch2numpy(tensor):\r\n assert (tensor.dim() == 3)\r\n c, h, w = tensor.shape\r\n tensor = tensor.reshape((h, w, c))\r\n ten...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns an image with values between min and max
def clip_image(img, min=0, max=1): img[img < min] = min img[img > max] = max return img
[ "def to_range(images, min_value=0.0, max_value=1.0, dtype=None):\n assert \\\n np.min(images) >= -1.0 - 1e-5 and np.max(images) <= 1.0 + 1e-5 \\\n and (images.dtype == np.float32 or images.dtype == np.float64), \\\n 'The input images should be float64(32) and in the range of [-1.0, 1.0]!'\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }