query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Reads and parses the extension's metadata from manifest.json
def _read_manifest_json(self): with open(os.path.join(self._crx_dir, "manifest.json")) as manifest: return json.load(manifest)
[ "def read_manifest(self): # -> None:\n ...", "def readManifestEntries(context):\n return GenericMetadata._readEntriesForSection(context.projectDir, GenericMetadata.MANIFEST_SECTION)", "def read_manifest(self, manifest):\n\n ## your code goes here\n pass", "def parse_manifest(manif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes an updated EV whitelist into the extension. Each new EV whitelist must be uploaded with a version number greater than the current version, so increments the version number.
def update_ev_whitelist(self, compressed_ev_whitelist): manifest = self._read_manifest_json() manifest["version"] = str(self.manifest_version() + 1) self._write_manifest_json(manifest) with open( os.path.join( self._crx_dir, "_platform_specific...
[ "def whitelist_file(self, fkey):\n self.whitelist.update([fkey])", "def generate_new_ev_hashes_whitelist(logs_list):\n all_hashes_set = set()\n for log_url, last_acceptable_entry in logs_list.items():\n output_dir = None\n if FLAGS.output_directory:\n parsed_url = urlparse.ur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Packs the extesion to the provided destination. Note that the provided dest_file_template is a template string so the version number can be filled in. Returns the exact file name that was written.
def pack_to(self, dest_file_template): fname = dest_file_template % self.manifest_version() shutil.make_archive(fname, "zip", self._crx_dir) return fname
[ "def pack(output_filename, sources):\n dirname = os.path.dirname(output_filename)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n ext = os.path.splitext(output_filename)[1][1:]\n if ext == 'zip':\n pack_zip(output_filename, sources)\n elif ext in ('gz', 'tgz', 'bz2', 'tar'):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes the directory containing the unpacked crx.
def cleanup(self): shutil.rmtree(self._crx_dir) self._crx_dir = None
[ "def __remove_base_directory__():\n p = subprocess.Popen('rm -rf {}/.wcscanner'.format(context.__BASE_PATH__), shell=True)\n p.wait()", "def RemoveCase(dirc):\n if os.path.exists(dirc):\n shutil.rmtree(dirc)\n #subprocess.call(['rm', '-r', dirc])", "def cleanup_dir(self):\n for copied_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scans the provided logs_list and generates a compressed EV certs whitelist for all EV certs in all the logs.
def generate_new_ev_hashes_whitelist(logs_list): all_hashes_set = set() for log_url, last_acceptable_entry in logs_list.items(): output_dir = None if FLAGS.output_directory: parsed_url = urlparse.urlsplit(log_url) output_dir = os.path.join( FLAGS.output_di...
[ "def _sonar_extend_certfiles(self, hostfiles, certfiles):\n existing_names = set([os.path.basename(x['name']) for x in certfiles])\n for rec in hostfiles:\n name = rec['name']\n bname = os.path.basename(name)\n parts = bname.split('_', 1)\n certfile_bname = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all feedback or create a new feedback
def feedback_list(request, format=None): if request.method == 'GET': feedback = Feedback.objects.all() serializer = FeedbackSerializer(feedback, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = FeedbackSerializer(data=request.data) ...
[ "def feedback(self, request, pk=None):\n user = self.get_object()\n feedback = Feedback.objects.filter(sender_id=user)\n serializer = FeedbackSerializerList(feedback, many=True)\n return Response(serializer.data)", "def list_feedback(request):\r\n return render(request, \"index/list...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Nhập địa chỉ file và kiểm tra trong thư mục có file csv theo đã nhập thông qua thư viện glob Nếu có lưu vào địa chỉ file url Nếu không trả về false và địa chỉ url = None
def Input_url(self,url,path_folder): print("Bạn yêu cầu file ở địa :{}".format(path_folder+url)) if len(glob.glob(path_folder+url, recursive=True) )>0: print("File data ở :{}".format(path_folder+url)) self.url=path_folder+url return False else: ...
[ "def getFile(self, fi):", "def nouveau_csv(nom, chemin=str(cfg.chemins['cheminLogs'])):\n nom = chemin + '/' + nom + '.csv'\n file = open(nom, \"wb\")\n file.close()\n return 'Le fichier ' + nom + ' a été créé'", "def file_message(self, update, context):\n # asigns file_tipe according to the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find nearby membrane vertices for cellcell interactions
def find_nearby_membranes(all_membranes, all_membrane_map, vert_normals): membrane_tree = scipy.spatial.cKDTree(all_membranes) nearby_membranes = np.array(list(membrane_tree.query_pairs(adhesion_max_dist, p=2))) nearby_membrane_map = defaultdict(list) if nearby_membranes.shape[0] > 0: # Exc...
[ "def get_near(self,map):\n near_cells = []\n for i in range(self.x-1, self.x+2):\n for j in range(self.y-1, self.y+2):\n if(i>=0 and i<map.size and j>=0 and j<map.size): near_cells.append(map.search(i,j))\n return near_cells", "def nearby_cells(self, cell):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes parameter identifiability for a PEST jco file,
def __init__(self, jco, par_info_file=None): self._Pest = Pest(jco, par_info_file=par_info_file) self.parinfo = self._Pest.parinfo self.la = errvar(jco) self.parinfo = None if par_info_file is not None: self.parinfo = pd.read_csv(par_info_file, index_col='Name') ...
[ "def test_parameters_mentioned(tests_path, jfname, pfname):\n # read JSON parameter file into a dictionary\n path = os.path.join(tests_path, '..', jfname)\n pfile = open(path, 'r')\n allparams = json.load(pfile)\n pfile.close()\n assert isinstance(allparams, dict)\n # read PYTHON code file text...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample points in [0, 1] x [0, 1] coordinate space based on their uncertainty. The unceratinties are calculated for each point using 'uncertainty_func' function that takes point's logit prediction as input. See PointRend paper for details.
def get_uncertain_point_coords_with_randomness( coarse_logits, uncertainty_func, num_points, oversample_ratio, importance_sample_ratio ): assert oversample_ratio >= 1 assert importance_sample_ratio <= 1 and importance_sample_ratio >= 0 num_boxes = coarse_logits.shape[0] num_sampled = int(num_points ...
[ "def uncertainty(self):\n \n scnl,picks,trigger,SNR = self.pick_ident()\n dt = self.stats.delta\n npts_Tma = int(round(self.picker.uncert_coeff / dt, 0))\n t = np.arange(0, self.stats.npts / self.stats.sampling_rate, dt) \n pick_uncert = copy.deepcopy(trigger)\n\n for i in range(len(trigger)):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find `num_points` most uncertain points from `uncertainty_map` grid.
def get_uncertain_point_coords_on_grid(uncertainty_map, num_points): R, _, H, W = uncertainty_map.shape h_step = 1.0 / float(H) w_step = 1.0 / float(W) num_points = min(H * W, num_points) point_indices = torch.topk(uncertainty_map.view(R, H * W), k=num_points, dim=1)[1] point_coords = torch.zer...
[ "def unstable_locs(grid):\n return np.argwhere(grid >= 4)", "def uncertainty_sampling(nn_main, sess_main, X, pool_size=None):\n\n temp = find_k_most_uncertain(nn_main, sess_main, X, k=1,\n pool_size=pool_size)\n\n return temp[0]", "def get_most_nnp(nps):\n counts_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get features from feature maps in `features_list` that correspond to specific point coordinates inside each bounding box from `boxes`.
def point_sample_fine_grained_features(features_list, feature_scales, boxes, point_coords): cat_boxes = Boxes.cat(boxes) num_boxes = [len(b) for b in boxes] point_coords_wrt_image = get_point_coords_wrt_image(cat_boxes.tensor, point_coords) split_point_coords_wrt_image = torch.split(point_coords_wrt_im...
[ "def _extract_box_classifier_features(self, proposal_feature_maps, scope):\r\n with tf.variable_scope(self._architecture, reuse=self._reuse_weights):\r\n with slim.arg_scope(nets.resnet_utils.resnet_arg_scope(\r\n batch_norm_epsilon=1e-5,\r\n batch_norm_scale=True,\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We estimate uncerainty as L1 distance between 0.0 and the logit prediction in 'logits' for the foreground class in `classes`.
def calculate_uncertainty_ins_seg(logits, classes): if logits.shape[1] == 1: gt_class_logits = logits.clone() else: gt_class_logits = logits[ torch.arange(logits.shape[0], device=logits.device), classes ].unsqueeze(1) return -(torch.abs(gt_class_logits))
[ "def calculate_uncertainty(logits):\n assert logits.shape[1] == 1\n gt_class_logits = logits.clone()\n return -(torch.abs(gt_class_logits))", "def multiclass_focal_entropy(phat, y, N_classes, weights, gamma, EPS = 1e-15) :\n\n y = F.one_hot(y, N_classes)\n loss = -y * torch.pow(1 - phat, gamma) * t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Forward logic of the coarse mask head.
def _forward_mask_coarse(self, features, boxes): point_coords = generate_regular_grid_point_coords( np.sum(len(x) for x in boxes), self.mask_coarse_side_size, boxes[0].device ) mask_coarse_features_list = [features[k] for k in self.mask_coarse_in_features] features_scales = [...
[ "def _find_front(self):\n self.front = (laplace(self.working_mask) > 0).astype('uint8')\n # TODO: check if scipy's laplace filter is faster than scikit's", "def Naive_forwardpass(self):\n\n for filter_k in range(0, self.n_filters):\n filter_col = self.im2col(self.filter_map[filter_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For each location of the prediction `sem_seg_logits` we estimate uncerainty as the difference between top first and top second predicted logits.
def calculate_uncertainty_sem_seg(sem_seg_logits): top2_scores = torch.topk(sem_seg_logits, k=2, dim=1)[0] return (top2_scores[:, 1] - top2_scores[:, 0]).unsqueeze(1)
[ "def calculate_uncertainty_ins_seg(logits, classes):\n if logits.shape[1] == 1:\n gt_class_logits = logits.clone()\n else:\n gt_class_logits = logits[\n torch.arange(logits.shape[0], device=logits.device), classes\n ].unsqueeze(1)\n return -(torch.abs(gt_class_logits))", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store [value] under [key]. Overwrites previous value.
def put(self, key, value): self._store[key] = value
[ "def _put(self, key, value):\n node_with_key = self._check_key(key, self._head)\n if node_with_key is None:\n # add a new key value pair\n old_head = self._head\n self._head = UnOrderedSeqST._Node(key, value, old_head)\n else:\n # update the key with ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store [value] in file named [key]. Overwrites previous file.
def put(self, key, value): self.execute_command('sudo -i bash -c \'echo -n "{0}" > {1}{2}\'' .format(value, self._store_path, key))
[ "def append(self, key, value):\n must_write_header = not key in self\n value = self._to_frame(value)\n with self._open(self.filename(key), 'a') as buf:\n if must_write_header:\n self._write_header(buf, value)\n self._write_data(buf, value)", "def write_bra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get value stored in file named [key] if it exist, None otherwise.
def get(self, key): output = self.execute_command( 'sudo -i bash -c \'if [ -f "{0}" ]; then cat "{0}"; else echo -n "FILE_NOT_FOUND"; fi\''.format( self._store_path + key)) value = return_fixed_output(output) return None if value == 'FILE_NOT_FOUND' else value
[ "def get_value_for(self, key):\n try:\n if not os.path.exists(self.filepath):\n raise\n return self._get_value_for(key)\n\n except:\n return \"\"", "def get_file(self, key):\n return self.get('file', key)", "def get(self, key):\n index1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses value read from appstack and apply expression if it is recognized as expression.
def parse_and_apply_expression(self, key, value): if RANDOM_EXPRESSION_PATTERN.match(str(value)): return self._store.get(key) or self._genarate_and_save_random(key, value) return value
[ "def eval(self, token):\n value = tokenToValue(token)\n try:\n if value.startswith(\"'\"):\n self.stack.append(value[1:])\n elif value.startswith('\"') or value.startswith('['):\n self.stack.append(value)\n else:\n f = self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determina a matriz de Sylvester com o numerador e denominador dados. Parâmetros
def sylv(num,den): n, m = len(num)-1, len(den)-1 N = max([n,m]) S = np.zeros( [ 2*N, 2*N ] ) for i in range(0,N): S[i][i:m+1+i] = den[::-1] S[i+N][i:n+1+i] = num[::-1] S = S.transpose() return S
[ "def q_ary_syndrome_calculation(c, m, gf_add, gf_mul, vals, rows):\r\n\r\n s = galois.dot_product(c, m, gf_add, gf_mul, vals, rows)\r\n return s", "def opDif(n, vetx, vety):\n\n mat = [0]*n\n for i in range(0, n):\n mat[i] = [0]*n\n mat[i][0] = vety[i]\n for i in range(1, n):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retorna os polos não dominantes de um sistema de ordem ``n``. Os polos não dominantes devem estar localizados uma década abaixo do polo dominantes mais rápido. Parâmetros
def polos_nondom(p1, n, pond=1): pond = abs(pond) p = 10*np.real(p1) - pond*np.arange(0, n-2) return p
[ "def getNeuropils(self):\n res = {}\n res['query'] = []\n res['format'] = 'nx'\n res['user'] = 'test'\n res['temp'] = True\n res['query'].append({'action': {'method': {'traverse_owned_by': {'cls': 'Neuropil'}}},\n 'object': {'state': 0}})\n res = self.execu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Função que criar uma sequência de degraus uniformes a partir de uma lista com as amplitudes, o espaçamento e o tempo de cada degrau. Parâmetros
def makeSteps(lists, T, dt): n, m = len(lists), int(T/dt) # n° de steps, qnt de valores t = np.arange(0, n*T, dt) # Tempo de simulação u = np.zeros_like(t) # Pré-alocação for i in range(n): u[i*m:(i+1)*m] = lists[i] # Seq. stesp u[-1] = lists[n-1] # Atualiza último valor return t, u
[ "def M_D_1(arrival_time,max_time,service_time=1/90):\n #conversion in seconds\n max_seconds = max_time*60*60\n sim_time = 0.0 # simulation time\n t_1 = 0.0 # time for next event (arrival)\n t_2 = max_seconds # time for next event (departure)\n t_n = 0.0 #last event time--> tempo dell'ultimo avveni...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cria um controlador PID com base nos parâmetros K, Ti, Td. É possível utilizar um filtro N no derivativo. A dedução foi feita adotando
def PID(K, Ti, Td, N=None): #assert K != 0 and Ti != 0 and Td != 0, 'Os parâmetros não podem ser todos nulos' assert K != 0, 'O ganho do controlador não pode ser nulo!' assert Ti != 0, 'O ganho do integrador não pode ser nulo' if N is not None: assert N > 0, 'Valor inválido para N!' if Ti i...
[ "def sintoniaPID(param, met='ZN',C='PID', modo=None):\n\n met, C = met.upper(), C.upper()\n # Tabela correspondente aos métodos de sintonia\n table = [\n [ #Método 'ZN'\n [1.2, 2, 0.5], # PID\n [0.9, 1/0.3, 0], # PI\n [1, np.inf, 0]], # P\n [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sintoniza um controlador PID, PI ou P com base nos parâmetros do modelo identificado e no método pedido. Parâmetros
def sintoniaPID(param, met='ZN',C='PID', modo=None): met, C = met.upper(), C.upper() # Tabela correspondente aos métodos de sintonia table = [ [ #Método 'ZN' [1.2, 2, 0.5], # PID [0.9, 1/0.3, 0], # PI [1, np.inf, 0]], # P [ #Método ITAE ...
[ "def set_pid(self,p=100,i=10,d=0):\r\n try:\r\n gpib_lock.acquire() \r\n self.lakeshore.write('CMODE 1,1')\r\n #log('PID 1,%i,%i,%i'%(p,i,d))\r\n self.lakeshore.write('PID 1,%i,%i,%i'%(p,i,d))\r\n except Exception,e:\r\n log(\"Failed to set ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> from sklearn import svm >>> X = [[0,0],[1,1]] >>> y = [0,1] >>> clf=svm.SVC() >>> clf.fit(X,y) SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) >>> clf.predict([[2.,2.]]) array([1])...
def svmtrain(x,y,w=None): # xl = x.tolist() # yl = y.tolist() clf = svm.SVC(kernel='linear', C=1000) # apparently C param here really matters clf.fit(x,y) return({'w':clf.coef_, 'b':clf.intercept_,'clf':clf, 'n_support':clf.support_vectors_.shape[0]})
[ "def svmClassifier(trainData, testData ,yPos, kernel, c, gamma):\n model = svm.SVC(kernel=kernel, C=c, gamma=gamma)\n # outcome and parameters\n y = np.array([x[yPos] for x in trainData])\n X = np.array([x[0:yPos] for x in trainData])\n # fit and calculate\n model.fit(X, y)\n # model.score(X, y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether an edgework view has been attached. Quits otherwise.
def check_edgework_view_attached(self) -> None: if not isinstance(self._edgework_view, EdgeworkView): raise TypeError("Edgework view not attached to bomb model.")
[ "def is_complete(self) -> bool:\n return self.plot_task.dataSet.figure_exists(\n self.plot_task, self.figure_name(), type(self).__module__.split(\".\")[-1]\n )", "def has_edge(self, e):\r\n return e in self.edges", "def isOn(self):\r\n return len(self.__agenda)>2", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stores the reference to the BombModel's module list.
def attach_module_list(self, modules) -> None: self.modules = modules self.draw_modules()
[ "def save(self):\n self._saved_modules = set(self._sys_modules.keys())", "def update_Modules(self):\n module_List = self.controller.getModules()\n self.listbox.delete(0, \"end\")\n for modules in module_List:\n self.listbox.insert(\"end\", modules.getName())", "def clear_mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the amount of strikes shown on EdgeworkView.
def update_strikes(self, strikes: int) -> None: strike_str = "-" if strikes == 0 else "X" * strikes self._strike_label.config(text=strike_str)
[ "def strikes(self, strikes):\n\n self._strikes = strikes", "def num_spikes(self):\n return self._num_spikes", "def update_likes(self):\n self.nb_likes = self.likes.count()\n self.save()", "def update_total(self):\r\n likes = 0.00\r\n\r\n if self.get_hamburger.get():\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a random barcode of the form FLIM, where the are alphanumeric characters. That gives a random range of 60 million possible barcodes.
def new_barcode(num_digits=5, chars=string.digits+string.uppercase): return 'FLIM-'+(''.join([random.choice(chars) for _ in xrange(num_digits)]))
[ "def gen_code():\n return ''.join([random.choice(string.ascii_uppercase + string.digits) for _ in range(10)])", "def generate_barcode(length=6):\n return generate_nucleotide_sequence(seq_length=length)", "def __generate_number_boleto_fake(self):\n numbers = \"0123456789\"\n return \"\".join(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the work order from an orders file. The file must have lines like "===ORDER 6===" to announce its orders. If multiple orders matching are found, the latest is returned. Returns None if no matching order is found.
def read_work_order(order_id, file): ptn = re.compile(r'^===ORDER ?([0-9]*)===') lines = None on = False with open(file, 'r') as fin: for line in fin: m = ptn.match(line) if m: g = m.group(1) if g and int(g)==order_id: o...
[ "def read_orders():\n\n orders_deserialized = []\n with open(\"orders.txt\", \"rb+\") as pickle_file:\n while True:\n try:\n orders_deserialized.append(pickle.load(pickle_file))\n except FileNotFoundError:\n print(\"I'm a p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starting from the given order (dict), creates a "complete order" message (another dict), containing updated material, new materials, and a new container.
def make_complete(order): order = order['work_order'] materials = order['materials'] updated_materials = [] parent_ids = [] if materials: m = materials[0] g = 'male' if m.get('gender')=='female' else 'female' updated_materials.append({'material_id': m['material_id'], 'gender'...
[ "def _create_add_message_from_order(order):\n message = {}\n message.update({\"message-type\": \"A\"})\n message.update({\"instrument\": order.instrument})\n message.update({\"order-id\": order.order_id})\n message.update({\"price\": int(order.price)})\n message.update({\"quantity\": int(order.qua...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the order from a file; constructs a "complete order" message, and sends that to the given url (if a url is given).
def complete_order(order_id, filename, url, proxy): order_json = read_work_order(order_id, filename) if order_json is None: raise LookupError("No order found with id %r"%order_id) order = json.loads(order_json) message = make_complete(order) data = json.dumps(message, indent=4) print dat...
[ "def read_work_order(order_id, file):\n ptn = re.compile(r'^===ORDER ?([0-9]*)===')\n lines = None\n on = False\n with open(file, 'r') as fin:\n for line in fin:\n m = ptn.match(line)\n if m:\n g = m.group(1)\n if g and int(g)==order_id:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the abelectronicsiopi binary sensors.
def setup_platform(hass, config, add_devices, discovery_info=None): pull_mode = config[CONF_PULL_MODE] invert_logic = config[CONF_INVERT_LOGIC] iopi = IOPi(config.get(CONF_I2C_ADDRESS), True) binary_sensors = [] pins = config[CONF_PINS] for pin_num, pin_name in pins.items(): ...
[ "def _init_io(self):\n GPIO.setwarnings(False)\n GPIO.setmode( GPIO.BCM )\n pins = [ self._spi_dc ]\n for pin in pins:\n GPIO.setup( pin, GPIO.OUT )", "def setup():\n GPIO.setmode(GPIO.BOARD)\n GPIO.setwarnings(False)\n GPIO.setup(list(PINS_X.values()), GPIO.OUT, in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the GPIO state.
def update(self): self._state = self.iobus.read_pin(self.targetpin)
[ "def update(self):\n self._state = self._pin.value", "def updateInput(self):\r\n if self.isInput():\r\n state = pi.input(self.gpi)\r\n self.state = state\r\n self.updateLED()", "def set(self, state):\n self.state = state\n self.client.put('/control/gp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Liest Daten des Referenzsensor aus txt Dokument und erstellt Referenzklasse
def referenzdaten_einlesen(self): self.refdata = np.genfromtxt(self.referencefile, skip_header=1, usecols=np.asarray(self.referenzspalte)) self.Referencedata = Reference()
[ "def __init__(self):\n self.file_name = 'moes_tavern_lines.txt'\n self.path_to_file = abspath(join(getcwd(), '../data',\n self.file_name))", "def read_data(self, loc):\n pass", "def read_data(self):\n pass", "def load_data(self):", "def ext...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Records audio frames Opens a stream to record audio through builtin mic.
def record_audio(self): stream = self.audio.open(format=DEFAULT_FORMAT, channels=DEFAULT_CHANNELS, rate=DEFAULT_RATE, input=True, frames_per_buffer=DEFAULT_CHUNK_SIZE) pri...
[ "def recorder():\n # Following block gets rid of annoying config errors by ALSA\n def py_error_handler(filename, line, function, err, fmt):\n pass\n ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p)\n c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)\n asoun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves audio file. Saves recorded audio file in local storage in wave format.
def save_audio(self, name=DEFAULT_OUT_NAME): print("Saving...") wf = wave.open(name+'.wav', 'wb') wf.setnchannels(DEFAULT_CHANNELS) wf.setsampwidth(self.audio.get_sample_size(DEFAULT_FORMAT)) wf.setframerate(DEFAULT_RATE) wf.writeframes(b''.join(self.frames)) wf.c...
[ "def save_audio_file(self):\n\n # has not recorded audio\n if not self.is_audio_record:\n print(\"***you did not set the record flag!\")\n return\n\n import soundfile\n\n # save audio\n soundfile.write('{}out_audio.wav'.format(self.mic_params['plot_path']), self.collector.x_all, self.featur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets recorded audio frames.
def get_recorded_audio(self): return self.frames
[ "def record_audio(self):\n stream = self.audio.open(format=DEFAULT_FORMAT,\n channels=DEFAULT_CHANNELS,\n rate=DEFAULT_RATE,\n input=True,\n frames_per_buffer=DEFAULT_CHUNK_SIZE)\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse all csv files for all available days.
def parse_csv(db: sqlite3.Connection, symbols_meta): logger.info('Parsing csv files for days.') csv_directory = settings.DATA_DIRECTORY / 'csv' # Get list of days by enumerating csv files in directory. csv_list = sorted(os.listdir(csv_directory), reverse=False) for jdx, f in enumerate(csv_list): ...
[ "def parse_csv_file(self):\n self.check_file_exists()\n parsed_data = None\n with open(self.file_name) as csv_fh:\n reader = csv.DictReader(csv_fh)\n for row in reader:\n\n # check if csv file contains data for each separate working week day\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that well formed bad placements raise PlayerInvalidPlacement
def test_bad_placement(self): board = Board() player1 = LegitPlayer() player2 = BadPlacementPlayer() player1.start_of_game() player2.start_of_game() player_guard1 = PlayerGuard(player1, timeout=3) player_guard2 = PlayerGuard(player2, timeout=3) # set ids ...
[ "def test_get_valid_placement(self):\n # returns different locations on the board (indexed locations)\n self.assertEqual(tictactoe.get_valid_placement(\"1\"), 0)\n self.assertEqual(tictactoe.get_valid_placement(\"5\"), 4)\n self.assertEqual(tictactoe.get_valid_placement(\"9\"), 8)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that well formed bad turns raise PlayerInvalidTurn
def test_bad_turn(self): board = Board() player1 = LegitPlayer() player2 = BadTurnPlayer() player1.start_of_game() player2.start_of_game() player_guard1 = PlayerGuard(player1) player_guard2 = PlayerGuard(player2) # set ids p1id = uuid.uuid4() ...
[ "def test_turns():\n g = server.gameState.GameState()\n\n assert g.get_turn() == \"black\"\n g.proc_move(\"A1-B2\")\n assert g.get_turn() == \"white\"\n g.proc_move(\"G7-G8\")\n assert g.get_turn() == \"black\"\n\n # Preview shouldn't update the turn\n g.proc_move(\"B1-A1\", True)\n asser...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that unowned worker placement gives the correct Exception
def test_bad_worker(self): board = Board() player1 = LegitPlayer() player2 = BadWorkerPlayer() player1.start_of_game() player2.start_of_game() player_guard1 = PlayerGuard(player1, timeout=3) player_guard2 = PlayerGuard(player2, timeout=3) # set ids ...
[ "def test_exception_in_worker_process(self):\n\n # NOTE: The process pool has a problem that if the workers are throwing exceptions, their\n # zmq sockets will be closed and there is some race condition that can cause the ventilate\n # to raise an exception. Only ventilating a single time guara...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that players who throw exceptions get filtered to our Exception
def test_exception_player(self): board = Board() player1 = ExceptionPlayer() player_guard1 = PlayerGuard(player1, timeout=3) # set ids p1id = uuid.uuid4() self.assertRaises(PlayerRaisedException, player_guard1.set_id, p1id) self.assertRaises(PlayerRaisedExcepti...
[ "def testException(self):\n self.assertFalse(self.testObject.testWithExcept())\n self.assertFalse(self.testObject.failed)\n self.assertTrue(self.testObject.hasExecuted)", "def test_exception():", "def test_malformed_player(self):\n board = Board()\n player1 = MalformedDataPlay...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that players who stall for time (sleep) are timed out and a timeout exception is thrown
def test_sleep_player(self): board = Board() player1 = SleepPlayer() player_guard1 = PlayerGuard(player1, timeout=1) p1id = uuid.uuid4() self.assertRaises(PlayerTimeout, player_guard1.set_id, p1id) self.assertRaises(PlayerTimeout, player_guard1.start_of_game) s...
[ "def testSleeping(self):\n time.sleep(2 * 60)\n raise AssertionError('Test case should have timed out.')", "def test_wait_non_existing(self):\n allowable_error = .2\n\n start = timestamp()\n self.assertRaises(TimeoutError, self.app.BlahBlah.wait, 'exists')\n expected = Ti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that players who return malformed data give the correction Exception
def test_malformed_player(self): board = Board() player1 = MalformedDataPlayer() player_guard1 = PlayerGuard(player1, timeout=3) p1id = uuid.uuid4() player_guard1.set_id(uuid.uuid4()) self.assertRaises(PlayerMalformedData, player_guard1.place_worker, board) sel...
[ "def test_bad_match(self):\n log.info('===== START TEST BAD MATCH =====')\n\n # Telemetered\n file_path = os.path.join(RESOURCE_PATH, '11129553_SNA_SNA.txt')\n\n stream_handle = open(file_path, MODE_ASCII_READ)\n\n self.create_parser(stream_handle)\n\n particles = self.pars...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the master brightness for the LEDs 0.0 1.0
def set_master_brightness(self, bright): if bright > 1.0 or bright < 0.0: raise ValueError('Brightness must be between 0.0 and 1.0') self.master_brightness = bright
[ "def set_brightness(self, value: int, /) -> None:", "def set_brightness(brightness):\n global _brightness\n _brightness = brightness", "def changeBrightness(self):\n self.brightnessControl.value = (\n self.brightnessControl.value - .25) % 1.25", "def set_level(self, value):\n va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the response from the Spot API.
async def handle_response(self, response: list) -> None: event: pycot.Event = spotcot.spot_to_cot(response) if event: await self._put_event_queue(event) else: self._logger.debug("Empty CoT Event for response='%s'", response)
[ "def process_response(self, response):\n pass", "async def _get_spot_feed(self):\n self._logger.debug(\"Polling Spot API\")\n async with aiohttp.ClientSession() as session:\n response = await session.request(\n method=\"GET\",\n url=self.spot_url,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets Spot Feed from API.
async def _get_spot_feed(self): self._logger.debug("Polling Spot API") async with aiohttp.ClientSession() as session: response = await session.request( method="GET", url=self.spot_url, params=self.params ) json_resp = aw...
[ "def get_feed():\n url = f\"{BASE_URL}{constants['paths']['FEED']}\"\n return Base()._request(url, auth=True)", "def get_spot_datafeed_subscription(self):\r\n return self.get_object('DescribeSpotDatafeedSubscription',\r\n None, SpotDatafeedSubscription, verb='POS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves every bullet and checks collision with enemy
def move_bullets(self, vel, enemies): self.cooldown(SCREEN) for bullet in self.bullets: bullet.move(vel) if bullet.off_screen(HEIGHT): self.bullets.remove(bullet) else: for enemy in enemies: if bullet.bullet_collisio...
[ "def test_player_bullet_collision(self):\n self.alien.shooting([320, 300], 5, False)\n self.assertFalse(collisions.collide(self.alien.bullets[0], self.player))\n\n for i in range(25):\n self.alien.bullets[0].movement()\n\n self.assertTrue(collisions.collide(self.alien.bullets[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw player (via super), health bar and bullets that are being shot
def draw(self, window): super().draw(window) self.health_bar(window) for bullet in self.bullets: bullet.draw(window)
[ "def draw(self, win, enemy):\r\n for b in self.my_bullets:\r\n if enemy.x < b.x < enemy.x + enemy.width and enemy.y < b.y < enemy.y + enemy.height:\r\n self.my_bullets.remove(b)\r\n elif 0 < b.x < win_width:\r\n b.draw(win)\r\n else:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a green and red bar that shows HP under the player
def health_bar(self, window): pygame.draw.rect(window, (255, 0, 0), (self.x, self.y + self.character_img.get_height() + 10, self.character_img.get_width(), 10)) pygame.draw.rect(window, (0, 255, 0), (self.x, self.y + self.character_img.get_height() + 10, self.character_img.get_width() * (self.health / s...
[ "def draw_health_bar(self, win):\n pygame.draw.rect(win ,GREEN,[self.x-8,self.y-40,(self.health/self.max_health)*30,5])\n pygame.draw.rect(win ,RED,[self.x+7,self.y-40,30-((self.health/self.max_health)*30),5])", "def display_health_bar(self, screen):\n pygame.draw.rect(screen, s.RED, (self.pos[0]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes special fire follow the player and draws it on screen
def specialfire_draw(self, window): self.specialfire_x = self.x + 10 window.blit(self.specialfire_image, (self.specialfire_x, self.specialfire_y))
[ "def fire_shot(self):\n \n self.change_mode(Modes.Draw_Shot)\n\n enemy_tank = self.enemy_team\n current_tank = self.cur_team\n\n self.current_shot = Shot(self.current_power, current_tank.get_angle(), current_tank, enemy_tank, self._map_resolution[1], self._map_resolution[0])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return if a collision between special fire and enemy has happened
def specialfire_collision(self, enemy): offset_x = enemy.x - self.specialfire_x offset_y = enemy.y - self.specialfire_y return self.specialfire_mask.overlap(enemy.mask, (offset_x, offset_y)) != None
[ "def enemy_collision(self):\n\n enemy_hit = pygame.sprite.spritecollide(self, self.game.enemies, False)\n if enemy_hit:\n self.hit = True\n self.end_moves()", "def enemy_collision(self, scene, player):\n item_top_left = scene.itemAt(player.pos() + QPointF(10, 3), self.tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
opens the Nodegraph with dockable configuration settings
def open(self): super(Nodzgraph, self).open(dockable=self.configuration.maya.docked, area=self.configuration.maya.dock_area, allowedArea=self.configuration.maya.allowed_dock_areas, floating=self.configura...
[ "def Open(self,platform_id,default_filename,node_config_filename):\n \n self._platform_id = platform_id\n \n log.debug(\"%r: Open: %s %s\", self._platform_id, default_filename,node_config_filename)\n\n \n \n try:\n default_config_file = open(default_filename, 'r')\n exc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
appends available node types in categories
def append_available_node_categories(self): available_node_types = self.graph.creation_field.available_items for types in self.configuration.maya.available_node_categories: node_types = pmc.listNodeTypes(types) for node_type in node_types: if not node_type in avai...
[ "def _add_icecat_categories(self, data):\n TreeNode = Pool().get('product.tree_node')\n ProductNodeRelationship = Pool().get(\n 'product.product-product.tree_node'\n )\n\n new_node = TreeNode._get_or_create_icecat_if_not_exists(\n int(data.Product.Category.get('ID')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function receives a 'POST' request method from a client and get it's data
def recieve_information_from_client(): client_data = request.forms.get('json') client_data_dict = json.loads(client_data) return client_data_dict
[ "def get_request_data():\n method = request.method.lower()\n if method in [\"get\", \"delete\"]:\n return request.args\n elif method in [\"post\", \"put\"]:\n if request.mimetype == 'application/json':\n try:\n return request.get_json()\n except:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function finds a file in the 'root' folder with the corresponding name, and reads its content depending on it's type.
def read_file(root, file_name, file_type='t'): page_dir = handle_path(main_directory + '/' + root + '/' + file_name) try: # if type != 'b' and type != 't': # raise with open(page_dir, 'r' + file_type) as page_reader: return str(page_reader.read()) except Fi...
[ "def find(root, type=None, name='.*'):\n #debug('root={0} type={1} name={2}'.format(root, type, name))\n pattern=re.compile(name)\n for root_dir, dirs, files in os.walk(root):\n # debug('zzz: {}'.format(files))\n if type=='f' or type is None:\n for file in files:\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function checks if a worker with this id exists in the database. if it doesn't exists, it will send an "Unauthorized" status error, it it does exists, it will return data it has about the worker. The worker will always send its id as the first argument to every route.
def identify(sus_id): worker_data = Db.find_worker(sus_id) if worker_data is None: raise_http_error("Unauthorized") return worker_data
[ "def ensure_worker_exists(self, worker_id: str) -> None:\n with self.table_access_condition:\n conn = self._get_connection()\n c = conn.cursor()\n c.execute(\n \"\"\"\n INSERT OR IGNORE INTO workers(\n worker_id,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function packages data to a Json file to send to the client.
def package_data(data_dict): return json.dumps(data_dict)
[ "def write_json(self, data, fichier):", "def cargar(self, data):\n json.dumps(data)\n with open('data.json', 'w') as file:\n json.dump(data, file, indent=4)", "def data_writer(file_path, data):\n outfile = open(file_path, \"w+\")\n json.dump(data, outfile)", "def get_json_file(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calculates results for the main server to display on the "task_stats" page.
def get_stats(): stats = { "progress_precent": 100.0*finished_work_units_amount/work_units_amount, "results": None if work_status == Db.WorkStatusNames.finished_work.value else Db.collect_results(), #If it's already finished, then all the results were already sent to the main server. ...
[ "def compute_statistics(self):", "def compute_metrics(self, results: list) -> dict:", "def _compute_global_stats():\n global_stats = []\n \n wmt16_group = Group.objects.filter(name='WMT16')\n wmt16_users = _get_active_users_for_group(wmt16_group)\n \n # Check how many HITs have been complete...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define SPARQL query to get a list of ICOS stations If %args is empty, all stations are returned. If %args = 4, we expect a bounding box, [lat1, lat2, lon1, lon2] If %args is >0 and != 4, we revert to return all stations
def icos_stations(*args): if len(args) != 4: filterstr = " " else: filterstr = """ filter( ?lat >= %s && ?lat <= %s && ?lon >= %s && ?lon <= %s).""" % (args) query = """ PREFIX cpst: <http://meta.icos-cp.eu/ontologies/stationentry/> SEL...
[ "def get_stations(datum):\n\n start = datum.get(\"Start Station\")\n\n end = datum.get(\"End Station\")\n\n return (start, end)", "def _geography_query(self, kwargs):\n state = _make_list(kwargs.pop(\"state\", []))\n county = _make_list(kwargs.pop(\"county\", []))\n msa = _make_list(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure that all arguments are less than or equal to 2 31 1. This limitation is introduced because databases stores INT in 4 bytes. If the validation fails for some argument, exception.Invalid is raised with appropriate information.
def _validate_db_int(**kwargs): max_int = (2 ** 31) - 1 for param_key, param_value in kwargs.items(): if param_value and param_value > max_int: msg = _("'%(param)s' value out of range, " "must not exceed %(max)d.") % {"param": param_key, ...
[ "def test_constraints(self):\n values.Integer.validate(2**63 - 1)\n values.Integer.validate(-2**63)\n\n with self.assertRaises(ValueError):\n values.Integer.validate(2**63)\n with self.assertRaises(ValueError):\n values.Integer.validate(-2**63 - 1)", "def validate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unset global configuration variables for database.
def clear_db_env(): global _FACADE _FACADE = None
[ "def remove_pgsql_conf(self):\n self.kv.unset(\"pgsql_host\")\n self.kv.unset(\"pgsql_port\")\n self.kv.unset(\"pgsql_db\")\n self.kv.unset(\"pgsql_user\")\n self.kv.unset(\"pgsql_pass\")\n self.kv.flush()", "def tearDown(self):\n # set the config module level vari...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an subject from the values dictionary.
def subject_create(context, values): return _subject_update(context, values, None, purge_props=False)
[ "def make_subject(self, data: dict, **kwargs: Any) -> Subject:\n return Subject(**data)", "def subject_property_create(context, values, session=None):\n prop_ref = models.SubjectProperty()\n prop = _subject_property_update(context, prop_ref, values, session=session)\n return prop.to_dict()", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Destroy the subject or raise if it does not exist.
def subject_destroy(context, subject_id): session = get_session() with session.begin(): subject_ref = _subject_get(context, subject_id, session=session) # Perform authorization check _check_mutate_authorization(context, subject_ref) subject_ref.delete(session=session) d...
[ "def delete_subject(request, subject):\n subject = get_object_or_404(Subject, slug=subject)\n subject.delete()\n return HttpResponse('Subject has been deleted.')", "def unsubscribe(self, subject):\n pass", "def delete_subject(subject_id) -> int:\n return _delete(\"subjects\", \"(subject_id = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate suitable dictionary list for locations field of subject. We don't need to set other data fields of location record which return from subject query.
def _normalize_locations(context, subject, force_show_deleted=False): if subject['status'] == 'deactivated' and not context.is_admin: # Locations are not returned for a deactivated subject for non-admin user subject['locations'] = [] return subject if force_show_deleted: locati...
[ "def _get_location_record(self, loc_item):\n meta = self._LOCATION_RECORD_META\n return dict(\n (\n k,\n meta[k]['validator'](loc_item[meta[k]['source_header'].lower()])\n ) for k in meta\n )", "def location_field_indexing(self):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if the given subject id is valid before executing operations. For now, we only check its length. The original purpose of this method is wrapping the different behaviors between MySql and DB2 when the subject id length is longer than the defined length in database model.
def _check_subject_id(subject_id): if (subject_id and len(subject_id) > models.Subject.id.property.columns[ 0].type.length): raise exception.SubjectNotFound()
[ "def validateID(id):\n\n if re.compile('[0-9]+').match(id) == None:\n output.completeOutputError(InvalidArgumentCount(descape =\"'%s' is not a valid Id. ID should be numeric with Length = '%s' \" \n\t\t\t% (id, lib.constants._ATTR_ID_LENGHT)))\n return -1\n else:\n # Check for the lenght ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an subject or raise if it does not exist.
def _subject_get(context, subject_id, session=None, force_show_deleted=False): _check_subject_id(subject_id) session = session or get_session() try: query = session.query(models.Subject).options( sa_orm.joinedload(models.Subject.properties)).options( sa_orm.joinedload( ...
[ "def find_subject(subject_id: SubjectID) -> Optional[Subject]:\n subject = DbSubject.query.get(subject_id)\n\n if subject is None:\n return None\n\n return _db_entity_to_subject(subject)", "def check_existing_subject(model, subject):\n subjects = [\n exercise for exercise in model.exerci...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the subject is mutable in this context.
def is_subject_mutable(context, subject): # Is admin == subject mutable if context.is_admin: return True # No owner == subject not mutable if subject['owner'] is None or context.owner is None: return False # Subject only mutable by its owner return subject['owner'] == context.o...
[ "def supply_mutable(self) -> bool:\n return (self.flags & 1) == 1", "def is_mutable_field(self):\n return conf.lib.clang_CXXField_isMutable(self)", "def levy_mutable(self) -> bool:\n return (self.flags & 4) == 4", "def has_immutability_policy(self) -> bool:\n return pulumi.get(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the default value of the columns from DB table In postgreDB case, if no right default values are being set, an psycopg2.DataError will be thrown.
def _get_default_column_value(column_type): type_schema = { 'datetime': None, 'big_integer': 0, 'integer': 0, 'string': '' } if isinstance(column_type, sa_sql.type_api.Variant): return _get_default_column_value(column_type.impl) return type_schema[column_type.__...
[ "def default(self):\r\n value = self.column.default\r\n if value is None:\r\n value = self.table.default\r\n return value", "def getFgDefault(self, **kwargs):\n\n res = {}\n for col in self.columnDefs:\n if col.get('columnId'):\n res[col['col...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a query with sorting / pagination criteria added. Pagination works by requiring a unique sort_key, specified by sort_keys. (If sort_keys is not unique, then we risk looping through values.) We use the last row in the previous page as the 'marker' for pagination. So we must return values that follow the passed m...
def _paginate_query(query, model, limit, sort_keys, marker=None, sort_dir=None, sort_dirs=None): if 'id' not in sort_keys: # TODO(justinsb): If this ever gives a false-positive, check # the actual primary key, rather than assuming its id LOG.warn(_LW('Id not in sort_keys...
[ "def _paginate_query(query, model, limit, sort_keys, marker=None,\n sort_dir=None, sort_dirs=None):\n\n if 'id' not in sort_keys:\n # TODO(justinsb): If this ever gives a false-positive, check\n # the actual primary key, rather than assuming its id\n LOG.warn(_('Id not in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removed protected attributes from values dictionary using the models __protected_attributes__ field.
def _drop_protected_attrs(model_class, values): for attr in model_class.__protected_attributes__: if attr in values: del values[attr]
[ "def _set_excluded_attributes(self) :\n self._excluded_attributes = self.__dict__.keys() + self._containers.keys()", "def post_only_cleanning(self, instance, validated_data):\n model_attrs = dict(**validated_data)\n post_only_fields = getattr(self, 'post_only_fields', None)\n if instance i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all subject locations for given subject
def _subject_locations_delete_all(context, subject_id, delete_time=None, session=None): session = session or get_session() location_refs = session.query(models.SubjectLocation).filter_by( subject_id=subject_id).filter_by(deleted=False).all() for loc_id in [loc_ref....
[ "def subject_destroy(context, subject_id):\n session = get_session()\n with session.begin():\n subject_ref = _subject_get(context, subject_id, session=session)\n\n # Perform authorization check\n _check_mutate_authorization(context, subject_ref)\n\n subject_ref.delete(session=sessi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create or update a set of subject_properties for a given subject
def _set_properties_for_subject(context, subject_ref, properties, purge_props=False, session=None): orig_properties = {} for prop_ref in subject_ref.properties: orig_properties[prop_ref.name] = prop_ref for name, value in six.iteritems(properties): prop_value...
[ "def subject_property_create(context, values, session=None):\n prop_ref = models.SubjectProperty()\n prop = _subject_property_update(context, prop_ref, values, session=session)\n return prop.to_dict()", "def subject_create(context, values):\n return _subject_update(context, values, None, purge_props=F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes all the child entries for the given subject id. Deletes all the child entries of the given child entry ORM model class using the parent subject's id.
def _subject_child_entry_delete_all(child_model_cls, subject_id, delete_time=None, session=None): session = session or get_session() query = session.query(child_model_cls).filter_by( subject_id=subject_id).filter_by(deleted=False) ...
[ "def _DeleteChildren(self, child_class, relation_field=None):\n relation_field = relation_field or self.TableName()\n with self.connection as cursor:\n safe_key = self.connection.EscapeValues(self.key)\n cursor.Delete(table=child_class.TableName(),\n conditions='`%s`=%s' % (relati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an SubjectProperty object.
def subject_property_create(context, values, session=None): prop_ref = models.SubjectProperty() prop = _subject_property_update(context, prop_ref, values, session=session) return prop.to_dict()
[ "def make_subject(self, data: dict, **kwargs: Any) -> Subject:\n return Subject(**data)", "def subject_create(context, values):\n return _subject_update(context, values, None, purge_props=False)", "def create(subdomain, subject_type_or_type_name, subject_name, author):\n return Subject(key_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all subject properties for given subject
def _subject_property_delete_all(context, subject_id, delete_time=None, session=None): props_updated_count = _subject_child_entry_delete_all( models.SubjectProperty, subject_id, delete_time, session) return props_updated_count
[ "def clear_subjects(db):\n\t\n\tfor p_hash, p in db.all_papers.items():\n\t\tif p.subject:\n\t\t\tp.subject = None", "def subject_destroy(context, subject_id):\n session = get_session()\n with session.begin():\n subject_ref = _subject_get(context, subject_id, session=session)\n\n # Perform aut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an SubjectMember object.
def subject_member_create(context, values, session=None): memb_ref = models.SubjectMember() _subject_member_update(context, memb_ref, values, session=session) return _subject_member_format(memb_ref)
[ "def create(subdomain, subject_type_or_type_name, subject_name, author):\n return Subject(key_name='%s:%s' % (subdomain, subject_name),\n type=get_name(subject_type_or_type_name), author=author)", "def make_subject(self, data: dict, **kwargs: Any) -> Subject:\n return Subject(*...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format a member ref for consumption outside of this module.
def _subject_member_format(member_ref): return { 'id': member_ref['id'], 'subject_id': member_ref['subject_id'], 'member': member_ref['member'], 'can_share': member_ref['can_share'], 'status': member_ref['status'], 'created_at': member_ref['created_at'], 'upda...
[ "def pretty_ref(self) -> str:\n base_code = self.ref\n pretty_code = \"\"\n for idx, _ in enumerate(base_code):\n if idx == 0 or idx == 4 or idx == 6 or idx == 8:\n pretty_code += (base_code[idx] + '-')\n else:\n pretty_code += base_code[idx]\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update an SubjectMember object.
def subject_member_update(context, memb_id, values): session = get_session() memb_ref = _subject_member_get(context, memb_id, session) _subject_member_update(context, memb_ref, values, session) return _subject_member_format(memb_ref)
[ "def update(self, subject):\n pass", "def update(self, subject: Subject) -> None:\n pass", "def _update(self):\n path = \"/members/%s\" % self._dict['member_id']\n data = self.extract()\n if self._dict['member_status_id'] in (\n MemberStatus.Active, MemberStatus.Err...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete an SubjectMember object.
def subject_member_delete(context, memb_id, session=None): session = session or get_session() member_ref = _subject_member_get(context, memb_id, session) _subject_member_delete(context, member_ref, session)
[ "def delete_subject(request, subject):\n subject = get_object_or_404(Subject, slug=subject)\n subject.delete()\n return HttpResponse('Subject has been deleted.')", "def delete_by_id(self, subject_id: str) -> any:\n pass", "def delete_member():\n client = RequestManager()\n client.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all subject members for given subject
def _subject_member_delete_all(context, subject_id, delete_time=None, session=None): members_updated_count = _subject_child_entry_delete_all( models.SubjectMember, subject_id, delete_time, session) return members_updated_count
[ "def delete_subject(subjects, subject_old):\n for i in range(len(subjects)):\n if subjects[i] == subject_old:\n subjects.remove(subjects[i])\n return", "def delete_subject(subject_id) -> int:\n return _delete(\"subjects\", \"(subject_id = %s)\", (subject_id,))", "def delete_un...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch an SubjectMember entity by id.
def _subject_member_get(context, memb_id, session): query = session.query(models.SubjectMember) query = query.filter_by(id=memb_id) return query.one()
[ "def subject_member_find(context, subject_id=None, member=None,\n status=None, include_deleted=False):\n session = get_session()\n members = _subject_member_find(context, session, subject_id,\n member, status, include_deleted)\n return [_subject_memb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all members that meet the given criteria. Note, currently include_deleted should be true only when create a new subject membership, as there may be a deleted subject membership between the same subject and tenant, the membership will be reused in this case. It should be false in other cases.
def subject_member_find(context, subject_id=None, member=None, status=None, include_deleted=False): session = get_session() members = _subject_member_find(context, session, subject_id, member, status, include_deleted) return [_subject_member_format(...
[ "def find_members(self, details):\n\n results = []\n\n for member in self.member:\n if details.match(member):\n results.append(member)\n\n return results", "def list_members(self, currentPage=None, pageSize=None, keywords=None,\n email=None, group...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the number of subject members for this subject
def subject_member_count(context, subject_id): session = get_session() if not subject_id: msg = _("Subject id is required.") raise exception.Invalid(msg) query = session.query(models.SubjectMember) query = query.filter_by(deleted=False) query = query.filter(models.SubjectMember.sub...
[ "def member_count(self):\n return len(self.members)", "def count_members(self):\n count = 0\n for record in self.models:\n count += record['count']\n\n return count", "def member_count(self):\n return self._member_count", "def subjectCount(self):\n coro = s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an subject tag.
def subject_tag_create(context, subject_id, value, session=None): session = session or get_session() tag_ref = models.SubjectTag(subject_id=subject_id, value=value) tag_ref.save(session=session) return tag_ref['value']
[ "def subject_create(context, values):\n return _subject_update(context, values, None, purge_props=False)", "def create_subject(in_subject):\n subject = in_subject.split(',')\n return Subject(subject[0], subject[1], subject[2], subject[3])", "def create_subject(name=\"Basket Weaving\"):\n subj = Subj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete an subject tag.
def subject_tag_delete(context, subject_id, value, session=None): _check_subject_id(subject_id) session = session or get_session() query = session.query(models.SubjectTag).filter_by( subject_id=subject_id).filter_by( value=value).filter_by(deleted=False) try: tag_ref = query.one(...
[ "def delete_subject(request, subject):\n subject = get_object_or_404(Subject, slug=subject)\n subject.delete()\n return HttpResponse('Subject has been deleted.')", "def delete(self, tag, params={}, **options):\n path = \"/tags/%s\" % (tag)\n return self.client.delete(path, params, **options...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all subject tags for given subject
def _subject_tag_delete_all(context, subject_id, delete_time=None, session=None): tags_updated_count = _subject_child_entry_delete_all(models.SubjectTag, subject_id, delete_t...
[ "def delete_subject(subjects, subject_old):\n for i in range(len(subjects)):\n if subjects[i] == subject_old:\n subjects.remove(subjects[i])\n return", "def subject_tag_delete(context, subject_id, value, session=None):\n _check_subject_id(subject_id)\n session = session or ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of tags for a specific subject.
def subject_tag_get_all(context, subject_id, session=None): _check_subject_id(subject_id) session = session or get_session() tags = session.query(models.SubjectTag.value).filter_by( subject_id=subject_id).filter_by(deleted=False).all() return [tag[0] for tag in tags]
[ "def tags(self):\n tagexp = re.compile(r\"\\[([^\\]]*)\\]\")\n subject = self['Subject']\n return tagexp.findall(subject)", "def subject_list():\n items = []\n\n soup = abcradionational.get_soup(URL + \"/podcasts/subjects\")\n \n subject_heading = abcradionational.get_podcast_head...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Purges soft deleted rows Deletes rows of table subjects, table tasks and all dependent tables according to given age for relevant models.
def purge_deleted_rows(context, age_in_days, max_rows, session=None): # check max_rows for its maximum limit _validate_db_int(max_rows=max_rows) session = session or get_session() metadata = MetaData(get_engine()) deleted_age = timeutils.utcnow() - datetime.timedelta(days=age_in_days) tables =...
[ "def purge_deleted_records(context, age_in_days):\n\n if age_in_days < 0:\n msg = _('Must supply a non-negative value for \"age_in_days\".')\n LOG.error(msg)\n raise exception.InvalidParameterValue(msg)\n\n metadata = MetaData()\n metadata.reflect(get_engine())\n deleted_age = timeu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format a task info ref for consumption outside of this module
def _task_info_format(task_info_ref): if task_info_ref is None: return {} return { 'task_id': task_info_ref['task_id'], 'input': task_info_ref['input'], 'result': task_info_ref['result'], 'message': task_info_ref['message'], }
[ "def _task_format(task_ref, task_info_ref=None):\n task_dict = {\n 'id': task_ref['id'],\n 'type': task_ref['type'],\n 'status': task_ref['status'],\n 'owner': task_ref['owner'],\n 'expires_at': task_ref['expires_at'],\n 'created_at': task_ref['created_at'],\n 'up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch an TaskInfo entity by task_id
def _task_info_get(context, task_id, session=None): session = session or get_session() query = session.query(models.TaskInfo) query = query.filter_by(task_id=task_id) try: task_info_ref = query.one() except sa_orm.exc.NoResultFound: LOG.debug("TaskInfo was not found for task with id ...
[ "def _get_task(self, task_id: str) -> Mapping[str, Any]:\n return self.__get_one_by_id(\"tasks\", \"task_id\", task_id)", "def db_get_task(task_id):\n sql = \"SELECT * FROM {} WHERE id=?\".format(TABLE_NAME)\n return db_query(sql, (task_id,), True)", "def get_task(task_id, workflow_id):\n stmt =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the task is visible in this context.
def _is_task_visible(context, task): # Is admin == task visible if context.is_admin: return True # No owner == task visible if task['owner'] is None: return True # Perform tests based on whether we have an owner if context.owner is not None: if context.owner == task['ow...
[ "def is_visible(self):\n return self.container['is_visible']", "def is_visible(self):\n return self._switcher.isVisible()", "def is_visible_in_grid(self):\n return self._is_visible_in_grid", "def hasTask(self):\n return bool(Task.peek())", "def is_visible(self):\n return s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format a task ref for consumption outside of this module
def _task_format(task_ref, task_info_ref=None): task_dict = { 'id': task_ref['id'], 'type': task_ref['type'], 'status': task_ref['status'], 'owner': task_ref['owner'], 'expires_at': task_ref['expires_at'], 'created_at': task_ref['created_at'], 'updated_at': ta...
[ "def _task_info_format(task_info_ref):\n if task_info_ref is None:\n return {}\n return {\n 'task_id': task_info_ref['task_id'],\n 'input': task_info_ref['input'],\n 'result': task_info_ref['result'],\n 'message': task_info_ref['message'],\n }", "def TaskDisplayName(cls...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves the numbers in one line according to the rules of 2048. Takes a line (list) as an argument
def move(line): length = len(line) pos = 0 global points global sym while pos < len( line): if (line[pos] == 0): del line[pos] else: pos = pos + 1 if len(line) == 0: return [0] * length pos = 0 while line[pos] != 0 and pos + 1...
[ "def slide(line):\n for num in range(len(line) -1):\n if line[num] == 0:\n for tile in range(num, len(line)):\n if line[tile] > 0:\n line[num] += line[tile]\n line[tile] = 0\n break\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decides which direction the numbers should move and which function to use. Takes a field (list) and a direction (string) as arguments
def Transform(field, dir): if dir == "w": field = TransformUpMovement(field) elif dir == "s": field = TransformDownMovement(field) elif dir == "a": field = TransformLeftMovement(field) elif dir == "d": field = TransformRightMovement(field) return field
[ "def move(direction):\n if direction == 'r':\n return 1\n if direction == 'l':\n return -1", "def motorsDirection(self, direction):\n\n print (direction)\n if direction == 'r' or direction == 'R':\n self.motorDirection(self.motor1DirectionPin, self.motorReverse)\n self.motorDir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks the field if it is full. Takes a field (list) as argument
def FullCheck(field): temp_list = field[:] field_copy = field[:] if temp_list == Transform(field_copy, "w"): if temp_list == Transform(field_copy, "a"): if temp_list == Transform(field_copy, "s"): if temp_list == Transform(field_copy, "d"): return True...
[ "def is_field_empty(*args):\n for field in args:\n if field == \"\" or field is None:\n return True\n return False\n return \"NONDETERMINISTIC\"", "def checkListFields( listfields ):\n validfields = ['filename', 'size', 'owner', 'project', 'mtime', 'atime']\n for ent in listfi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ask for a row/column size constatly until it is not a valid choice (choice >= 2)
def SizeCheck(): while True: try: curses.echo() # Enable echoing of characters stdscr.addstr(0, 0, "Give a table square row/column size : ") stdscr.move(0, 38) size = stdscr.getstr(0, 38, 2) size = int(size) curses.noecho() ...
[ "def select_board_size():\n board_size = 0\n while board_size not in range(2, 21):\n # Max size is 20 because that still confortably fits on screen.\n try:\n board_size = int(input('Select a board size between 2 and 20: '))\n except ValueError:\n continue\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main drawing function that initializes curses
def Init_curses(): curses.noecho() curses.cbreak() curses.curs_set(False) stdscr.keypad(True) curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pai...
[ "def start(cls):\n scr = curses.initscr()\n curses.noecho()\n curses.cbreak()\n curses.start_color()\n curses.use_default_colors()\n scr.keypad(True)\n curses.init_pair(1, curses.COLOR_RED, -1)\n curses.init_pair(2, curses.COLOR_BLUE, -1)\n curses.init_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Right matrix division A/B.
def rmdiv(A, B, rcond=None): A = np.asarray(A) B = np.asarray(B) if len(A.shape) == 1: A = A[..., None] if len(B.shape) == 1: B = B[..., None] return np.linalg.lstsq(B.transpose(), A.transpose(), rcond=rcond)[0].transpose()
[ "def orthogonal_rightsolve(A, B):\n return orthogonal_solve(A.T, B.T).T", "def __rdiv__(self,that):\n B = that if isinstance(that,Factor) else Factor([],that)\n return B.__opExpand2(self, np.divide)", "def divide_a_b(self, a, b):\n return a / b", "def divide(A):\r\n m, n = A.shape \r\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }