query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
Define ZMQ connection and return socket to work with
def connect_to_worker(): socket = context.socket(zmq.REQ) socket.connect("tcp://localhost:5555") return socket
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def meta_trader_connector():\n context = zmq.Context()\n socket = context.socket(zmq.REQ)\n socket.connect(SOCKET_LOCAL_HOST)\n return socket", "def socket(self):\n if not hasattr(self, \"_socket\"):\n # create a new one\n self._socket = self.context.socke...
[ "0.7175116", "0.70785046", "0.6988766", "0.690476", "0.67760694", "0.673751", "0.664417", "0.65480554", "0.64834565", "0.6372554", "0.62621725", "0.6188751", "0.6151901", "0.614989", "0.6100526", "0.60442936", "0.6018518", "0.60160136", "0.59882885", "0.5986249", "0.5965816",...
0.77242374
0
Make request to ZMQ worker for calculation, logs results and times and returns them
def calculate(expression, socket): start = time.time() socket.send(bytes(expression)) result = socket.recv() total_time = (time.time() - start)*1000.0 total_time_str = '{0:.3f}'.format(total_time) logging.info('{} = {} in {}ms'.format(expression, result, total_time_str)) return { 'result': result, 'time': total_time_str }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main_task_handler():\n context = zmq.Context()\n\n # socket to sending messages to save\n save_sender = context.socket(zmq.PUSH)\n save_sender.connect(SAVE_PUSH_QUEUE_ADDR)\n\n c = 0\n while (True):\n # simulate some very complex computation\n (x, y) = (random.gauss(0, 1), rando...
[ "0.5938819", "0.59349483", "0.5909281", "0.5909281", "0.5895395", "0.5823286", "0.5821491", "0.57913584", "0.57686776", "0.5757286", "0.5728129", "0.57082814", "0.56994784", "0.56603485", "0.56561863", "0.565306", "0.5591266", "0.5583581", "0.5565303", "0.5563218", "0.5479768...
0.57413363
10
Used to handle not responding zmq server
def raise_timeout(*args, **kwargs): raise ZMQNotResponding('ZMQ server is not responding')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fix_zmq_exit():\n import zmq\n ctx = zmq.Context.instance()\n ctx.term()", "def test_recv_nomsg(self):\n flag, msg_recv = self.recv_instance.recv(timeout=self.sleeptime)\n assert(not flag)\n nt.assert_equal(msg_recv, self.recv_instance.eof_msg)", "def connectionLost(reason):",...
[ "0.6562494", "0.62199134", "0.62131953", "0.61594874", "0.61404806", "0.6073438", "0.6002306", "0.59552497", "0.5933235", "0.59127086", "0.5870852", "0.58468467", "0.5773297", "0.5767091", "0.5763371", "0.57514524", "0.5717791", "0.57169217", "0.5679771", "0.56770015", "0.567...
0.71370596
0
Create a recurring subscription.
def create_braintree(): #TODO: plan_id and user_id should be unique, I should be updating # old plans if they get reactivated. Implement logic to check this in future. # otherwise you can end up with a bunch of unactive plans when you get the user. # Which may cause slowness for that user. # Set the subscription details. self.user_id = user.id self.plan_id = plan_id # Create the user account if none exists. if user.customer_id is None: result = braintree.Customer.create() if result.is_success: user.customer_id = result.customer.id else: return result # Create the payment method result = braintree.PaymentMethod.create({ 'customer_id': user.customer_id, 'payment_method_nonce': payment_method_nonce, 'options': { 'verify_card': True } }) if result.is_success: self.payment_method_token = result.payment_method.token else: return result # Create subscription result = braintree.Subscription.create({ 'payment_method_token': self.payment_method_token, 'plan_id': plan_id }) if result.is_success: self.subscription_id = result.subscription.id self.active = True else: return result # Commit to database db.session.add(user) db.session.add(self) db.session.commit() return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def recurring_charge_subscription(\n subscription_id: str,\n namespace: Optional[str] = None,\n x_additional_headers: Optional[Dict[str, str]] = None,\n **kwargs\n):\n if namespace is None:\n namespace, error = get_services_namespace()\n if error:\n return None, error\n r...
[ "0.7562298", "0.72675866", "0.7255067", "0.6888839", "0.67131966", "0.66710687", "0.663895", "0.66039276", "0.6548797", "0.6534004", "0.6509307", "0.6500344", "0.64609605", "0.6345497", "0.6329807", "0.6320571", "0.629122", "0.627429", "0.62693095", "0.6210127", "0.6126169", ...
0.0
-1
DEPERECIATED FUNCTION PLEASE USE active field of subscription
def is_active(self): return self.active
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_get_subscription(self):\n pass", "def list_subscriptions(self):\n return {'abonnementen': self.customer.abonnementen}", "def activate_subscription(**kwargs):\n sub, created = Subscription.objects.get_or_create(**kwargs)\n # check if it already existed and was deactivated\n if not cr...
[ "0.63394845", "0.62465435", "0.61932844", "0.61151147", "0.60587835", "0.59960914", "0.5993149", "0.5967535", "0.58414245", "0.58307177", "0.58283544", "0.5719315", "0.57160527", "0.5682019", "0.5677654", "0.56643665", "0.56286776", "0.56263405", "0.56165206", "0.55921304", "...
0.0
-1
this functions creates a draft with the email data given the user id should be either 'me', either 'users/email.com' either 'users/{AAD_userId}',
def create_draft(auth, subject, body, addresses, user_id, cc_addresses=[], attachments_list=None): data = {} data['Subject'] = subject data['Body'] = {} data['Body']['ContentType'] = 'HTML' data['Body']['Content'] = body data['ToRecipients'] = [{'EmailAddress': {'Address': addr}} for addr in addresses] data['ccRecipients'] = [{'EmailAddress': {'Address': addr}} for addr in cc_addresses] if attachments_list is not None: data['Attachments'] = attachments_list params = json.dumps(data).encode('utf8') url = "{api_url}/{user_id}/messages".format(api_url=API_URL, user_id=user_id) headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(auth.access_token) } req = urllib.request.Request(url, params, headers) try: resp = urllib.request.urlopen(req) resp_data = json.load(resp) logging.getLogger(__name__).info("Draft created") return resp_data['id'] except urllib.error.HTTPError as err: raise AzureError(err)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_email(context, params):\n updated = {}\n for key in params:\n updated[camelcase_to_underscore(key)] = params[key]\n params = updated\n if not params.get('val') or params.get('is_deleted'):\n return None\n form_email = dict()\n if not params.get('label'):\n form_ema...
[ "0.6185358", "0.5889587", "0.56886303", "0.563527", "0.5423166", "0.5389278", "0.53863585", "0.5356391", "0.5334495", "0.5330233", "0.53246087", "0.53019273", "0.5286498", "0.5276959", "0.5267437", "0.5240132", "0.5237234", "0.5231543", "0.52308434", "0.5228887", "0.5216414",...
0.73411775
0
iterator which goes through all the pages to find all the emails
def get_all_emails_it(auth, user_id, folder_id='AllItems', pages_limit=None, pages_size=50, **kwargs): i = 0 args_dict = dict(kwargs, top=pages_size, skip=pages_size * i) curr_emails = get_emails(auth, user_id, folder_id, **args_dict) while len(curr_emails) != 0: yield curr_emails if pages_limit is not None and i >= pages_limit: break i += 1 args_dict = dict(kwargs, top=pages_size, skip=pages_size * i) curr_emails = get_emails(auth, user_id, folder_id, **args_dict)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_email_addresses(startdate, enddate, user, password):\n emails = []\n page = 1\n more_pages = True\n\n while more_pages:\n response = requests.get(\n 'https://restapi.surveygizmo.com/v2/survey/{survey}'\n '/surveyresponse?'\n 'filter[field][0]=datesubmitte...
[ "0.6516295", "0.64715", "0.6371025", "0.6256334", "0.6235852", "0.61884665", "0.61240774", "0.6112633", "0.6023784", "0.60078543", "0.59824973", "0.59707236", "0.5946463", "0.5928901", "0.5901219", "0.58981884", "0.5887079", "0.5860919", "0.5854434", "0.58382696", "0.5836329"...
0.71289283
0
Calculate the masked ratio.
def get_masked_ratio(mask): hist = mask.histogram() return hist[0] / np.prod(mask.size)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def maskedFraction(self):\n\n\t\tif not self._masked:\n\t\t\treturn 0.0\n\t\telse:\n\t\t\treturn self._masked_fraction", "def maskedFraction(self):\n\n\t\treturn self._masked_fraction", "def bw_ratio(self):\r\n bw = self.bwstats.mean\r\n if bw == 0.0: return 0\r\n else: return self.bw/(1024.*bw)", "...
[ "0.7183577", "0.6947266", "0.6375616", "0.62425804", "0.6177991", "0.6146051", "0.6002309", "0.5985765", "0.59175396", "0.58450127", "0.5783589", "0.5759599", "0.57562935", "0.56993043", "0.56441855", "0.56413704", "0.5576878", "0.55284727", "0.54961735", "0.5492076", "0.5457...
0.78421235
0
Retrieves or create a key/value from the request extra_context. If key is found, it is returned, that simple. If not, and a value has been passed, the key is set and returned.
def get_or_create(key, value=None): if not hasattr(g, key): value = value() if callable(value) else value setattr(g, key, value) return getattr(g, key)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_context(self, extra_ctx=None, **kwargs):\n ctx = {\n 'user': self.user,\n }\n if extra_ctx:\n ctx.update(extra_ctx)\n ctx.update(kwargs)\n return ctx", "def get(self, key, default=None):", "def addToExtra(self,key,val):\n if self.extra == ...
[ "0.57630116", "0.5627676", "0.5543135", "0.55403066", "0.5527593", "0.5498205", "0.54873115", "0.5451134", "0.54109406", "0.5372317", "0.5307185", "0.525926", "0.5251889", "0.5233425", "0.5200257", "0.51947916", "0.51554173", "0.51229984", "0.508491", "0.50824934", "0.5082493...
0.5090194
18
Create a dictionary with domain architectures exclusive in a single pathogen type group.
def generateArchitectureDataStructure(db, collapse_pathogen_groups=False): # Calculate total numbers of species and strains for each pathogen group counts_species_pathogen_dict = defaultdict(lambda: defaultdict(int)) for row in db.getNumSpeciesPathogen(): counts_species_pathogen_dict[row['pathogen_type']]['num_species'] = row['num_species'] counts_species_pathogen_dict[row['pathogen_type']]['num_strains'] = row['num_strains'] architecture_pathogen_dict = defaultdict(list) arch_strains_species_dict = defaultdict(lambda: defaultdict(list)) for row in db.getArchitecturePathogenTypeIterator(): strains = row['species'] species = str(strains).split(' (')[0] pathogen_type = row['pathogen_type'] architecture_id = row['architecture'] architecture_acc = row['architecture_acc'] architecture_pathogen_dict[(architecture_id, architecture_acc)].append(pathogen_type) arch_strains_species_dict[(architecture_id, architecture_acc)]['species'].append(species) arch_strains_species_dict[(architecture_id, architecture_acc)]['strains'].append(strains) for architecture in architecture_pathogen_dict.keys(): # If an architecture is only present in proteins of a certain pathogen_type, # it should have only 1 pathogen_type pathogen_groups_set = set(architecture_pathogen_dict[architecture]) if not exclusive_arch(pathogen_groups_set, collapse_pathogen_groups): architecture_pathogen_dict.pop(architecture) arch_strains_species_dict.pop(architecture) else: # Check if the architecture is present in all species and strains species_set = set(arch_strains_species_dict[architecture]['species']) strains_set = set(arch_strains_species_dict[architecture]['strains']) total_num_species, total_num_strains = get_number_ssp_stt_members(counts_species_pathogen_dict, pathogen_groups_set, collapse_pathogen_groups) arch_strains_species_dict[architecture]['total_num_species'] = total_num_species arch_strains_species_dict[architecture]['total_num_strains'] = total_num_strains if total_num_species == len(species_set): arch_strains_species_dict[architecture]['all_species'] if total_num_strains == len(strains_set): arch_strains_species_dict[architecture]['all_strains'] return architecture_pathogen_dict, arch_strains_species_dict
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def environments_of(groups):\n types = {}\n for group in groups:\n for env in group.environments:\n et = env.environmentType\n envs = types.setdefault((et.id, et.name), set())\n envs.add((env.id, env.name))\n return types", "def build_groupings(idir: str) -> dict:...
[ "0.53147066", "0.5278428", "0.51913285", "0.5105832", "0.5089798", "0.5063621", "0.5043128", "0.5004288", "0.49817312", "0.4942777", "0.49404955", "0.49214888", "0.49084446", "0.48987442", "0.48879838", "0.4885036", "0.48838812", "0.48718145", "0.4864769", "0.4852137", "0.483...
0.56843174
0
Boolean function to check if a given architecture is exclusive.
def exclusive_arch(pathogen_groups_set, collapse_pathogen_groups): if len(pathogen_groups_set) == 1: return True # Only check pathogen grouping when the flag is on if collapse_pathogen_groups: if len(pathogen_groups_set) > 2: return False if 0 in pathogen_groups_set and 1 in pathogen_groups_set: return True if 3 in pathogen_groups_set and 4 in pathogen_groups_set: return True return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_logical(*args):\n return _ida_hexrays.is_logical(*args)", "def __bool__(self):\n return any(self.smask)", "def is_infrastructure (self):\n return sum([1 for i in self.infras]) != 0", "def is_exclusive(self):\n return self.exclusive", "def incompatible_architecture(self) -> bool:\n ...
[ "0.588355", "0.5876618", "0.58541375", "0.58166057", "0.5798117", "0.5712255", "0.5689939", "0.5669322", "0.5637539", "0.5548849", "0.5544105", "0.5517736", "0.54952157", "0.5487494", "0.5465993", "0.5461534", "0.54453385", "0.5438241", "0.5419825", "0.53650993", "0.53650993"...
0.59786093
0
Loads the labels file. Supports files with or without index numbers.
def load_labels(path): with open(path, 'r', encoding='utf-8') as f: lines = f.readlines() labels = {} for row_number, content in enumerate(lines): pair = re.split(r'[:\s]+', content.strip(), maxsplit=1) if len(pair) == 2 and pair[0].strip().isdigit(): labels[int(pair[0])] = pair[1].strip() else: labels[row_number] = pair[0].strip() return labels
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read_labels(idx_filename):\n return IdxFileLoader().load(idx_filename, gzip_compressed=True)[-1]", "def load_labels():\n filename = os.path.join(config['inference']['model_dir'], 'output_labels.txt')\n global labels\n labels = [line.rstrip() for line in tf.gfile.FastGFile(filename)]", "def load_label...
[ "0.7585093", "0.73918986", "0.7356385", "0.7295458", "0.7295458", "0.7251934", "0.72350484", "0.72224325", "0.69650286", "0.6930105", "0.6915016", "0.68840927", "0.6850086", "0.683416", "0.68133795", "0.6811225", "0.6805284", "0.67956245", "0.67892665", "0.6772183", "0.675498...
0.684912
13
Sets the input tensor.
def set_input_tensor(self, image): tensor_index = self.interpreter.get_input_details()[0]['index'] input_tensor = self.interpreter.tensor(tensor_index)()[0] input_tensor[:, :] = image
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_input_tensor(self, image):\n tensor_index = self.model.get_input_details()[0]['index']\n input_tensor = self.model.tensor(tensor_index)()[0]\n input_tensor[:, :] = image", "def _set_input_tensor(self, image):\n tensor_index = self._interpreter.get_input_details()[0]['index']\n...
[ "0.78925943", "0.7880494", "0.7589295", "0.74826103", "0.74208987", "0.74208987", "0.74208987", "0.73879915", "0.6989476", "0.67201304", "0.66477954", "0.66477954", "0.65359837", "0.64077353", "0.6385685", "0.6378955", "0.6283016", "0.62689894", "0.6259443", "0.62375194", "0....
0.78595096
2
Returns the output tensor at the given index.
def get_output_tensor(self, index): output_details = self.interpreter.get_output_details()[index] tensor = np.squeeze(self.interpreter.get_tensor(output_details['index'])) return tensor
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_output_tensor(index):\n output_details = interpreter.get_output_details()[index]\n tensor = np.squeeze(interpreter.get_tensor(output_details['index']))\n return tensor", "def get_output_tensor(self, index):\n output_details = self.model.get_output_details()[index]\n tensor = np.squ...
[ "0.88110566", "0.8773681", "0.86581725", "0.8473132", "0.8446493", "0.8446493", "0.8446493", "0.75534517", "0.7171569", "0.68134344", "0.6715133", "0.6542007", "0.65397805", "0.65058136", "0.6436549", "0.6430624", "0.63161963", "0.6215072", "0.6104049", "0.6095873", "0.608248...
0.87153566
2
Returns a list of detection results, each a dictionary of object info.
def detect_objects(self, image, threshold): self.set_input_tensor(image) self.interpreter.invoke() # Get all output details boxes = self.get_output_tensor(0) classes = self.get_output_tensor(1) scores = self.get_output_tensor(2) count = int(self.get_output_tensor(3)) results = [] for i in range(count): if scores[i] >= threshold: result = { 'bounding_box': boxes[i], 'class_id': classes[i], 'score': scores[i] } results.append(result) return results
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def detect_objects(interpreter, image):\n set_input_tensor(interpreter, image)\n interpreter.invoke()\n\n # Get all output details\n boxes = get_output_tensor(interpreter, 0)\n classes = get_output_tensor(interpreter, 1)\n scores = get_output_tensor(interpreter, 2)\n count = int(get_output_ten...
[ "0.7317474", "0.71720695", "0.7067133", "0.70630217", "0.7045426", "0.7042128", "0.66765565", "0.662646", "0.6616235", "0.65515685", "0.65083957", "0.6459783", "0.6371822", "0.63698006", "0.6324095", "0.6281179", "0.6168086", "0.6153466", "0.61346966", "0.612045", "0.61051345...
0.7075441
2
Return a distance matrix.
def distance_matrix(n_row, n_col): n_pop = int(n_row * n_col) center = int(n_row/2*(n_col+1)) pop_idx = np.arange(n_pop) pop_idx_col = np.remainder(pop_idx, n_col) pop_idx_row = pop_idx // n_row pos = np.vstack((pop_idx_col,pop_idx_row)).T distance = spa.distance.cdist([pos[center]], pos)[0] return distance
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getDistanceMatrix(self):\n return self.distmat.as_matrix()", "def getDistanceMatrix(self):\n v = self.getVectors()\n vLis = v.keys()\n N = len(v.keys())\n D = np.zeros([N, N], dtype=np.float32)\n print(N)\n for i in range(N):\n print(\"%d/%d\" %(i, ...
[ "0.8100148", "0.773013", "0.76817036", "0.76695836", "0.7526487", "0.7413217", "0.72635025", "0.72520757", "0.7237255", "0.720597", "0.71226275", "0.7120114", "0.7059747", "0.7056286", "0.7044589", "0.70375097", "0.69336534", "0.69194335", "0.6913005", "0.6888755", "0.6846131...
0.6237683
47
transform tags for solr
def transform_tags(self, instance): return instance.tags.split(',')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _preprocess(self, tagged: List[Tuple]) -> Tuple:\n ori = \" \".join([tag[0] for tag in tagged])\n tags = [tag[1] for tag in tagged]\n # Mapping into general tagset\n tags = [self._map[tag] if tag in self._map else \"X\" for tag in tags]\n return \" \".join(tags), ori", "def...
[ "0.6342739", "0.62034404", "0.61902505", "0.61189127", "0.61091095", "0.60965765", "0.6026633", "0.59895706", "0.5947233", "0.5945939", "0.59207904", "0.58725727", "0.5865535", "0.5798255", "0.57310975", "0.5727268", "0.5669075", "0.56652087", "0.5649698", "0.5608626", "0.558...
0.6025879
7
get a model for solr
def transform_entity(self, instance, what): whats = [] for _what in instance.get_entity(what): whats.append(str(_what)) return whats
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_model(self):\n raise NotImplementedError(\n \"You must provide a 'get_model' method for the '%r' index.\" % self\n )", "def get_model(self):\n return QueryS", "def get_model():\n return UNISAL", "def get_model(self):\n url = self.resource()\n params = ...
[ "0.6687158", "0.64133453", "0.63109964", "0.62503785", "0.62141037", "0.61795294", "0.6167323", "0.61600643", "0.61600643", "0.61600643", "0.61600643", "0.61600643", "0.6062293", "0.6059364", "0.6059364", "0.6059364", "0.6059364", "0.6059364", "0.6059364", "0.6059364", "0.605...
0.0
-1
get people for solr
def transform_people(self, instance): return self.transform_entity(instance, 'Person')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def search_professors(search_term):\n print(\"Professor to search\", search_term)\n if search_term == \"\" or search_term is None:\n return json.dumps([])\n else:\n # pandas_index_list = elastic_dash.search_professors(search_term)\n pandas_index_list = elastic_dash.search_personnel(se...
[ "0.64752334", "0.6471866", "0.6469839", "0.6443082", "0.63948816", "0.63601685", "0.62068886", "0.61978406", "0.6176863", "0.61702245", "0.60960656", "0.6083975", "0.60412025", "0.602639", "0.60190237", "0.59710723", "0.59653676", "0.5906777", "0.58994013", "0.5892216", "0.58...
0.0
-1
get organisations for solr
def transform_organisations(self, instance): return self.transform_entity(instance, 'Organisation')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def organizations(self):\n return self.get('{}/orgs'.format(ApiVersion.A1.value))", "def get_org_list():\r\n\r\n resp = requests.get(''.join([Kegg.BASE_URL, 'list/organism']))\r\n return resp.text", "def organizations(self):\n self.elements('organizations')", "def list(self) -> List[O...
[ "0.70180196", "0.6930935", "0.68222815", "0.67474467", "0.66747344", "0.64471346", "0.6437008", "0.64310277", "0.63073766", "0.62133086", "0.6173378", "0.61321056", "0.61253846", "0.61062926", "0.6087762", "0.6074626", "0.60670793", "0.60509616", "0.60316247", "0.6012012", "0...
0.59292954
24
get places for solr
def transform_places(self, instance): return self.transform_entity(instance, 'Place')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_places():\n global app_id, rest_api_key, places\n\n if not places:\n connection = httplib.HTTPSConnection(PARSE_API_URL, PARSE_API_PORT)\n connection.connect()\n connection.request(\n method='GET',\n url=PLACES_ENDPOINT,\n headers={\"X-Parse-Application-Id\": app_id, \"X-Parse-...
[ "0.7075361", "0.6944823", "0.6674378", "0.6600828", "0.65889496", "0.65875274", "0.653786", "0.65263355", "0.64731616", "0.6373014", "0.6317828", "0.63092935", "0.63040537", "0.6248984", "0.62213624", "0.61126393", "0.61077696", "0.60606116", "0.6059774", "0.6050336", "0.6047...
0.0
-1
idAIV, EC, SC, PC, RV, OC, Total, FK_Organization, FK_Equipment
def loadAIVValues(self, values): #The 'values' variable has the following form if values[1] == values[2] == values[3] == values[4] == values[5] == 0.00: #wx.MessageBox("Es un total") self.aiv_totalok.SetValue(True) self.changeTextsInputs(True) self.aiv_total.SetValue(str(values[6])) else: self.changeTextsInputs(False) self.aiv_totalok.SetValue(False) #wx.MessageBox("Costos individuales") self.aiv_equipmentCost.SetValue(str(values[1])) self.aiv_serviceCost.SetValue(str(values[2])) self.aiv_personnelCost.SetValue(str(values[3])) self.aiv_resellCost.SetValue(str(values[4])) self.aiv_otherCost.SetValue(str(values[5])) self.aiv_total.SetValue(str(values[6]))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ItemDed(_posagi, e17500, e18400, e18500, e18800, e18900,\n e20500, e20400, e19200, e20550, e20600, e20950, e19500, e19570,\n e19400, e19550, e19800, e20100, e20200, e20900, e21000, e21010,\n MARS, _sep, c00100, ID_ps, ID_Medical_frt, ID_Casualty_frt,\n ID_Miscellaneo...
[ "0.5435056", "0.4894137", "0.48406047", "0.47943744", "0.47545114", "0.47482443", "0.4708286", "0.46779168", "0.4671095", "0.4662206", "0.4640695", "0.46324465", "0.45957166", "0.45863223", "0.45708844", "0.45649207", "0.45606184", "0.4560529", "0.4551793", "0.45511213", "0.4...
0.4452974
32
returns True if employee has rejoined otherwise False
def is_rejoinee(self): return len(self._start_date) > 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_employee():\n return _is_member('uw_employee')", "def is_expired(self):\n expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)\n return (self.date_joined + expiration_date <= datetime.datetime.now())", "def is_expired(self):\n expiration_date = datetime.tim...
[ "0.6680365", "0.587085", "0.58500487", "0.57760894", "0.5741819", "0.57230127", "0.56929135", "0.56781346", "0.56605685", "0.5577466", "0.55369276", "0.5530934", "0.55146056", "0.55014586", "0.54542553", "0.5392969", "0.5388207", "0.53847474", "0.5377452", "0.53713554", "0.53...
0.61320335
1
Process the Exit of employee
def process_employee_exit(self): if self.is_employee_serving(): self._end_date.append(datetime.now().isoformat()) print(f"Successfully processed exit for employee {self.name} on" \ f"{self._end_date[-1]}\nWe wish {self.name} for future endeavours") return raise RejoiningException("Employee not in service. Cannot process exit.")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def do_exit(self, args):\n return -1", "def identify_result_exit(self, record):\n return [\"exit\"]", "def exit(self):\n pass", "def _PExit(self, m):\n pass", "def user_exit(cls):\n cls.exit_program(ErrorCodes.E_USER_EXIT)", "def do_exit(self, line): \n sys.exit(0)...
[ "0.66456366", "0.66187525", "0.6506358", "0.64646137", "0.6454185", "0.6431671", "0.63921857", "0.63420844", "0.63289636", "0.6281149", "0.6274805", "0.6250398", "0.6227689", "0.6203884", "0.6194826", "0.6160062", "0.6157645", "0.61544615", "0.61414033", "0.6138231", "0.61304...
0.8065909
0
Check if growth results have expected no samples.
def has_nsamples(results, n): n_rates = results.growth_rates.sample_id.nunique() n_exchanges = results.exchanges.sample_id.nunique() return n_rates == n and n_exchanges == n
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def has_more_samples(self):\n return True", "def has_more_samples(self):\n return True", "def has_more_samples(self):\n return True", "def test_sufficient_statistics(self):\n assert (\n len(self.data),\n self.data.var(),\n self.data.mean(),\n ...
[ "0.7002155", "0.7002155", "0.7002155", "0.6810179", "0.6439376", "0.6349528", "0.6328535", "0.6269995", "0.62555325", "0.6226843", "0.6206803", "0.6174545", "0.61745423", "0.61745423", "0.61745423", "0.61745423", "0.61406535", "0.61071175", "0.6073733", "0.6044353", "0.604206...
0.63572603
5
Index page where I test few functions and make sure routes are connected
def test(): print "SERVER IS RUNNING" return render_template("statemap.html") # return render_template("testworld.html")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_main(self):\n path = reverse(\"main\")\n request = RequestFactory().get(path)\n response = index(request)\n assert response.status_code == 200", "def test_index_view(self):\n response = self.client.get(url_for('main.index'))\n self.assertEqual(response.status_co...
[ "0.77554923", "0.7587984", "0.7496175", "0.7468367", "0.7461118", "0.73280954", "0.72975385", "0.72921324", "0.72654486", "0.72471523", "0.724658", "0.724658", "0.72161573", "0.72141546", "0.71513706", "0.7143187", "0.7128356", "0.711231", "0.7095507", "0.7054877", "0.7005856...
0.0
-1
Log user into site, find user in the DB and their their user id in the session then if they are logged in redirect them to map page
def process_login(): # Get form variables email = request.form["email"] password = request.form["password"] # printing data from form to BASH print "form password" print password # check user exisit and then asign them variable user user = User.query.filter_by(email=email).first() print "\n \n \n ", user # Conditions if not user: flash("No such user") return redirect("/") elif user.password != password: flash("Incorrect password") return redirect("/") else: session["user_id"] = user.user_id flash("Logged in") return redirect('/passport')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def logininfo():\n\n email = request.form.get(\"email\")\n password = request.form.get(\"password\")\n\n user = User.query.filter_by(email=email).first()\n # import pdb; pdb.set_trace()\n if not user:\n return redirect(\"/register\")\n\n if user.password != password:\n flash('Invali...
[ "0.70838326", "0.69987136", "0.67759037", "0.67270076", "0.657737", "0.6569989", "0.6562039", "0.65591156", "0.6542138", "0.6500258", "0.6500258", "0.64939904", "0.6488533", "0.6474254", "0.647039", "0.6464649", "0.64607286", "0.6430233", "0.6424035", "0.64013207", "0.638578"...
0.6567707
6
removing user_id from session to logout user
def process_logout(): print " LOGGED OUT USER " del session["user_id"] flash("You have Successfully Logged Out!") return redirect("/")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def logout_user(session):\n del session['user']", "def logout():\n\n if session.get('user_id'):\n del session['user_id']\n flash('You are now logged out.')\n return redirect('/login')", "def logout(self):\n if 'user' in session:\n del session['user']\n session.sa...
[ "0.86715126", "0.81939507", "0.8084283", "0.8076383", "0.8072221", "0.80592704", "0.7940466", "0.792623", "0.7907761", "0.78814626", "0.78327316", "0.7786549", "0.7768795", "0.77528083", "0.7744378", "0.7737063", "0.7730634", "0.77184623", "0.7702954", "0.7678678", "0.7678678...
0.7882814
9
New user signup form
def register_processed(): print "REGISTER ROUTE IS WORKING" # Get variables from HTML form email = request.form["email"] password = request.form["password"] # query the DB for user new_user = User(email=email, password=password) # check DB for user searching by email same_email_user = User.query.filter(User.email == email).first() # users who registered / login will be redircted --> passport/profile pg. if same_email_user: flash("Email is already registered. Please signin to your account") return redirect("/") # check user by username --> condition to authentiate user same_username = User.query.filter(User.email == email).first() if same_username: flash("please pick another username") return redirect("/") # add user to db if they are new db.session.add(new_user) # commit transaction db.session.commit() # query db user by email add them to current session and redirect # user to passport page user = User.query.filter_by(email=email).first() flash("User %s added.You have successfully created an account! Welcome to Wanderlust" % email) session["user_id"] = user.user_id return redirect("/passport")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def signup_form(request):\n return {'signup_form': UserForm()}", "def signup():\n return render_template(\"new_user.html\")", "def signup():", "def signupview(request):\n if request.method != 'POST':\n # Display blank registration form\n form = UserCreationForm()\n else:\n # ...
[ "0.82840896", "0.82833594", "0.8074069", "0.79622245", "0.7919632", "0.7732329", "0.76864487", "0.7676215", "0.7661683", "0.7627001", "0.7598874", "0.7574743", "0.7571235", "0.7540624", "0.75386494", "0.75366706", "0.75335234", "0.75069493", "0.75018096", "0.7460415", "0.7452...
0.0
-1
wanderlist list interative list where users can add new items to their travel bucket list
def passport(): user_id = session['user_id'] # query users list items and load list items when user access passport page places = db.session.query(AdventureList.adventure_item).filter(AdventureList.user_id == user_id).all() # take users wanderlist and loads list items # create empty list bind list to variable name new_place_list new_place_list = [] # iterate over items and append them to empty list starting from index[0] for item in places: new_place_list.append(item[0]) print new_place_list return render_template('passport.html', places=new_place_list)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_new_item():\n\n lst = item_list()\n return render_template('index.html', sell_flag=1, items=lst)", "def NewItems(self) -> _n_1_t_7:", "def view_list():\n # an HTML representation of the user shopping list\n printed_list = user[\"name\"]\n printed_list += \"<form>\"\n printed_list += '...
[ "0.63726956", "0.5953915", "0.58900404", "0.56818676", "0.5578206", "0.5571558", "0.5569564", "0.55676425", "0.55432063", "0.5523418", "0.5523418", "0.55003536", "0.5476887", "0.5428944", "0.5371039", "0.53561133", "0.53371036", "0.53357625", "0.5332503", "0.53266263", "0.532...
0.54712594
13
user clicks on state, when color changes, state is stored as a visit.
def state_map(): # get current user from session user_id = session["user_id"] print user_id # inputs from state map in console.log [feature.id] = state_id feature = state state_id = request.form['feature_id'] print state_id state = db.session.query(State).filter_by(state_id=state_id).one() user_state_obj = User_State(state_id=state_id, user_id=user_id, visited_at=datetime.now()) db.session.add(user_state_obj) db.session.commit() user_state_json_data = {"state_id": state.state_id, "state_name": state.state_name, "visited_at": user_state_obj.visited_at} return jsonify(user_state_json_data) ################## REMOVING ##########################
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_click_state(self, event):\n raise NotImplementedError", "def select_action(self, state):", "def state_changed(self, oldstate, newstate, event, *args, **kwargs):", "def state_changed(self, oldstate, newstate, event, *args, **kwargs):", "def on_state_change(self, new_state):\n self.sta...
[ "0.63449645", "0.63005996", "0.62316686", "0.62316686", "0.6165384", "0.61550564", "0.608084", "0.6026097", "0.59596413", "0.5938203", "0.5936117", "0.59297", "0.5917869", "0.5911632", "0.5898261", "0.58883375", "0.5822766", "0.58192563", "0.57938737", "0.5782378", "0.5760959...
0.0
-1
delete function for removing state visit
def removeStateVisit(): user_id = session["user_id"] print user_id state_id = request.form.get('feature_id') state = db.session.query(State).filter_by(state_id=state_id).one() user_state_obj = db.session.query(User_State).filter(User_State.user_id == user_id, User_State.state_id == state_id).first() print user_state_obj user_state_json_data = "error" if user_state_obj: db.session.delete(user_state_obj) db.session.commit() user_state_json_data = {"state_id": state_id, "state_name": state.state_name, "visited_at": user_state_obj.visited_at} return jsonify(user_state_json_data) ################### LOAD USERS STATE VISITS #######################
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def delete_state(self, s):\n state = self.state(s)\n for transition in self.transitions():\n if transition.to_state == state:\n self.delete_transition(transition)\n self._states_.remove(state)\n try:\n del self._states_dict_[state.label()]\n e...
[ "0.7199102", "0.69216", "0.6769232", "0.6697931", "0.66519755", "0.663655", "0.6609245", "0.65962636", "0.659605", "0.6585508", "0.65570766", "0.65462", "0.65451986", "0.6523356", "0.65081394", "0.6460999", "0.64571273", "0.64526856", "0.63653034", "0.635942", "0.63002914", ...
0.6547938
11
RETURN user profile information
def profile(): user_id = session["user_id"] # from HTML form getting inputs from ajax call first = request.form.get('first', None) last = request.form.get('last', None) username = request.form.get('username', None) city = request.form.get('city', None) state = request.form.get('state', None) quote = request.form.get('quote', None) about = request.form.get('about', None) print "profile", first, last, city, state, quote, about # query db for current user user = db.session.query(User).filter_by(user_id=user_id).one() # ajax request inputs user.first_name = first user.last_name = last user.username = username user.city = city user.state = state user.quote = quote user.about = about db.session.commit() # profile_info_data = {"key": value} profile_info_data = {"first": first, "last": last, "username": username, "city": city, "state": state, "quote": quote, "about": about} # query DB for this user if the unser is none print "Profile been has been stored in DB" return jsonify(profile_info_data) # @app.route('/disply-profile-info', methods=['POST'])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_user_profile(self):\n return self.request('get', 'id/users')", "def get_profile():\n logger.debug(\"entering function get_profile\")\n response = read_user_profile()\n logger.debug(\"exiting function get_profile\")\n return jsonify(response)", "def user_info(self):\n response ...
[ "0.79147726", "0.76836777", "0.7588437", "0.7583951", "0.75469744", "0.7536266", "0.74995303", "0.74964917", "0.7494386", "0.7476675", "0.74665", "0.74247897", "0.7411005", "0.7400891", "0.73773926", "0.73690546", "0.7363023", "0.73458177", "0.73306763", "0.73088706", "0.7305...
0.67085403
100
google address form that prepopulates address
def google_postcard_form_ajax(): user_id = session["user_id"] # input from ajax call from HTML form street_number = request.form.get('street_number') route_address = request.form.get('route') city = request.form.get('locality') postal_code = request.form.get('postal_code') state = request.form.get("state") country = request.form.get('country') message = request.form.get('message', None) print "google-postcard-ajax", street_number, route_address, city, postal_code, state, country, message # commit form information to Database db.session.commit() postcard_data = {"street_number": street_number, "route": route_address, "city": city, "state": state, "country": country, "message": message} return jsonify(postcard_data)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_autofill_address():\n try:\n # get data sent by client\n client_data = request.get_json()\n print(' ')\n print('\\n------ getting autofill_address ------')\n print(f\"recived: input:{client_data['text']}\")\n\n place = gmaps.place(client_data['value'])\n ...
[ "0.63437706", "0.6269668", "0.6109527", "0.5922518", "0.5916802", "0.57907397", "0.57753795", "0.5754547", "0.57486415", "0.5744301", "0.57018614", "0.5698119", "0.5649869", "0.56383955", "0.559803", "0.55916196", "0.55846936", "0.55796117", "0.55482423", "0.554614", "0.55070...
0.0
-1
d3 state map where users can click on country and changes colors
def d3_world_map(): return render_template("world.html")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def states_traveled(person, color):\r\n folium.GeoJson(data=state_geo,\r\n name=person['Name'] + ' - '\r\n + str(len(person['States'])),\r\n style_function=state_style(person, color)\r\n ).add_to(us_map)", "def make_map(df):\n fig = px...
[ "0.6094421", "0.60562986", "0.600109", "0.58970064", "0.58948016", "0.57658577", "0.56608766", "0.5599893", "0.55898225", "0.552269", "0.5476184", "0.5427226", "0.53729886", "0.53549206", "0.5288607", "0.52129906", "0.52069104", "0.51814765", "0.51725775", "0.51422197", "0.50...
0.0
-1
state map where users can click on state and changes colors
def world_map(): # AJAX CALL FOR USER STATE VISIT # get current user from session user_id = session["user_id"] print user_id # inputs from state map in console.log [feature.id] = state_id feature = state country_id = request.form['mapData.id'] print country_id country = db.session.query(Country).filter_by(country_id=country_id).one() user_country_obj = User_Country(country_id=country_id, user_id=user_id, visited_at=datetime.now()) # TODO: make the object be added db.session.add(user_country_obj) db.session.commit() # # # TODO: query datbase for the information to go into this json user_country_json_data = {"country_id": country.country_id, "country_name": country.country_name, "visited_at": user_country_obj.visited_at} return jsonify(user_country_json_data)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_state(canvas, state):\n for key, value in state.items():\n set_attribute(canvas, key, value)", "def state_style(person, color):\r\n return lambda x: {'fillColor': color if x['id']\r\n in person['States'] else 'white',\r\n 'color': 'black',\r\n ...
[ "0.6322096", "0.6314533", "0.62529945", "0.61717737", "0.6053243", "0.5946069", "0.583432", "0.582224", "0.58115244", "0.58107173", "0.57522345", "0.5743763", "0.5738496", "0.57296467", "0.5709835", "0.56997746", "0.56476825", "0.56447077", "0.55822253", "0.5581793", "0.55771...
0.0
-1
Takes a full media url from Bandwidth and extracts the media id
def get_media_id(media_url): split_url = media_url.split("/") #Media urls of the format https://messaging.bandwidth.com/api/v2/users/123/media/file.png if split_url[-2] == "media": return split_url[-1] #Media urls of the format https://messaging.bandwidth.com/api/v2/users/123/media/abc/0/file.png else: #This is required for now due to the SDK parsing out the `/`s return "%2F".join(split_url[-3:])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def media_id(self):\n try:\n return Html.toId(self.content)\n except:\n Mp3Error(1)", "def _id_from_url(url):\n url = re.sub(r'\\?.*', '', url)\n video_id = url.split('/')[-2]\n return video_id", "def media_content_id(self):\n return self._media_u...
[ "0.65878916", "0.6518125", "0.6397448", "0.6382529", "0.61623603", "0.61505437", "0.6048567", "0.60049254", "0.60015476", "0.5999453", "0.5963927", "0.5951866", "0.59363306", "0.59259576", "0.59230775", "0.5900245", "0.5842724", "0.5811348", "0.57866263", "0.5779499", "0.5772...
0.79839915
0
Takes a full media url from Bandwidth and extracts the filename
def get_media_filename(media_url): return media_url.split("/")[-1]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_file_path(self, url):\n try:\n row = ET.fromstring(self._session.get(url, headers={\"Access-Token\":self._token}).text)[1][2][1]\n data = [row[1].text, row[1].text, row[2].text]\n if \" - S\" in data[0]:\n data[0] = data[0][0:data[1].rfind(\" - S\")]\...
[ "0.7303174", "0.70052874", "0.68807364", "0.67521065", "0.67236215", "0.66535795", "0.661498", "0.6603966", "0.6586546", "0.6538387", "0.6509765", "0.64932483", "0.64535576", "0.6430052", "0.638914", "0.63559645", "0.6279012", "0.62202466", "0.6168988", "0.61595553", "0.60698...
0.7981755
0
Takes a list of media urls and downloads the media into the temporary storage
def download_media_from_bandwidth(media_urls): downloaded_media_files = [] for media_url in media_urls: media_id = get_media_id(media_url) filename = get_media_filename(media_url) with open(filename, "wb") as f: try: downloaded_media = messaging_client.get_media(MESSAGING_ACCOUNT_ID, media_id) f.write(downloaded_media.body) except Exception as e: print(e) downloaded_media_files.append(filename) return downloaded_media_files
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def downloadLocal(url_list,path):\n print(\"You are downloading {} images\".format(parser_arguments().limit),end=\" \");print(\"of {} class.\".format(parser_arguments().classes))\n print(\"Please, be patient :)\")\n for i in range(len(url_list)):\n filename= url_list[i].split(\"/\")[-1] # name of t...
[ "0.66829646", "0.6647512", "0.6639991", "0.6638432", "0.66363764", "0.6452788", "0.6394921", "0.63525635", "0.6312523", "0.6243412", "0.6240311", "0.61974305", "0.6190884", "0.61289537", "0.6114882", "0.6058402", "0.6052626", "0.6050897", "0.59977293", "0.5993598", "0.5966962...
0.75554264
0
Takes a list of media files and uploads them to Bandwidth The media file names are used as the media id
def upload_media_to_bandwidth(media_files): for filename in media_files: with open(filename, "rb") as f: file_content = f.read() try: ##Note: The filename is doubling as the media id## response = messaging_client.upload_media(MESSAGING_ACCOUNT_ID, filename, str(len(file_content)), body=file_content) except Exception as e: print(e)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def upload_files(self, files):\n\n for f in files:\n self.scp.put(f, recursive=True)", "def upload(self, folder_list, files):\n current_folder_id = self.top_folder_id\n for fname in folder_list:\n current_folder_id = self._fetch_or_create_folder(fname, current_folder_id)\n for fil...
[ "0.619183", "0.60925543", "0.6053126", "0.5934323", "0.59186196", "0.57231236", "0.5704533", "0.57031876", "0.57009745", "0.56800365", "0.5639666", "0.5630675", "0.56029576", "0.56010246", "0.55941606", "0.5494556", "0.54650325", "0.54639095", "0.5461023", "0.5386679", "0.536...
0.8371117
0
Removes all of the given files
def remove_files(files): for file_name in files: os.remove(file_name)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_files(self, files: Set[str]) -> None:\n for f in files:\n src = os.path.join(self.get_directory(), f)\n os.remove(src)", "def clean(files):\n\tfor file in files:\n\t\ttry:\n\t\t\tos.remove(file)\n\t\texcept Exception as e:\n\t\t\tprint(e)", "def remove_files(file_list):\...
[ "0.8326417", "0.8259835", "0.7764254", "0.7697654", "0.76045775", "0.76031864", "0.7492463", "0.7479637", "0.7377181", "0.73686516", "0.7330737", "0.7330138", "0.7317665", "0.7217544", "0.72154135", "0.720359", "0.719617", "0.71945643", "0.71943825", "0.71901155", "0.71693027...
0.8486456
0
Takes information from a Bandwidth inbound message callback that includes media and responds with a text message containing the same media sent through Bandwidth's media resource.
def handle_inbound_media_mms(to, from_, media): downloaded_media_files = download_media_from_bandwidth(media) upload_media_to_bandwidth(downloaded_media_files) remove_files(downloaded_media_files) body = MessageRequest() body.application_id = MESSAGING_APPLICATION_ID body.to = [from_] body.mfrom = to body.text = "Rebound!" #Build the media URL by taking the media ids (that doubled as the file names) and appending them to #the bandwidth media base url body.media = [BANDWIDTH_MEDIA_BASE_ENDPOINT + media_file for media_file in downloaded_media_files] try: messaging_client.create_message(MESSAGING_ACCOUNT_ID, body) except Exception as e: print(e) return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handle_inbound_message():\n data = json.loads(request.data)\n\n if data[0][\"type\"] == \"message-received\":\n if \"call me\" in data[0][\"message\"][\"text\"]:\n handle_inbound_sms_call_me(data[0][\"message\"][\"to\"][0], data[0][\"message\"][\"from\"])\n elif \"media\" in data...
[ "0.6259964", "0.6026629", "0.586778", "0.5793742", "0.5789032", "0.5778347", "0.56937456", "0.56709975", "0.5563751", "0.55476165", "0.5544929", "0.5535647", "0.55325127", "0.55144805", "0.55017763", "0.5446944", "0.5444091", "0.5428671", "0.5415789", "0.54080504", "0.5401289...
0.68463576
0
Take information from a Bandwidth inbound message callback and responds with a text message with the current date and time
def handle_inbound_sms(to, from_): body = MessageRequest() body.application_id = MESSAGING_APPLICATION_ID body.to = [from_] body.mfrom = to body.text = "The current date-time is: " + str(time.time() * 1000) + " milliseconds since the epoch" try: messaging_client.create_message(MESSAGING_ACCOUNT_ID, body) except Exception as e: print(e) return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main(connection, info, conf) :\r\n connection.rawsend(\"NOTICE %s :\u0001TIME %s\u0001\\n\" % (info[\"sender\"], time.strftime(\"%b %d %Y, %H:%M:%S %Z\")))", "def bitfinex2_on_message(caller, msg):\n msg = json.loads(msg)\n if caller.subbed_count == 7:\n if msg[1] == \"te\":\n chnl...
[ "0.6424744", "0.63330656", "0.6156469", "0.5986524", "0.5985888", "0.5976923", "0.59701186", "0.59519804", "0.58698654", "0.58497447", "0.5847021", "0.5816966", "0.57789177", "0.5738842", "0.5738044", "0.5738044", "0.5737132", "0.57114446", "0.5695387", "0.5639442", "0.563712...
0.5533975
30
Takes information from a Bandwidth inbound message callback and initiates a call
def handle_inbound_sms_call_me(to, from_): handle_call_me(to, from_)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def on_call(message, client):\n pass", "def _call(self, msg, cb, *args):\r\n if not self._status:\r\n raise InterfaceDisabledError('A disabled interface should not be '\r\n 'called.')\r\n\r\n if not callable(cb):\r\n raise T...
[ "0.63667405", "0.60182863", "0.59576505", "0.59576505", "0.59211445", "0.589763", "0.589763", "0.589763", "0.5851596", "0.5813852", "0.5791376", "0.57506865", "0.57401466", "0.5735596", "0.5733125", "0.57320815", "0.571448", "0.5710372", "0.570059", "0.5682062", "0.5653709", ...
0.62250584
1
A method for showing how to handle Bandwidth messaging callbacks. For inbound SMS that contains the phrase "call me", a phone call is made and the user is asked to forward the call to another number For inbound SMS that doesn't contain the phrase "call me", the response is a SMS with the date and time. For inbound MMS with a media attachment, the response is the same media attachment sent through Bandwidth's media resource. For all other events, the callback is logged to console
def handle_inbound_message(): data = json.loads(request.data) if data[0]["type"] == "message-received": if "call me" in data[0]["message"]["text"]: handle_inbound_sms_call_me(data[0]["message"]["to"][0], data[0]["message"]["from"]) elif "media" in data[0]["message"]: handle_inbound_media_mms(data[0]["message"]["to"][0], data[0]["message"]["from"], data[0]["message"]["media"]) else: handle_inbound_sms(data[0]["message"]["to"][0], data[0]["message"]["from"]) else: print(data) return ""
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handle_inbound_sms_call_me(to, from_):\n handle_call_me(to, from_)", "def handle_inbound_media_mms(to, from_, media):\n downloaded_media_files = download_media_from_bandwidth(media)\n upload_media_to_bandwidth(downloaded_media_files)\n remove_files(downloaded_media_files)\n body = MessageReque...
[ "0.6835022", "0.60718656", "0.59854895", "0.59607", "0.5945775", "0.5932107", "0.5932107", "0.5917332", "0.5839464", "0.5817131", "0.5794533", "0.574719", "0.5722084", "0.5713493", "0.57134485", "0.5699287", "0.5698061", "0.56944233", "0.5692819", "0.5692426", "0.56885827", ...
0.6912686
0
Formats |record| with color.
def format(self, record): msg = super(ColoredFormatter, self).format(record) color = self._COLOR_MAPPING.get(record.levelname) if self._use_colors and color: msg = '%s%s%s' % (color, msg, self._RESET) return msg
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def format(self, record):\n\n\t\t# Use copy.copy - c.f. https://stackoverflow.com/a/7961390\n\t\tcolored_record = copy.copy(record)\n\n\t\tcolor = None\n\t\ttry:\n\t\t\tcolor = record.color\n\t\texcept AttributeError as e:\n\t\t\tpass\n\n\t\tif color is not None:\n\t\t\tif color is None or not color or color == \"...
[ "0.8311548", "0.7502058", "0.74881405", "0.7452882", "0.7222441", "0.7179237", "0.7129312", "0.70246935", "0.6647282", "0.6643303", "0.6622566", "0.6554629", "0.6488578", "0.64701414", "0.64188516", "0.6313016", "0.6285745", "0.61440796", "0.59593135", "0.59322673", "0.592492...
0.76215637
1
Setup the logging module.
def setup_logging(debug=False, quiet=0): fmt = '%(asctime)s: %(levelname)-7s: ' if debug: fmt += '%(filename)s:%(funcName)s: ' fmt += '%(message)s' # 'Sat, 05 Oct 2013 18:58:50 -0400 (EST)' datefmt = '%a, %d %b %Y %H:%M:%S %z' tzname = time.strftime('%Z', time.localtime()) if tzname and ' ' not in tzname and len(tzname) <= 5: # If the name is verbose, don't include it. Some systems like to use # "Eastern Daylight Time" which is much too chatty. datefmt += f' ({tzname})' if debug: level = logging.DEBUG elif quiet <= 0: level = logging.INFO elif quiet <= 1: level = logging.WARNING elif quiet <= 2: level = logging.ERROR elif quiet <= 3: level = logging.CRITICAL formatter = ColoredFormatter(fmt, datefmt) handler = logging.StreamHandler(stream=sys.stdout) handler.setFormatter(formatter) logger = logging.getLogger() logger.addHandler(handler) logger.setLevel(level)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __setup_logging(self):\n\n loglevel = logging.INFO\n if self.config[\"verbose\"]:\n loglevel = logging.DEBUG\n\n FORMAT = '[%(asctime)s %(filename)s:%(lineno)s %(levelname)s] %(message)s'\n if self.config[\"log\"]:\n logging.basicConfig(format=FORMAT, level=log...
[ "0.8276232", "0.8171842", "0.7997143", "0.79586464", "0.7953245", "0.7951404", "0.79431313", "0.787981", "0.78718454", "0.7863005", "0.785225", "0.7807847", "0.7795416", "0.77918327", "0.77759767", "0.77299064", "0.77242017", "0.7685312", "0.76751614", "0.7672853", "0.7662601...
0.0
-1
Parse all the |args| and save the results to |namespace|.
def parse_args(self, args=None, namespace=None): # This will call our parse_known_args below, so don't use setup_logging. namespace = argparse.ArgumentParser.parse_args( self, args=args, namespace=namespace) return namespace
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse(self, args):\n pass", "def parse_arguments(args):", "def parse_args(self, args: List[str]) -> Namespace:\n parser = self._to_parser()\n args = parser.parse_args(args)\n if hasattr(args, 'dm_commands'):\n if args.dm_commands is not None:\n args.dm_...
[ "0.72242314", "0.70827246", "0.7079136", "0.6844468", "0.684225", "0.678038", "0.6626821", "0.65809435", "0.65164214", "0.6471258", "0.64519733", "0.64393944", "0.64139444", "0.63585967", "0.631252", "0.62846994", "0.62844545", "0.6282284", "0.6273448", "0.6238388", "0.620952...
0.70003927
3
Parse all the |args| and save the results to |namespace|.
def parse_known_args(self, args=None, namespace=None): namespace, unknown_args = argparse.ArgumentParser.parse_known_args( self, args=args, namespace=namespace) setup_logging(debug=namespace.debug, quiet=namespace.quiet) return (namespace, unknown_args)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse(self, args):\n pass", "def parse_arguments(args):", "def parse_args(self, args: List[str]) -> Namespace:\n parser = self._to_parser()\n args = parser.parse_args(args)\n if hasattr(args, 'dm_commands'):\n if args.dm_commands is not None:\n args.dm_...
[ "0.72235036", "0.70820785", "0.70796216", "0.70001507", "0.68445134", "0.6841379", "0.67815137", "0.6625614", "0.65816057", "0.65165967", "0.64699036", "0.64527774", "0.643961", "0.64133555", "0.6358838", "0.62851185", "0.62849003", "0.62825257", "0.6272746", "0.6238674", "0....
0.6311945
15
Add our custom/consistent set of command line flags.
def add_common_arguments(self, short_options=True): getopts = lambda *args: args if short_options else args[1:] self.add_argument(*getopts('-d', '--debug'), action='store_true', help='Run with debug output.') self.add_argument(*getopts('-q', '--quiet'), action='count', default=0, help='Use once to hide info messages, twice to hide ' 'warnings, and thrice to hide errors.')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def AddFlags(arg_parser):\n common_flags.DefineAppsDomainFlagWithDefault(arg_parser)\n common_flags.DefineVerboseFlagWithDefaultFalse(arg_parser)\n\n arg_parser.add_argument(\n '--long_list', '-l', action='store_true', default=False,\n help='Show more columns of output.')\n arg_parser.add_argument(\n...
[ "0.6911403", "0.6741382", "0.6687998", "0.65631276", "0.6552243", "0.65478307", "0.6540075", "0.65375626", "0.6467081", "0.64280957", "0.6374949", "0.6354658", "0.6335308", "0.633125", "0.6321641", "0.6318687", "0.63147134", "0.6310211", "0.6308138", "0.62982756", "0.625911",...
0.5957892
47
Touch (and truncate) |path|.
def touch(path): open(path, 'wb').close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def touch(path: str) -> None:\n Stat.forget(path)\n os.utime(path)", "def touch(path):\n fd = open(path, 'a')\n fd.close()", "def Touch(path, makedirs=False):\n if makedirs:\n SafeMakedirs(os.path.dirname(path))\n\n # Create the file if nonexistant.\n open(path, 'a').close()\n # Upda...
[ "0.7507206", "0.7477994", "0.7407964", "0.7295061", "0.7234373", "0.7213623", "0.7138664", "0.7133505", "0.6832273", "0.6770861", "0.6743686", "0.6636576", "0.6419507", "0.6384915", "0.6220418", "0.601276", "0.5957383", "0.5900866", "0.5870614", "0.5842674", "0.5808397", "0...
0.7130963
8
Remove |path| and ignore errors if it doesn't exist.
def unlink(path): try: os.unlink(path) except FileNotFoundError: pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove(path):\n try:\n os.remove(path)\n except FileNotFoundError:\n _logger.error('file does not exist %s; stack: %s', path, stack_trace())", "def remove(path):", "def remove(path: str) -> None:\n if Stat.isfile(path):\n Stat.forget(path)\n os.remove(path)\...
[ "0.80879766", "0.79950017", "0.79609793", "0.7946199", "0.7846539", "0.77772456", "0.77729934", "0.7742355", "0.7642514", "0.76163965", "0.7585357", "0.74620676", "0.74620676", "0.74493706", "0.7417251", "0.7417251", "0.7414736", "0.7359514", "0.7351339", "0.7341862", "0.7340...
0.7559851
11
Always symlink |path| to a relativized |target|.
def symlink(target, path): unlink(path) path = os.path.realpath(path) target = os.path.relpath(os.path.realpath(target), os.path.dirname(path)) logging.info('Symlinking %s -> %s', path, target) os.symlink(target, path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def symlink(path, v=False):\r\n if not os.path.exists(path):\r\n err(path + ' : no such file or directory')\r\n elif not os.path.isdir(path):\r\n err(path + ' : not a directory')\r\n else:\r\n theme_name = os.path.basename(os.path.normpath(path))\r\n theme_path = os.path.join(_...
[ "0.7404254", "0.7402173", "0.7312787", "0.72121716", "0.7204278", "0.71373194", "0.71331364", "0.71290386", "0.71224445", "0.70757365", "0.69786334", "0.69786334", "0.69290304", "0.68298745", "0.6800475", "0.6755648", "0.67269856", "0.67166317", "0.6690445", "0.66393733", "0....
0.8573706
0
Return a string for the |cmd| list w/reasonable quoting.
def cmdstr(cmd): if isinstance(cmd, str): return cmd quoted = [] for arg in cmd: if isinstance(arg, Path): arg = str(arg) if ' ' in arg: arg = '"%s"' % (arg,) quoted.append(arg) return ' '.join(quoted)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cmdify(self):\n return \" \".join(\n itertools.chain(\n [_quote_if_contains(self.command, r\"[\\s^()]\")],\n (_quote_if_contains(arg, r\"[\\s^]\") for arg in self.args),\n )\n )", "def command_list_to_str(command):\n return \" \".join(pipes...
[ "0.7206458", "0.7059188", "0.6501883", "0.6480349", "0.6454796", "0.6273626", "0.6229917", "0.620037", "0.61765164", "0.6134786", "0.610084", "0.6098873", "0.60828114", "0.6048522", "0.6045765", "0.602606", "0.6023066", "0.6018371", "0.5999344", "0.59954375", "0.59915906", ...
0.67177594
2
Run |cmd| inside of |cwd| and exit if it fails.
def run(cmd: List[str], cmd_prefix: List[str] = None, log_prefix: List[str] = None, check: bool = True, cwd: str = None, extra_env: Dict[str, str] = None, **kwargs): # Python 3.6 doesn't support capture_output. if sys.version_info < (3, 7): capture_output = kwargs.pop('capture_output', None) if capture_output: assert 'stdout' not in kwargs and 'stderr' not in kwargs kwargs['stdout'] = subprocess.PIPE kwargs['stderr'] = subprocess.PIPE # The |env| setting specifies the entire environment, so we need to manually # merge our |extra_env| settings into it before passing it along. if extra_env is not None: env = kwargs.pop('env', os.environ) env = env.copy() env.update(extra_env) kwargs['env'] = env if not log_prefix: log_prefix = [] log_cmd = log_prefix + cmd if not cmd_prefix: cmd_prefix = [] real_cmd = cmd_prefix + cmd if cwd is None: cwd = os.getcwd() logging.info('Running: %s\n (cwd = %s)', cmdstr(log_cmd), cwd) if cmd_prefix: logging.debug('Real full command: %s', cmdstr(real_cmd)) result = subprocess.run(real_cmd, cwd=cwd, check=False, **kwargs) if check and result.returncode: logging.error('Running %s failed!', log_cmd[0]) if result.stdout is not None: logging.error('stdout:\n%s', result.stdout) if result.stderr is not None: logging.error('stderr:\n%s', result.stderr) sys.exit(result.returncode) return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run_cmd(self, cmd, cwd=None):\n logging.debug('Running %s', cmd)\n proc = subprocess.Popen(\n cmd,\n cwd=cwd or self._app_dir,\n stdout=subprocess.PIPE)\n output, _ = proc.communicate()\n if proc.returncode:\n sys.stderr.write('\\n' + output + '\\n')\n raise subproces...
[ "0.72233146", "0.714203", "0.7020301", "0.6959047", "0.6955779", "0.69045275", "0.6902057", "0.67949283", "0.67763764", "0.6725198", "0.6682631", "0.6600782", "0.6563511", "0.6562186", "0.6558308", "0.65555507", "0.65034527", "0.649164", "0.6484016", "0.6430076", "0.6378891",...
0.6026382
47
Return sha256 hex digest of |path|.
def sha256(path: Union[Path, str]) -> str: # The file shouldn't be too big to load into memory, so be lazy. with open(path, 'rb') as fp: data = fp.read() m = hashlib.sha256() m.update(data) return m.hexdigest()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_hash(path: Path) -> str:\n m = hashlib.sha256()\n m.update(path.read_bytes())\n return m.hexdigest()", "def _get_hash(self, path):\n with open(path, \"r\") as fp:\n content = fp.read()\n\n return sha256(content).hexdigest()", "def hash_of_file(path):\n with open(pat...
[ "0.84448147", "0.7994854", "0.7628011", "0.7436823", "0.73758745", "0.72930205", "0.72381604", "0.7233479", "0.72159195", "0.70954305", "0.70228964", "0.69657105", "0.695293", "0.6945403", "0.69420445", "0.6941568", "0.6924218", "0.68792206", "0.68724394", "0.68499297", "0.68...
0.83290803
1
Unpack |archive| into |cwd|.
def unpack(archive: Union[Path, str], cwd: Optional[Path] = None, files: Optional[List[Union[Path, str]]] = ()): archive = Path(archive) if cwd is None: cwd = Path.cwd() if files: files = ['--'] + list(files) else: files = [] # Try to make symlink usage easier in Windows. extra_env = { 'MSYS': 'winsymlinks:nativestrict', } logging.info('Unpacking %s', archive.name) # We use relpath here to help out tar on platforms where it doesn't like # paths with colons in them (e.g. Windows). We have to construct the full # before running through relpath as relative archives will implicitly be # checked against os.getcwd rather than the explicit cwd. src = os.path.relpath(cwd / archive, cwd) run(['tar', '--no-same-owner', '-xf', src] + files, cwd=cwd, extra_env=extra_env)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _unpack_archive(self):\n with zipfile.ZipFile(self._archive_full_path, 'r') as zip_ref:\n zip_ref.extractall(self._storage_path)\n\n _logger.debug('Archive has been unpacked.')", "def unpack_dir(indir, outdir, bands=None, clouds=None):\r\n archives = glob.glob(indir + '*.tar.gz')\...
[ "0.72888505", "0.6926044", "0.6809945", "0.6746972", "0.6636526", "0.65584207", "0.6507182", "0.6496216", "0.6464963", "0.6461252", "0.64201564", "0.63850856", "0.6347677", "0.63212836", "0.6308422", "0.6223524", "0.6171321", "0.61497027", "0.61496353", "0.614074", "0.6140402...
0.7522544
0
Create an |archive| with |paths| in |cwd|. The output will use XZ compression.
def pack(archive: Union[Path, str], paths: List[Union[Path, str]], cwd: Optional[Path] = None, exclude: Optional[List[Union[Path, str]]] = ()): archive = Path(archive) if cwd is None: cwd = Path.cwd() if archive.suffix == '.xz': archive = archive.with_suffix('') # Make sure all the paths have sane permissions. def walk(path): if path.is_symlink(): return elif path.is_dir(): # All dirs should be 755. mode = path.stat().st_mode & 0o777 if mode != 0o755: path.chmod(0o755) for subpath in path.glob('*'): walk(subpath) elif path.is_file(): # All scripts should be 755 while other files should be 644. mode = path.stat().st_mode & 0o777 if mode in (0o755, 0o644): return if mode & 0o111: path.chmod(0o755) else: path.chmod(0o644) else: raise ValueError(f'{path}: unknown file type') logging.info('Forcing sane permissions on inputs') for path in paths: walk(cwd / path) logging.info('Creating %s tarball', archive.name) # We use relpath here to help out tar on platforms where it doesn't like # paths with colons in them (e.g. Windows). We have to construct the full # before running through relpath as relative archives will implicitly be # checked against os.getcwd rather than the explicit cwd. tar = os.path.relpath(cwd / archive, cwd) run(['tar', '--owner=0', '--group=0', '-cf', tar] + [f'--exclude={x}' for x in exclude] + ['--'] + paths, cwd=cwd) logging.info('Compressing tarball') run(['xz', '-f', '-T0', '-9', tar], cwd=cwd)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_archive_file(location, paths, environment=None, compression=None, archive_format=None):\n if archive_format == 'zip':\n archive = ZipTarWrapper(location.name, 'w', zipfile.ZIP_DEFLATED)\n else:\n write_type = \"w\"\n if compression:\n write_type = \"w|{0}\".format...
[ "0.6538356", "0.6479174", "0.64458525", "0.6059645", "0.6056643", "0.5963025", "0.596087", "0.5931735", "0.5828145", "0.5716116", "0.57026917", "0.56945693", "0.56655836", "0.5658968", "0.5611987", "0.5595439", "0.5587479", "0.5581423", "0.55702585", "0.5558787", "0.5543491",...
0.720668
0
Fetch |uri| and write the results to |output| (or return BytesIO).
def fetch_data(uri: str, output=None, verbose: bool = False, b64: bool = False): # This is the timeout used on each blocking operation, not the entire # life of the connection. So it's used for initial urlopen and for each # read attempt (which may be partial reads). 5 minutes should be fine. TIMEOUT = 5 * 60 if output is None: output = io.BytesIO() try: with urllib.request.urlopen(uri, timeout=TIMEOUT) as infp: mb = 0 length = infp.length while True: data = infp.read(1024 * 1024) if not data: break # Show a simple progress bar if the user is interactive. if verbose: mb += 1 print('~%i MiB downloaded' % (mb,), end='') if length: percent = mb * 1024 * 1024 * 100 / length print(' (%.2f%%)' % (percent,), end='') print('\r', end='', flush=True) if b64: data = base64.b64decode(data) output.write(data) except urllib.error.HTTPError as e: logging.error('%s: %s', uri, e) sys.exit(1) return output
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fetch(uri, output, b64=False):\n output = os.path.abspath(output)\n distdir, name = os.path.split(output)\n if os.path.exists(output):\n logging.info('Using existing download: %s', name)\n return\n\n logging.info('Downloading %s to %s', uri, output)\n os.makedirs(distdir, exist_ok=...
[ "0.6911675", "0.6535504", "0.6211069", "0.60043406", "0.59758717", "0.58903176", "0.5829563", "0.5752656", "0.57295847", "0.5723706", "0.57197624", "0.5693564", "0.5693242", "0.56680185", "0.5658385", "0.56308764", "0.5616187", "0.5565478", "0.5563205", "0.5561096", "0.554989...
0.7404381
0
Download |uri| and save it to |output|.
def fetch(uri, output, b64=False): output = os.path.abspath(output) distdir, name = os.path.split(output) if os.path.exists(output): logging.info('Using existing download: %s', name) return logging.info('Downloading %s to %s', uri, output) os.makedirs(distdir, exist_ok=True) # Use kokoro build cache or Gentoo distdir if available. for envvar in ('KOKORO_GFILE_DIR', 'DISTDIR'): cache_dir = os.getenv(envvar) if cache_dir: cache_file = os.path.join(cache_dir, name) if os.path.exists(cache_file): logging.info(' Cache hit via %s', envvar) symlink(cache_file, output) return # Don't be verbose if running on CI systems. verbose = os.isatty(sys.stdout.fileno()) # We use urllib rather than wget or curl to avoid external utils & libs. # This seems to be good enough for our needs. tmpfile = output + '.tmp' for _ in range(0, 5): try: with open(tmpfile, 'wb') as outfp: fetch_data(uri, outfp, verbose=verbose, b64=b64) break except ConnectionError as e: time.sleep(1) logging.warning('Download failed; retrying: %s', e) else: logging.error('Unabled to download; giving up') unlink(tmpfile) sys.exit(1) # Clear the progress bar. if verbose: print(' ' * 80, end='\r') os.rename(tmpfile, output)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def download_img(self, url, output):\n try:\n print(\"Downloading from: %s\" % url)\n with open(output, 'wb') as f:\n f.write(urllib2.urlopen(url).read())\n print(\"Wrote to: %s\" % output)\n except IOError, e:\n print(e)", "def download(se...
[ "0.75725585", "0.7476779", "0.74181694", "0.7360501", "0.73380905", "0.7268354", "0.72478145", "0.71812546", "0.7168818", "0.70615435", "0.7010822", "0.69799095", "0.696379", "0.69605494", "0.6942747", "0.6924495", "0.69024444", "0.68827945", "0.6880968", "0.6865058", "0.6858...
0.7142565
9
Download our copies of node & npm to our tree and updates env ($PATH).
def node_and_npm_setup(): # We have to update modules first as it'll nuke the dir node lives under. node.modules_update() node.update()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_requirements():\n with cd(REMOTE_REPO_DIR):\n cmd = ['npm install']\n # cmd += ['--requirement %s' % os.path.join(CODE_DIR,'requirements.txt')]\n run(' '.join(cmd))", "def InstallNodeDependencies():\n logging.info('entering ...')\n # Install the project dependencies specifie...
[ "0.6407233", "0.63381755", "0.6324544", "0.6251576", "0.6231938", "0.6057195", "0.5836138", "0.5828892", "0.5789863", "0.5718106", "0.56944567", "0.56539077", "0.5616942", "0.5609459", "0.5526702", "0.5480729", "0.5467356", "0.54643357", "0.5417278", "0.5364148", "0.53312916"...
0.7617056
0
Load a module from the filesystem.
def load_module(name, path): loader = importlib.machinery.SourceFileLoader(name, path) module = types.ModuleType(loader.name) loader.exec_module(module) return module
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_module(module_name: str, module_path: str) -> object:\n spec = module_util.spec_from_file_location(module_name, module_path)\n module = module_util.module_from_spec(spec)\n spec.loader.exec_module(module) # type: ignore\n return module", "def load_module(path):\n spec = spec_from_file_location(\"...
[ "0.7140824", "0.7115812", "0.7082071", "0.7029506", "0.7029197", "0.6992073", "0.6935706", "0.6864377", "0.6848782", "0.6841059", "0.68201846", "0.6806607", "0.67745715", "0.6732326", "0.6725582", "0.6686308", "0.6678542", "0.6671717", "0.6595986", "0.6595986", "0.6583503", ...
0.74431866
0
Load & cache the program module.
def _module(self): if self._module_cache is None: self._module_cache = load_module(self._name, self._path) return self._module_cache
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load(self):\n\n\t\tif self.module is None:\n\t\t\t# Cause the interpreter to load the module in local namespace ...\n\t\t\texec \"import \" + self.name\n\n\t\t\t# Store the module object ...\n\t\t\tobject.__setattr__(self, 'module', eval(self.name))", "def load(self):\n \"\"\"Load a program into memor...
[ "0.64689153", "0.63654965", "0.62676257", "0.62425035", "0.62108284", "0.62063473", "0.61392486", "0.6114491", "0.602539", "0.60204077", "0.60017616", "0.59714663", "0.588076", "0.5877579", "0.58205396", "0.5767681", "0.5746382", "0.57439184", "0.57372934", "0.5737229", "0.57...
0.6589164
0
Dynamic forwarder to module members.
def __getattr__(self, name): return getattr(self._module, name)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def forward(self,input):\n\t\traise RuntimeError(\"All subclasses of Module must implement a forward method\")", "def forward(self, X):\n res = X\n for i, module in enumerate(self.modules):\n res = module.forward(res)\n\n return res", "def forward(self, x):\n result = x\n...
[ "0.61396086", "0.6047265", "0.6046735", "0.5913129", "0.5799977", "0.5715483", "0.5634315", "0.5634315", "0.5568903", "0.5568903", "0.5526504", "0.5521884", "0.5437717", "0.5414434", "0.5402117", "0.54014426", "0.53860456", "0.5361227", "0.52834386", "0.5244702", "0.5238629",...
0.0
-1
Set the packet length.
def _set_packet_len(self, packet_len): self._packet_len = packet_len
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setPacketLength(self):\n self.packetLength = len(self) - PRIMARY_HEADER_BYTE_SIZE - 1", "def setLength(self, new_length):\n\n self.length = new_length", "def length(self, length):\n\n self._length = length", "def set_length(self, ak_tpl: BKT, newLength: float): # -> None:\n ...", ...
[ "0.7967779", "0.7632073", "0.72674304", "0.7185319", "0.7084449", "0.70364594", "0.6882304", "0.66527474", "0.6593729", "0.6497038", "0.64803594", "0.6373639", "0.63581616", "0.63335747", "0.6284977", "0.6236442", "0.6221398", "0.6134403", "0.6132038", "0.6003637", "0.597266"...
0.8634613
0
Increment control counter for flow control of Ethernet traffic.
def update_control(self): self._control_ctr += 0x01
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def increment_counter(self) -> None:", "def increment_etherscan_calls():\n _increment_counter(\"etherscan_calls\")", "def inc(self):\n \n self.count += 1", "def inc( self ):\n self.count += 1", "def _inc_counter(self) -> None:\n self._state_storage.increment_counter()", "de...
[ "0.64278454", "0.642254", "0.6130352", "0.60675645", "0.5942708", "0.5894269", "0.5890736", "0.58173895", "0.5758865", "0.5732553", "0.5684082", "0.567313", "0.55923927", "0.55792695", "0.55606544", "0.554892", "0.55463547", "0.5544628", "0.5536674", "0.55294377", "0.55287164...
0.5772331
8
Return bytes representation of Ethernet header.
def __bytes__(self): return pack("<HH", self._packet_len, self._control_ctr)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def header_bytes(self, zero_checksum=False):\n b = bytearray()\n\n counter = 0\n integer = 0\n\n # The values are packed into 4-byte integers, since the largest\n # fixed-size header fields are 4-byte IP addresses. After that, they are\n # added to the byte array as 4 byte...
[ "0.71295446", "0.6759291", "0.67367053", "0.6716264", "0.65858597", "0.6580915", "0.6509498", "0.64819175", "0.6466296", "0.6400534", "0.6400534", "0.62959313", "0.62959313", "0.6222679", "0.61640424", "0.6083347", "0.60510254", "0.6036172", "0.60090053", "0.59898037", "0.598...
0.6176237
14
Creates a XCP Ethernet frame
def create_message(self, packet): self._header.packet_len = len(bytes(packet)) frame_bytes = super(EthernetTransport, self).create_message(packet) # Update control counter for next frame self._header.update_control() return bytes(frame_bytes)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gen_ieee_packet(self, data):\n\t\tpacket = Dot15d4FCS() / Dot15d4Data() / Raw(load=data)\n\n\t\tpacket.fcf_srcaddrmode = 2\n\t\tpacket.fcf_destaddrmode = 2\n\n\t\tpacket.fcf_panidcompress = True\n\t\tpacket.fcf_ackreq = True\n\t\tpacket.seqnum = self.seqnum\n\n\t\tpacket.dest_panid = self.link_config.dest_pani...
[ "0.58488214", "0.5700761", "0.56956196", "0.56287456", "0.56241447", "0.56202054", "0.54626226", "0.5419994", "0.5410478", "0.53642374", "0.53623325", "0.531552", "0.52997607", "0.526246", "0.5247345", "0.5247104", "0.5242202", "0.5209782", "0.5174515", "0.5075918", "0.503412...
0.6318154
0
Computes the pickup_features feature group. To restrict features to a time range, pass in ts_column, start_date, and/or end_date as kwargs.
def pickup_features_fn(df, ts_column, start_date, end_date): df = filter_df_by_ts( df, ts_column, start_date, end_date ) pickupzip_features = ( df.groupBy( "pickup_zip", window("tpep_pickup_datetime", "1 hour", "15 minutes") ) # 1 hour window, sliding every 15 minutes .agg( mean("fare_amount").alias("mean_fare_window_1h_pickup_zip"), count("*").alias("count_trips_window_1h_pickup_zip"), ) .select( col("pickup_zip").alias("zip"), unix_timestamp(col("window.end")).alias("ts").cast(IntegerType()), partition_id(to_timestamp(col("window.end"))).alias("yyyy_mm"), col("mean_fare_window_1h_pickup_zip").cast(FloatType()), col("count_trips_window_1h_pickup_zip").cast(IntegerType()), ) ) return pickupzip_features
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def dropoff_features_fn(df, ts_column, start_date, end_date):\n df = filter_df_by_ts(\n df, ts_column, start_date, end_date\n )\n dropoffzip_features = (\n df.groupBy(\"dropoff_zip\", window(\"tpep_dropoff_datetime\", \"30 minute\"))\n .agg(count(\"*\").alias(\"count_trips_window_30m...
[ "0.6709174", "0.59639823", "0.5956674", "0.57902575", "0.5713756", "0.5689175", "0.5615991", "0.5600183", "0.5599253", "0.5595833", "0.55765986", "0.55623573", "0.5488219", "0.5388274", "0.53792185", "0.5378838", "0.5333837", "0.53081375", "0.53008443", "0.5289871", "0.525374...
0.7756553
0
Computes the dropoff_features feature group. To restrict features to a time range, pass in ts_column, start_date, and/or end_date as kwargs.
def dropoff_features_fn(df, ts_column, start_date, end_date): df = filter_df_by_ts( df, ts_column, start_date, end_date ) dropoffzip_features = ( df.groupBy("dropoff_zip", window("tpep_dropoff_datetime", "30 minute")) .agg(count("*").alias("count_trips_window_30m_dropoff_zip")) .select( col("dropoff_zip").alias("zip"), unix_timestamp(col("window.end")).alias("ts").cast(IntegerType()), partition_id(to_timestamp(col("window.end"))).alias("yyyy_mm"), col("count_trips_window_30m_dropoff_zip").cast(IntegerType()), is_weekend(col("window.end")).alias("dropoff_is_weekend"), ) ) return dropoffzip_features
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pickup_features_fn(df, ts_column, start_date, end_date):\n df = filter_df_by_ts(\n df, ts_column, start_date, end_date\n )\n pickupzip_features = (\n df.groupBy(\n \"pickup_zip\", window(\"tpep_pickup_datetime\", \"1 hour\", \"15 minutes\")\n ) # 1 hour window, sliding...
[ "0.66726613", "0.5643213", "0.55374706", "0.5524301", "0.5516429", "0.54855764", "0.5438203", "0.538857", "0.53348887", "0.53311694", "0.5320984", "0.5259109", "0.5249251", "0.52357846", "0.52223134", "0.5205125", "0.5173679", "0.5165818", "0.51619375", "0.5140185", "0.513639...
0.75834435
0
Ceilings datetime dt to interval num_minutes, then returns the unix timestamp.
def rounded_unix_timestamp(dt, num_minutes=15): nsecs = dt.minute * 60 + dt.second + dt.microsecond * 1e-6 delta = math.ceil(nsecs / (60 * num_minutes)) * (60 * num_minutes) - nsecs return int((dt + timedelta(seconds=delta)).timestamp())
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _time_ms(self, dt):\n if dt.tzinfo is None:\n dt = dt.replace(tzinfo=pytz.utc)\n return int((dt - self._EPOCH).total_seconds() * 1000)", "def _time_ms(dt):\n epoch = datetime.datetime.utcfromtimestamp(0)\n diff = dt - epoch\n return diff.total_seconds() * 1000", "def _get_...
[ "0.57981074", "0.5748822", "0.5663159", "0.56519955", "0.5603236", "0.5469628", "0.5442284", "0.54418385", "0.5433084", "0.5365743", "0.5359583", "0.53497386", "0.53274846", "0.5236749", "0.5208083", "0.520233", "0.51816577", "0.5176535", "0.51646566", "0.51259786", "0.510066...
0.7375313
0
Align trigger on display (> 0 is right of center, < 0 is left of center)
def hpos(self, offset_sec = None): if offset_sec is not None: if not isinstance(offset_sec, (int, float)): raise TypeError('delay_sec must be numeric value') self.command(f'SET Horizontal Offset of Trigger {-offset_sec} sec {"LEFT" if offset_sec < 0 else "RIGHT"} of center') else: return self.query_float('ENTER Current Horizontal Offset of Trigger (seconds)')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def center(self):\n if self.pos != 0.0:\n self.pos = 0.0", "def center_ava(self):\n\t\tself.rect.midbottom = self.screen_rect.midbottom\n\t\tself.x = float(self.rect.x)", "def center(self):\n cp = self.dat.flowsheet.getCenter()\n self.centerOn(cp[0], cp[1])", "def centerAxis()...
[ "0.61338747", "0.60391134", "0.5984671", "0.5806344", "0.57887024", "0.57887024", "0.57887024", "0.57887024", "0.5788586", "0.5779757", "0.5755072", "0.5707836", "0.57064337", "0.57064337", "0.5662579", "0.5656464", "0.5644351", "0.5622311", "0.5614773", "0.5609005", "0.56051...
0.0
-1
Return current sample rate in Sa/s
def sample_rate(self): return self.query_float('ENTER Current Sample Rate (Sa/s)')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sample_rate(self):\r\n return self.config.sample_rate", "def sample_rate(self):\n return self._sample_rate", "def sample_rate(self):\n return self._sample_rate", "def sample_rate(self):\n return self._sample_rate", "def sample_rate(self, sr=None):\n return self._sample_ra...
[ "0.81212515", "0.8000023", "0.8000023", "0.7969299", "0.7864392", "0.7847092", "0.782177", "0.7783444", "0.7727639", "0.76789045", "0.763086", "0.74798954", "0.7479725", "0.7386037", "0.7357198", "0.73316765", "0.7272404", "0.72663385", "0.7222648", "0.70849174", "0.6931208",...
0.86877906
0
Capture scope screen and save as filename. File type determines format as supported by derived class
def screen_capture(self, filename): self.command(f'CAPTURE SCREEN as {filename}') return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_raw(self, filename, typ):\n self.lib.SaveAsRaw(ct.c_char_p(str.encode(filename)),\n ct.c_int(self.savetypes[typ]))", "def out_filename(self, filetype, format='old', dir=Location.OUT_DIR):\n filename = self.filename(filetype=filetype, format=format)\n #retur...
[ "0.59803706", "0.58541864", "0.58138627", "0.5693963", "0.5692039", "0.5593365", "0.55539596", "0.55515766", "0.5475402", "0.5469633", "0.5382346", "0.5378022", "0.53728104", "0.53728104", "0.53492075", "0.533417", "0.5317118", "0.53051895", "0.53029484", "0.52836293", "0.528...
0.5047978
46
assert expected_content has been written to stdout
def assertStdoutContains(self, expected_content): if type(expected_content) is not types.ListType: expected_content = [ expected_content ] stdout_message = sys.stdout.getvalue() for the_text in expected_content: self.assertIn(the_text, stdout_message,('Stdout "%s" does not contain text "%s"' % (stdout_message, the_text)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_cot_output(self, expected):\n sys.stdout = StringIO.StringIO()\n output = None\n try:\n self.instance.run()\n except (TypeError, ValueError, SyntaxError, LookupError):\n self.fail(traceback.format_exc())\n finally:\n output = sys.stdout....
[ "0.76000136", "0.7482878", "0.7107269", "0.70161605", "0.68864036", "0.68497556", "0.6828578", "0.6819774", "0.6798522", "0.6753548", "0.66351914", "0.6541468", "0.64065236", "0.6402621", "0.6388881", "0.6368317", "0.6329488", "0.63178706", "0.6316625", "0.63080114", "0.63029...
0.72075444
2
assert unexpected_content has not been written to stdout
def assertStdoutDoesNotContain(self, unexpected_content): if type(unexpected_content) is not types.ListType: unexpected_content = [ unexpected_content ] stdout_message = sys.stdout.getvalue() for the_text in unexpected_content: self.assertNotIn(the_text, stdout_message,('Stdout "%s" contains text "%s"' % (stdout_message, the_text)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_cot_output(self, expected):\n sys.stdout = StringIO.StringIO()\n output = None\n try:\n self.instance.run()\n except (TypeError, ValueError, SyntaxError, LookupError):\n self.fail(traceback.format_exc())\n finally:\n output = sys.stdout....
[ "0.6872373", "0.65048116", "0.6423676", "0.6372315", "0.63059235", "0.6282092", "0.62726283", "0.62563837", "0.61430126", "0.6134692", "0.61007786", "0.60741216", "0.6065867", "0.60580695", "0.6008732", "0.597988", "0.58616245", "0.58479875", "0.5832719", "0.5825116", "0.5822...
0.69911766
0
Call this method to extract the widget to pack into your GUI when you are building the viewer into things.
def get_widget(self): return self.imgwin
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def assemble_widget(self) -> widgets.Widget:\n graph_selection = self._create_layer_selection(layer_type=\"graphs\")\n map_selection = self._create_layer_selection(layer_type=\"maps\")\n view_buttons = self.create_visibility_buttons()\n\n widget = widgets.VBox(\n [\n ...
[ "0.6719459", "0.6683136", "0.6647989", "0.6631315", "0.6631315", "0.66061366", "0.6587179", "0.6580063", "0.6485855", "0.64484394", "0.643607", "0.6428566", "0.6412553", "0.6378195", "0.63732135", "0.6308009", "0.6247851", "0.62427694", "0.62391776", "0.6239147", "0.6238216",...
0.0
-1
Render the image represented by (rgbobj) at dst_x, dst_y in the offscreen pixmap.
def render_image(self, rgbobj, dst_x, dst_y): self.logger.debug("redraw pixmap=%s" % (self.pixmap)) if self.pixmap is None: return self.logger.debug("drawing to pixmap") # Prepare array for rendering arr = rgbobj.get_array(self.rgb_order, dtype=np.uint8) (height, width) = arr.shape[:2] return self._render_offscreen(self.pixmap, arr, dst_x, dst_y, width, height)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw(self):\r\n self.screen.blit(self.image, self.image.get_rect())", "def draw(self, surface):\r\n surface.blit(self.image, self.rect)", "def draw(self):\n self.screen.blit(self.image, self.rect)", "def draw(self, surface):\n surface.blit(self.image, self.rect)", "def draw(...
[ "0.61686844", "0.5998365", "0.5990171", "0.59325355", "0.59325355", "0.5924451", "0.5898981", "0.5876628", "0.58228207", "0.5799751", "0.5746103", "0.5726643", "0.5718437", "0.56835777", "0.565392", "0.5641117", "0.5641117", "0.5641117", "0.5641117", "0.56196475", "0.5606678"...
0.8753144
0
This method is called by the event handler when the size of the window changes (or it can be called manually). We allocate an offscreen pixmap of the appropriate size and inform the superclass of our window size.
def configure_window(self, width, height): self.configure_surface(width, height)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __ev_resize(self, event):\n\n new_size = event.dict['size']\n surface_size = self.__screen.get_size()\n old_center = self.__screen.get_rect().center\n if new_size != surface_size:\n self.__screen = pygame.display.set_mode(new_size,\n ...
[ "0.72156596", "0.7100522", "0.6702604", "0.6601584", "0.65673465", "0.65583104", "0.65517545", "0.6497365", "0.6497365", "0.647053", "0.643673", "0.63569677", "0.6356837", "0.6324894", "0.6282427", "0.6277227", "0.62645644", "0.6249151", "0.6226418", "0.62170535", "0.6205427"...
0.56322706
80
Used for generating thumbnails. Does not include overlaid graphics.
def get_plain_image_as_widget(self): arr = self.getwin_array(order=self.rgb_order) # convert numpy array to native image widget image_w = self._get_wimage(arr) return image_w
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_thumbnail(self, target, format=None):", "def generate_image(self):\n pass", "def _prepareImage(self):\n painter = QPainter(self)\n if len(self.thumbs) == 0:\n return\n destwidth = self.width()\n division = len(self.thumbs)\n NF = division\n ...
[ "0.7301337", "0.6821647", "0.68065804", "0.6654889", "0.66077906", "0.65570223", "0.6476974", "0.64667434", "0.64605975", "0.64199996", "0.64156866", "0.63598025", "0.63443893", "0.63439167", "0.63422894", "0.63266927", "0.6324976", "0.62868947", "0.61534524", "0.60603607", "...
0.0
-1
Used for generating thumbnails. Does not include overlaid graphics.
def save_plain_image_as_file(self, filepath, format='png', quality=90): img_w = self.get_plain_image_as_widget() # assumes that the image widget has some method for saving to # a file img_w.save(filepath, format=format, quality=quality)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_thumbnail(self, target, format=None):", "def generate_image(self):\n pass", "def _prepareImage(self):\n painter = QPainter(self)\n if len(self.thumbs) == 0:\n return\n destwidth = self.width()\n division = len(self.thumbs)\n NF = division\n ...
[ "0.7300164", "0.68219376", "0.6806696", "0.6653911", "0.6605065", "0.655592", "0.6475331", "0.64640075", "0.64590347", "0.64180756", "0.64131033", "0.63602334", "0.6345334", "0.63405406", "0.6339203", "0.6324948", "0.6323947", "0.62881386", "0.6151722", "0.6059803", "0.600211...
0.0
-1
Convert the numpy array (which is in our expected order) to a native image object in this widget set.
def _get_wimage(self, arr_np): #return result raise NotImplementedError
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def convertNumpy2Image(self, array):\n cv2image = cv2.cvtColor(array, cv2.COLOR_BGR2RGBA)\n img = Image.fromarray(cv2image)\n imgtk = ImageTk.PhotoImage(image=img)\n return imgtk", "def newimagefromarray(self, *args, **kwargs):\n return _image.image_newimagefromarray(self, *arg...
[ "0.76605815", "0.7366861", "0.7267543", "0.7149821", "0.7017206", "0.69027084", "0.6662344", "0.6589255", "0.6467619", "0.6431062", "0.63332164", "0.63316214", "0.62858456", "0.62591535", "0.6197975", "0.61858237", "0.6156995", "0.61221844", "0.6117985", "0.60852593", "0.5992...
0.5590651
42
Convert red, green and blue values specified in floats with range 01 to whatever the native widget color object is.
def _get_color(self, r, g, b): clr = (r, g, b) return clr
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_color(self, value):\n value = min(max(0,value), 1) * 510\n\n if value < 255:\n redValue = 255\n greenValue = math.sqrt(value) * 16\n greenValue = int(greenValue)\n else:\n greenValue = 255\n value = value - 255\n redValu...
[ "0.6687373", "0.66278064", "0.6625339", "0.6615278", "0.65561914", "0.64596033", "0.64479345", "0.6447677", "0.6441892", "0.64142656", "0.6391666", "0.6331374", "0.6328157", "0.6308797", "0.6283234", "0.62787604", "0.624464", "0.6223854", "0.6213597", "0.6211883", "0.6205541"...
0.6279571
15
Translate a keycode/keyname in the widget set to a ginga standard ASCII symbol.
def transkey(self, keycode, keyname): self.logger.debug("keycode=%d keyname='%s'" % ( keycode, keyname)) try: return self._keytbl[keyname.lower()] except KeyError: return keyname
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _translate_keyname(inp):\n convert = {'Equal': '=', 'Escape': 'Esc', 'Delete': 'Del', 'Return': 'Enter',\n 'Page_up': 'PgUp', 'Page_down': 'PgDn'}\n if inp in convert:\n out = convert[inp]\n else:\n out = inp\n return out", "def process_key(key):\n print(chr(key))",...
[ "0.649627", "0.64508295", "0.60739535", "0.5946068", "0.5925816", "0.591658", "0.5915577", "0.5905107", "0.58689904", "0.5861603", "0.5852588", "0.58291864", "0.5826368", "0.5734772", "0.5725578", "0.57112306", "0.57053083", "0.5674953", "0.565874", "0.5647493", "0.5629468", ...
0.57259935
14
Called when the window is mapped to the screen. Adjust method signature as appropriate for callback.
def map_event(self, widget, event): #self.configure_window(width, height) return self.make_callback('map')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw_final_screen(self):\r\n root = Tk()\r\n MapGUI(root, self)\r\n root.geometry('710x540')\r\n root.mainloop()", "def on_activate(self, caller):\n self.window = GameWindow()\n self.add_window(self.window)", "def on_window_ready(self):\n pass", "def rende...
[ "0.66794527", "0.6534415", "0.64738363", "0.6434481", "0.63836956", "0.63404757", "0.62570506", "0.6250776", "0.6242063", "0.6228347", "0.6141727", "0.6103516", "0.6091959", "0.60864115", "0.60830456", "0.6010346", "0.6000272", "0.5971659", "0.597011", "0.59490347", "0.594538...
0.6313375
6
Called when the window gets focus. Adjust method signature as appropriate for callback.
def focus_event(self, widget, event, hasFocus): return self.make_callback('focus', hasFocus)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ev_windowfocusgained(self, event: WindowEvent) -> None:", "def __window_focus(self):\n pass", "def ev_windowfocusgained(self, event: tcod.event.WindowEvent) -> T | None:", "def onFocus(*args):", "def onFocus(*args):", "def onFocus(*args):", "def onFocus(*args):", "def get_focus(self):\n\n ...
[ "0.8171678", "0.804375", "0.75519395", "0.71898013", "0.71898013", "0.71898013", "0.71898013", "0.71747136", "0.715196", "0.6995946", "0.6974785", "0.6864648", "0.6742967", "0.67170674", "0.67143035", "0.66499484", "0.6622382", "0.6622382", "0.6622382", "0.6622382", "0.662197...
0.68105537
12
Called when the mouse cursor enters the window. Adjust method signature as appropriate for callback.
def enter_notify_event(self, widget, event): enter_focus = self.t_.get('enter_focus', False) if enter_focus: # set focus on widget pass return self.make_callback('enter')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ev_windowenter(self, event: WindowEvent) -> None:", "def mouse_enter(self):\n pass", "def ev_windowenter(self, event: tcod.event.WindowEvent) -> T | None:", "def append_cursor_enter_callback(self):", "def mouse_in(event):\r\n\r\n if str(event.type) == 'Enter':\r\n about...
[ "0.7506842", "0.72784686", "0.70456034", "0.69871587", "0.6757498", "0.664396", "0.6616291", "0.65236306", "0.6389402", "0.6246457", "0.61803067", "0.61756974", "0.61756974", "0.6149091", "0.61142", "0.6091212", "0.60810506", "0.6032246", "0.5978715", "0.597732", "0.5919302",...
0.5393033
73
Called when the mouse cursor leaves the window. Adjust method signature as appropriate for callback.
def leave_notify_event(self, widget, event): self.logger.debug("leaving widget...") return self.make_callback('leave')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ev_windowleave(self, event: WindowEvent) -> None:", "def OnLeaveWindow(self, event):\r\n \r\n if self._hover_button:\r\n self._hover_button.cur_state = AUI_BUTTON_STATE_NORMAL\r\n self._hover_button = None\r\n self.Refresh()\r\n self.Update()", "def...
[ "0.7683408", "0.7552822", "0.75221896", "0.7349047", "0.73260576", "0.72890663", "0.7207108", "0.7075997", "0.6955286", "0.6878195", "0.68585074", "0.67361873", "0.67259437", "0.66449815", "0.65735984", "0.6550799", "0.6520514", "0.646866", "0.64424396", "0.64258564", "0.6395...
0.6011161
40
Called when a key is pressed and the window has the focus. Adjust method signature as appropriate for callback.
def key_press_event(self, widget, event): # get keyname or keycode and translate to ginga standard # keyname = # keycode = keyname = '' # self.transkey(keyname, keycode) self.logger.debug("key press event, key=%s" % (keyname)) return self.make_ui_callback('key-press', keyname)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _on_key_press(self, event):", "def ev_windowfocusgained(self, event: WindowEvent) -> None:", "def _on_key_release(self, event):", "def on_key(self, _win, key, _scancode, action, _mods):\n if action == glfw.PRESS or action == glfw.REPEAT:\n if key == glfw.KEY_ESCAPE or key == glfw.KEY_Q:...
[ "0.7016208", "0.6989728", "0.696532", "0.6910112", "0.6764562", "0.67168427", "0.6626978", "0.6623902", "0.6604723", "0.6576953", "0.6570364", "0.6550427", "0.65445656", "0.65329766", "0.6531511", "0.65207005", "0.6487252", "0.64807296", "0.64629245", "0.6444512", "0.64369535...
0.0
-1
Called when a key is released after being pressed. Adjust method signature as appropriate for callback.
def key_release_event(self, widget, event): # get keyname or keycode and translate to ginga standard # keyname = # keycode = keyname = '' # self.transkey(keyname, keycode) self.logger.debug("key release event, key=%s" % (keyname)) return self.make_ui_callback('key-release', keyname)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def key_release_event(self, event):\n pass", "def _on_key_release(self, event):", "def on_key_release(self, key, modifiers):\n player_controller.input_release(key, self.player)", "def keyReleaseEvent(self, event):\n self.game_engine.input_manager.keyReleaseEvent(event)", "def _onkeyrel...
[ "0.8233656", "0.7974817", "0.7656666", "0.76358575", "0.74908", "0.73535097", "0.73379964", "0.7314337", "0.7266822", "0.7175188", "0.7162018", "0.7148087", "0.70924264", "0.7065574", "0.70232534", "0.7012686", "0.7012686", "0.70101947", "0.70101947", "0.6966152", "0.69470584...
0.76694167
2
Called when a mouse button is pressed in the widget. Adjust method signature as appropriate for callback.
def button_press_event(self, widget, event): x, y = event.x, event.y # x, y = coordinates where the button was pressed self.last_win_x, self.last_win_y = x, y button = 0 # Prepare a button mask with bits set as follows: # left button: 0x1 # middle button: 0x2 # right button: 0x4 # Others can be added as appropriate self.logger.debug("button down event at %dx%d, button=%x" % (x, y, button)) data_x, data_y = self.check_cursor_location() return self.make_ui_callback('button-press', button, data_x, data_y)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def on_mouse_press(self, x, y, button):\n\n pass", "def ev_mousebuttondown(self, event: MouseButtonDown) -> None:", "def handle_mouse_press(self, event):", "def mouse_press_event(self, x: int, y: int, button: int):\n pass", "def on_mouse_press(self, x, y, button, key_modifiers):\r\n pa...
[ "0.8186688", "0.7803107", "0.7685904", "0.7667033", "0.7550329", "0.75264764", "0.74540734", "0.74537903", "0.7434162", "0.71306", "0.71141076", "0.7086629", "0.70717835", "0.70475805", "0.70216006", "0.70136315", "0.69730556", "0.69179136", "0.69159424", "0.69106615", "0.690...
0.786055
1
Called when a mouse button is released after being pressed. Adjust method signature as appropriate for callback.
def button_release_event(self, widget, event): x, y = event.x, event.y # x, y = coordinates where the button was released self.last_win_x, self.last_win_y = x, y button = 0 # prepare button mask as in button_press_event() data_x, data_y = self.check_cursor_location() return self.make_ui_callback('button-release', button, data_x, data_y)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mouse_release_event(self, x: int, y: int, button: int):\n pass", "def on_mouse_release(self, x, y, button):\n pass", "def on_mouse_release(self, x, y, button, key_modifiers):\r\n pass", "def OnMouseUp(self, evt):\n self.ReleaseMouse()", "def emitReleaseEvent(self, clickLocat...
[ "0.80996853", "0.80075884", "0.7933358", "0.74254155", "0.7286587", "0.7269564", "0.72388613", "0.72388613", "0.72174096", "0.71852064", "0.7037113", "0.7027572", "0.7019888", "0.69756335", "0.6968941", "0.6932969", "0.69013923", "0.68389016", "0.6834489", "0.68217915", "0.68...
0.7786435
3
Called when a mouse cursor is moving in the widget. Adjust method signature as appropriate for callback.
def motion_notify_event(self, widget, event): x, y = event.x, event.y # x, y = coordinates of cursor self.last_win_x, self.last_win_y = x, y button = 0 # prepare button mask as in button_press_event() data_x, data_y = self.check_cursor_location() return self.make_ui_callback('motion', button, data_x, data_y)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mouse_move_callback(self, event):\n # TODO drag and drop figuriek\n print(\"moving at \", event.x + self.offset_x, event.y + self.offset_y)", "def on_mouse_motion(self, x, y, delta_x, delta_y):\r\n pass", "def __mouseMoved(self, x, y):\n # Are we on the bounding box?\n if...
[ "0.7342505", "0.7273285", "0.7090941", "0.70634186", "0.7034477", "0.69676363", "0.6943248", "0.68984425", "0.669294", "0.659831", "0.65874934", "0.6549803", "0.6516948", "0.6500888", "0.6497365", "0.6471458", "0.6461945", "0.64583486", "0.6448528", "0.6439387", "0.63827825",...
0.64577484
18
Called when a mouse is turned in the widget (and maybe for finger scrolling in the trackpad). Adjust method signature as appropriate for callback.
def scroll_event(self, widget, event): x, y = event.x, event.y num_degrees = 0 direction = 0 # x, y = coordinates of mouse self.last_win_x, self.last_win_y = x, y # calculate number of degrees of scroll and direction of scroll # both floats in the 0-359.999 range # num_degrees = # direction = self.logger.debug("scroll deg=%f direction=%f" % ( num_degrees, direction)) data_x, data_y = self.check_cursor_location() return self.make_ui_callback('scroll', direction, num_degrees, data_x, data_y)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handle_mouse_press(self, event):", "def handle_mouse(self, x, y):\n pass", "def on_mouse_press(self, event):\n self.on_mouse_wheel(event)", "def on_mouse_press(self, x, y, button):\n\n pass", "def mouseDragged():\n if mousePressed:\n mousePressed()", "def on_mouse_motio...
[ "0.71367556", "0.68652886", "0.67238146", "0.6668152", "0.6439022", "0.6427705", "0.64046293", "0.6377476", "0.6342399", "0.61890846", "0.6186807", "0.608219", "0.6079052", "0.60771847", "0.60688984", "0.60027486", "0.59981054", "0.5972442", "0.59615374", "0.59591645", "0.595...
0.0
-1
Called when a drop (drag/drop) event happens in the widget. Adjust method signature as appropriate for callback.
def drop_event(self, widget, event): # make a call back with a list of URLs that were dropped #self.logger.debug("dropped filename(s): %s" % (str(paths))) #self.make_ui_callback('drag-drop', paths) raise NotImplementedError
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def dropEvent(self, de):\n # dragging a track\n if hasattr(Globals.dragObject, \"trackFrame\"):\n de.accept()\n trackFrame = Globals.dragObject.trackFrame\n oldParent = trackFrame.parentWidget()\n if oldParent:\n args = (trackFrame, self, old...
[ "0.72224736", "0.7178574", "0.7033632", "0.69308865", "0.69137365", "0.68517953", "0.66538286", "0.660371", "0.6481881", "0.6399347", "0.6314507", "0.63019335", "0.6220606", "0.6072313", "0.60482043", "0.6036351", "0.59223694", "0.59200025", "0.58687717", "0.58277893", "0.573...
0.81672764
0
Update every cell in the grid. This is a single step in the evolution. Compute number in each state and number of state changes.
def update_grid(self, x): # Append boundary rows and columns to matrix x = self.append_boundary(x) # the boundary is recomputed at each step y = np.copy(x) # For each cell within boundary, compute state according to rules. chg_0_1 = 0 # the number of cells that changed from state 0 to state 1 chg_1_0 = 0 # the number of cells that changes from state 1 to state 0 chg_none = 0 # the number of cells that did not change index = np.arange(1, x.shape[0] - 1) for i in index: for j in index: neighborhood = x[i - 1:i + 2:1, j - 1:j + 2:1] # 3x3 sub matrix centered at i, j y[i, j] = self.update_cell(neighborhood) change = int(y[i, j] - x[i, j]) if change == -1: chg_1_0 += 1 if change == 0: chg_none += 1 if change == 1: chg_0_1 += 1 # Compute statistics excluding boundary total = np.power(x[1:-1:1, 1:-1:1].shape[0] - 1, 2) start_1 = np.sum(x[1:-1:1, 1:-1:1]) end_1 = np.sum(y[1:-1:1, 1:-1:1]) stats = [total, start_1, end_1, chg_1_0, chg_none, chg_0_1] return y[1:-1:1, 1:-1:1], stats # remove the boundary
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _update_cells(self):\n for row_number in range(self.number_cells_y):\n for col_number in range(self.number_cells_x):\n if self.to_be_updated[row_number][col_number]:\n self.cells[row_number][col_number].update()", "def update_cells(self, state):\n wi...
[ "0.7286067", "0.70985454", "0.65855974", "0.64528495", "0.6422918", "0.62100416", "0.62099385", "0.61870646", "0.6159121", "0.6139433", "0.6139193", "0.60986966", "0.6086777", "0.60648525", "0.6041667", "0.6039886", "0.6037677", "0.60304636", "0.60248035", "0.6021954", "0.600...
0.65298665
3
Compute the final grid at given number of steps
def grid_frame(self, steps, figure_size=(12, 12)): x = self.seed counts = [] for n in np.arange(0, steps): x, stats = self.update_grid(x) counts.append(stats) counts = np.array(counts) fig, ax = plt.subplots(figsize=figure_size) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) color_map = matplotlib.colors.ListedColormap(['white', 'black']) img = plt.imshow(x, interpolation='nearest', cmap=color_map) img.axes.grid(False) plt.title(self.title + ' | Step ' + str(steps)) plt.show() return x, counts
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def grid_traveller(m: int, n: int):\n\n if m == 1 and n == 1:\n return 1\n if m == 0 or n == 0:\n return 0\n return grid_traveller(m - 1, n) + grid_traveller(m, n - 1)", "def recursion_loop(pulls, discount, grid_n):\n\n r_grid = np.linspace(0, 1, grid_n)\n gittins, values = initial_a...
[ "0.62839276", "0.6177618", "0.6006914", "0.5955859", "0.5950042", "0.5941752", "0.58852285", "0.58458596", "0.5777134", "0.57740855", "0.5760194", "0.57317764", "0.572567", "0.5684606", "0.5644186", "0.5635062", "0.563393", "0.5599859", "0.5587036", "0.55789906", "0.55467486"...
0.61110514
2
Display a step by step animation of the cellular automata rule.
def grid_animation(self, steps, figure_size=(12, 12), speed=100): steps -= 1 x = self.seed fig, ax = plt.subplots(figsize=figure_size) ax.grid(False) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) color_map = matplotlib.colors.ListedColormap(['white', 'black']) im = plt.imshow(x[1:-1:1, 1:-1:1], interpolation='nearest', cmap=color_map, animated=True) counter = 0 def update_figure(*args): nonlocal x, counter, fig counter += 1 x, stats = self.update_grid(x) plt.title(self.title + ' | Step ' + str(counter), fontsize=14) im.set_array(x[1:-1:1, 1:-1:1]) return im, # why is this comma necessary? ani = animation.FuncAnimation(fig, update_figure, frames=steps, interval=speed, blit=False, repeat=False) return ani
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def animate(self):\n if self.board.automaton.get() == \"life\":\n self.state = self.life.game_of_life(self.state)\n #self.life.random_activations(self.state)\n elif self.board.automaton.get() == \"seeds\":\n self.state = self.life.seeds(self.state)\n else:\n ...
[ "0.62367564", "0.6091286", "0.6087436", "0.6078769", "0.6029971", "0.60093224", "0.59166366", "0.59036875", "0.581892", "0.5817786", "0.5748448", "0.5748111", "0.5671084", "0.5665676", "0.5663996", "0.5663854", "0.563546", "0.5605197", "0.5595019", "0.55923826", "0.55907106",...
0.603831
4
For Jupyter Notebook Display Only?
def grid_animation_quick(self, frames, iterations=10, fps=0.02, figsize=(6, 6)): color_map = matplotlib.colors.ListedColormap(['white', 'black']) fig, ax = plt.subplots(figsize=figsize) for r in np.arange(0, iterations): ax.cla() ax.axes.grid(False) ax.set_axis_off() im = ax.imshow(frames[0], cmap=color_map, animated=True) for image, step in zip(frames[1:], np.arange(1, len(frames[1:])+1)): time.sleep(fps) ax.title.set_text('Rule 942 | Step ' + str(step) + ' | Active ' + str(int(np.sum(image)))) im.set_data(image) fig.canvas.draw()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def jupyter():", "def notebook():\n pass", "def notebook():\n pass", "def _ipython_display_(self):\n with self._sc:\n self._box._ipython_display_()", "def in_notebook():\n from IPython import get_ipython\n return get_ipython() is not None", "def output_notebook(self):\n ...
[ "0.8027189", "0.7526061", "0.7526061", "0.7300398", "0.71970946", "0.6907858", "0.68669766", "0.6833837", "0.67673033", "0.6737627", "0.67263234", "0.66920686", "0.6689149", "0.66816413", "0.6628358", "0.65491647", "0.65302175", "0.6369754", "0.6367418", "0.6348409", "0.63246...
0.0
-1
Main function to get data into Splunk.
def collect_events(helper, ew): # pylint: disable=no-self-argument,invalid-name,too-many-statements,too-many-branches def clear_checkbox(session_key, stanza): """ Sets the 'reindex_data' value in the REST API to 0 to clear it. Splunk then automatically restarts the input.""" url = f'https://localhost:8089/servicesNS/nobody/TA-strava-for-splunk/data/inputs/strava_api/{stanza}' headers = {'Authorization': f'Splunk {session_key}'} payload = 'reindex_data=0' helper.send_http_request(url, "POST", headers=headers, payload=payload, verify=False, use_proxy=False) def get_activities(ts_activity, access_token): """Gets all activities, 30 per page as per Strava's default.""" params = {'after': ts_activity, 'access_token': access_token} url = "https://www.strava.com/api/v3/activities" response = return_json(url, "GET", parameters=params) return response def get_activity(activity, token): """Gets specific activity.""" url = f'https://www.strava.com/api/v3/activities/{activity}?include_all_efforts=true' params = {'access_token': token} response = return_json(url, "GET", parameters=params, timeout=10) return response def get_activity_stream(token, activity, types, series_type='time', resolution='high'): """Gets the activity stream for given activity id.""" types = ','.join(types) params = {'access_token': token} url = f'https://www.strava.com/api/v3/activities/{activity}/streams/{types}&series_type={series_type}&resolution={resolution}&key_by_type=' response = return_json(url, "GET", parameters=params, timeout=10) return response def get_athlete(token): """Gets details on currently logged in athlete.""" url = "https://www.strava.com/api/v3/athlete" params = {'access_token': token} response = return_json(url, "GET", parameters=params, timeout=10) return response def get_epoch(timestamp): """Converts Strava datetime to epoch timestamp""" timestamp_dt = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ") epoch = calendar.timegm(timestamp_dt.timetuple()) return epoch def get_token(client_id, client_secret, token, renewal): """Get or refresh access token from Strava API.""" url = "https://www.strava.com/api/v3/oauth/token" if renewal: payload = { 'client_id': client_id, 'client_secret': client_secret, 'refresh_token': token, 'grant_type': 'refresh_token'} message = "Successfully refreshed Strava token." else: payload = { 'client_id': client_id, 'client_secret': client_secret, 'code': token, 'grant_type': 'authorization_code'} message = "Successfully authenticated with Strava using access code." response = return_json(url, "POST", payload=payload) helper.log_info(message) return response def kvstore_save_athlete(session_key, athlete_id, firstname, lastname, weight, ftp): # pylint: disable=too-many-arguments """Stores athlete's id, first name, last name, weight and ftp into strava_athlete KV Store collection.""" url = 'https://localhost:8089/servicesNS/nobody/TA-strava-for-splunk/storage/collections/data/strava_athlete/batch_save' headers = {'Content-Type': 'application/json', 'Authorization': f'Splunk {session_key}'} payload = [{"_key": athlete_id, "id": athlete_id, "firstname": firstname, "lastname": lastname, "fullname": firstname + " " + lastname, "weight": weight, "ftp": ftp}] helper.send_http_request(url, "POST", headers=headers, payload=payload, verify=False, use_proxy=False) def parse_data(data, activity_id, activity_start_date): """Gets raw JSON data, parses it into events and writes those to Splunk.""" data_dict = {} final_dict = {} for i in data: data_dict[i['type']] = i['data'] counter = 1 nrange = len(data_dict['time']) for item in range(1, nrange + 1): final_dict[item] = {} for key, value in data_dict.items(): counter = 1 for i in value: final_dict[counter][key] = i final_dict[counter]['activity_id'] = activity_id if 'time' in key: final_dict[counter]['time'] = final_dict[counter]['time'] + activity_start_date final_dict[counter]['time'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(final_dict[counter]['time'])) if 'latlng' in key: final_dict[counter]['lat'] = final_dict[counter]['latlng'][0] final_dict[counter]['lon'] = final_dict[counter]['latlng'][1] final_dict[counter].pop('latlng') counter += 1 result_list = [value for key, value in final_dict.items()] for event in result_list: write_to_splunk(index=helper.get_output_index(), sourcetype='strava:activities:stream', data=json.dumps(event)) helper.log_info(f'Added activity stream {activity_id} for {athlete_id}.') return True def return_json(url, method, **kwargs): """Gets JSON from URL and parses it for potential error messages.""" response = helper.send_http_request(url, method, use_proxy=False, **kwargs) try: response.raise_for_status() except requests.HTTPError as ex: # status code 429 means we hit Strava's API limit, wait till next 15 minute mark (+5 seconds) and try again if ex.response.status_code == 429: # Get the 15m/24h API limits for this user api_usage_15m = response.headers['X-RateLimit-Usage'].split(",")[0] api_usage_24h = response.headers['X-RateLimit-Usage'].split(",")[1] api_limit_15m = response.headers['X-RateLimit-Limit'].split(",")[0] api_limit_24h = response.headers['X-RateLimit-Limit'].split(",")[1] timestamp_now = int(time.time()) modulus_time = timestamp_now % 900 sleepy_time = 0 if modulus_time == 0 else (900 - modulus_time + 5) helper.log_warning(f'Strava API rate limit hit. Used {api_usage_15m}/15min (limit {api_limit_15m}), {api_usage_24h}/24h (limit {api_limit_24h}). Sleeping for {sleepy_time} seconds.') time.sleep(sleepy_time) response = return_json(url, method, **kwargs) helper.log_debug(f'429 detail: {response}') return response if ex.response.status_code in (400, 401): helper.log_error(f'{ex.response.status_code} Error: Strava API credentials invalid or session expired. Make sure Client ID & Client Secret have been added to the Configuration -> Add-On Parameters tab and your access code is valid.') sys.exit(1) if ex.response.status_code == 404: helper.log_warning(f'404 Error: no stream data for url {url}, can happen for manually added activities.') return False if ex.response.status_code == 500: helper.log_warning(f'500 Error: no data received from Strava API for url {url}, it might be corrupt or invalid. Skipping activity.') return False # In case there's any other error than the ones described above, log the error and exit. helper.log_error(f'Error: {ex}') sys.exit(1) # Must have been a 200 status code return response.json() def set_athlete(response): """Creates dict with athlete details, including token expiry.""" name = response['athlete']['firstname'] + " " + response['athlete']['lastname'] athlete = { 'id': response['athlete']['id'], 'name': name, 'access_token': response['access_token'], 'refresh_token': response['refresh_token'], 'expires_at': response['expires_at'], 'ts_activity': 0} return athlete def write_to_splunk(**kwargs): """Writes activity to Splunk index.""" event = helper.new_event(**kwargs) ew.write_event(event) # get configuration arguments client_id = helper.get_global_setting('client_id') client_secret = helper.get_global_setting('client_secret') access_code = helper.get_arg('access_code') start_time = helper.get_arg('start_time') or 0 types = ['time', 'distance', 'latlng', 'altitude', 'velocity_smooth', 'heartrate', 'cadence', 'watts', 'temp', 'moving', 'grade_smooth'] # stanza is the name of the input. This is a unique name and will be used as a checkpoint key to save/retrieve details about an athlete stanza = list(helper.get_input_stanza())[0] athlete = helper.get_check_point(stanza) helper.log_debug(f'Athlete: {athlete}') # if reindex_data checkbox is set, update the start_time to be the one specified and clear the checkbox. if helper.get_arg('reindex_data'): if int(helper.get_arg('reindex_data')) == 1: athlete.update({'ts_activity': start_time}) helper.save_check_point(stanza, athlete) # the clear_checkbox function will restart this input as soon as the change is made, so no further code required. clear_checkbox(helper.context_meta['session_key'], stanza) # if athlete is set, get details & tokens - otherwise fetch tokens with get_token() if athlete: athlete_id = athlete['id'] athlete_name = athlete['name'] expires_at = athlete['expires_at'] refresh_token = athlete['refresh_token'] else: expires_at = False refresh_token = False # Check if expires_at token is set and renew token if token expired. Otherwise fetch token with initial access code. if expires_at: if time.time() >= expires_at: response = get_token(client_id, client_secret, refresh_token, renewal=True) helper.log_debug(f"Access token: {response['access_token']}, refresh token: {response['refresh_token']}") athlete.update({'access_token': response['access_token'], 'refresh_token': response['refresh_token'], 'expires_at': response['expires_at']}) else: response = get_token(client_id, client_secret, access_code, renewal=False) athlete = set_athlete(response) athlete_id = athlete['id'] athlete_name = athlete['name'] helper.save_check_point(stanza, athlete) access_token = athlete['access_token'] athlete_detail = get_athlete(access_token) athlete_firstname = athlete_detail['firstname'] athlete_lastname = athlete_detail['lastname'] athlete_weight = '' athlete_ftp = '' if athlete_detail['resource_state'] == 3: athlete_weight = athlete_detail['weight'] athlete_ftp = athlete_detail['ftp'] helper.log_debug("Saving athlete's details to KV Store.") kvstore_save_athlete(helper.context_meta['session_key'], str(athlete_id), athlete_firstname, athlete_lastname, str(athlete_weight), str(athlete_ftp)) # For backwards compatibility with upgrades from pre-2.5.0, which uses athlete['ts_newest_activity']. If there, clean them up. if 'ts_newest_activity' in athlete: helper.log_info(f"Found existing timestamp {athlete['ts_newest_activity']}! Will remove it now.") ts_activity = athlete['ts_newest_activity'] athlete.update({'ts_activity': ts_activity}) athlete.pop('ts_newest_activity') athlete.pop('get_old_activities') athlete.pop('ts_oldest_activity') helper.save_check_point(stanza, athlete) else: ts_activity = athlete['ts_activity'] or start_time # webhook_updates contains updated activities that came in via webhook. webhook_updates = helper.get_check_point('webhook_updates') or {} if str(athlete_id) in webhook_updates: for activity in webhook_updates[str(athlete_id)][:]: helper.log_info(f'Received update via webhook for activity {activity} from athlete {athlete_id}') response = get_activity(activity, access_token) ts_activity = get_epoch(response['start_date']) # Store the event in Splunk write_to_splunk(index=helper.get_output_index(), sourcetype=helper.get_sourcetype(), data=json.dumps(response)) # Get stream data for this activity and write to Splunk stream_data = get_activity_stream(access_token, activity, types) if stream_data: parse_data(stream_data, activity, ts_activity) # Remove from dict and save dict webhook_updates[str(athlete_id)].remove(activity) helper.save_check_point('webhook_updates', webhook_updates) helper.log_info(f'Got all webhook events for athlete {athlete_id}') helper.log_info(f'Checking if there are new activities for {athlete_name} ({athlete_id})') while True: response_activities = get_activities(ts_activity, access_token) # if all activities retrieved, set get_old_activities, save checkpoint and end loop to finish if len(response_activities) == 0: # pylint: disable=no-else-break helper.log_info(f'All done, got all activities for {athlete_name} ({athlete_id})') break else: # Get more details from each activity for event in response_activities: activity_id = event['id'] response = get_activity(activity_id, access_token) # response = False for a 500 Error, which is likely an invalid Strava API file. In that case skip the activity and continue. if response: data = json.dumps(response) # Get start_date (UTC) and convert to UTC timestamp ts_activity = get_epoch(event['start_date']) # Store the event in Splunk write_to_splunk(index=helper.get_output_index(), sourcetype=helper.get_sourcetype(), data=data) helper.log_info(f'Added activity {activity_id} for {athlete_id}.') # Get stream data for this activity stream_data = get_activity_stream(access_token, activity_id, types) if stream_data: parse_data(stream_data, activity_id, ts_activity) # Save the timestamp of the last event to a checkpoint athlete.update({'ts_activity': ts_activity}) helper.save_check_point(stanza, athlete)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n print(dumps(get_data()))\n return 0", "def main():\n print get_latest_data()", "def get_data():\n pass", "def get_data():\n pass", "def get_data():\n pass", "def get_data():\n pass", "def get_data():\n return", "def main():\n logger = logging.getLogger(__n...
[ "0.6757108", "0.63172305", "0.6213477", "0.6213477", "0.6213477", "0.6165671", "0.5924254", "0.5922558", "0.57879984", "0.57552046", "0.57526654", "0.5694825", "0.5639846", "0.563431", "0.55584145", "0.5550838", "0.55116856", "0.55113345", "0.55080515", "0.54997003", "0.54927...
0.0
-1