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
Returns a market segment ID into a JSON structure.
def json_market_builder(self, customerID, marketID) : json_result = '{\n' json_result += '\t "_results":[\n' json_result += '\t\t{ "customerID": "' + str(customerID) json_result += ', "marketID": "' + str(marketID) json_result += '}\n' json_result += '\n\t]\n}' return json_result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_segment_dictionary(segment):\n return {\n \"encoded_name\": segment.encoded_name(),\n \"id\": segment.pk,\n \"timestamp\": int(time.time()),\n \"persistent\": segment.persistent\n }", "def getSerpentId(self):\n raise NotImplementedError", "def _make_segment_d...
[ "0.5654718", "0.5459859", "0.5401625", "0.5299592", "0.5264468", "0.5212608", "0.5205277", "0.5189763", "0.51112807", "0.5020024", "0.4996774", "0.49531874", "0.49421018", "0.49232537", "0.49065843", "0.48627487", "0.48627487", "0.48185506", "0.4808638", "0.47962487", "0.4795...
0.54065216
2
Returns RFM score from dataframe given from parameter. RFM score is computed from local RFM matrix threshold.
def get_rfm(self, df): df_tmp, df_RFM, df_RFM_threshold, day_now \ = p5_util.p5_df_rfm_build(df, df_RFM_threshold=self.df_RFM_quantiles ,day_now = self._day_now) RFM = df_RFM.RFM.iloc[0] return str(RFM)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_rfm_score(dataframe):\n\n dataframe[\"recency_score\"] = pd.qcut(dataframe['recency'].rank(method=\"first\"), 5, labels=[5, 4, 3, 2, 1])\n dataframe[\"frequency_score\"] = pd.cut(dataframe['frequency'], bins=[0, 4, 8, 13, 17, 20], labels=[1, 2, 3, 4, 5])\n dataframe[\"RFM_SCORE\"] = (dataframe[...
[ "0.6958095", "0.61751866", "0.60585284", "0.5860262", "0.58369166", "0.5765395", "0.57476515", "0.5725581", "0.5717504", "0.5708911", "0.5702308", "0.5689124", "0.5686297", "0.5685354", "0.56756556", "0.5671112", "0.5645583", "0.5639483", "0.56138635", "0.56126195", "0.559187...
0.60182154
3
This function is used for validation process. It returns a list of stockCode items and a list of quantities for each item.
def get_order_lists(self, n_items, n_quantities): arr_stock_code = self._df_invoice_original.StockCode.unique() arr_stock_code = np.random.choice(arr_stock_code, n_items) list_stockCode = list(arr_stock_code) list_quantities = np.ones(arr_stock_code.shape[0]) list_quantities *=n_quantities return list_stockCode, list_quantities
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_items(self):\n\n items = []\n\n params = self.request.query_params\n\n if 'items[]' in params:\n items = params.getlist('items[]', [])\n elif 'item' in params:\n items = [params.get('item', None)]\n\n if type(items) not in [list, tuple]:\n ...
[ "0.7183774", "0.62451553", "0.6027354", "0.5956186", "0.57162726", "0.5646305", "0.56151676", "0.55878735", "0.55574286", "0.54344946", "0.5425899", "0.54236686", "0.5393303", "0.539217", "0.5386628", "0.53802747", "0.5373666", "0.5363041", "0.53269744", "0.52845365", "0.5275...
0.6709346
1
Builds an projection block as described in Deep Residual Learning for Image Recognition (2015) You can assume the input data will have shape (224, 224, 3) All convolutions inside and outside the blocks should be followed by batch normalization along the channels axis and a rectified linear activation (ReLU), respectively. All weights should use he normal initialization
def resnet50(): initializer = K.initializers.he_normal(seed=None) X = K.Input(shape=(224, 224, 3)) # conv1 layer = K.layers.Conv2D(filters=64, kernel_size=(7, 7), strides=(2, 2), padding='same', kernel_initializer=initializer, )(X) layer = K.layers.BatchNormalization(axis=3)(layer) layer = K.layers.Activation('relu')(layer) # conv2_x layer = K.layers.MaxPool2D(pool_size=(3, 3), strides=(2, 2), padding='same')(layer) layer = projection_block(layer, [64, 64, 256], 1) for _ in range(2): layer = identity_block(layer, [64, 64, 256]) # conv3_x layer = projection_block(layer, [128, 128, 512]) for _ in range(3): layer = identity_block(layer, [128, 128, 512]) # conv4_x layer = projection_block(layer, [256, 256, 1024]) for _ in range(5): layer = identity_block(layer, [256, 256, 1024]) # conv5_x layer = projection_block(layer, [512, 512, 2048]) for _ in range(2): layer = identity_block(layer, [512, 512, 2048]) layer = K.layers.AveragePooling2D(pool_size=(7, 7), padding='same')(layer) layer = K.layers.Dense(units=1000, activation='softmax', kernel_initializer=initializer, )(layer) model = K.models.Model(inputs=X, outputs=layer) return model
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _building_block_v1(inputs, filters, training, projection_shortcut, strides,\n data_format):\n shortcut = inputs\n\n if projection_shortcut is not None:\n shortcut = projection_shortcut(inputs)\n shortcut = batch_norm(inputs=shortcut, training=training,\n d...
[ "0.6879483", "0.6712965", "0.6681837", "0.6617764", "0.65615404", "0.65488005", "0.6432119", "0.64201134", "0.6342974", "0.6342974", "0.63249046", "0.63225436", "0.62239516", "0.6200089", "0.6196667", "0.6185265", "0.61718935", "0.6138998", "0.61151755", "0.6111726", "0.60973...
0.57862914
74
Sentence generator for an entire corpus directory.
def sentences_for_dir(path='./',separate=True,gzipped=True): for filename in cowfiles(path): for metadata, data in sentence_generator(filename,separate,gzipped): yield metadata, data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_data_sentences(dirname):\n sentence_list = []\n for fname in os.listdir(dirname):\n with open(os.path.join(dirname, fname)) as file:\n #sentence_list.append(gensim.models.word2vec.LineSentence(file))\n sentence_list.append(file)\n return sentence_list", "def sents(s...
[ "0.6356309", "0.6221751", "0.6179384", "0.595983", "0.5889285", "0.5882137", "0.5873492", "0.58633006", "0.5855387", "0.5792811", "0.578709", "0.5780858", "0.5774546", "0.5762869", "0.5740365", "0.5727936", "0.5726981", "0.5708242", "0.56983536", "0.56931585", "0.569029", "...
0.71198934
0
This function returns a Pyramid WSGI application.
def main(global_config, **settings): # Read the settings for SQLAlchemy and # configure connection engine and session maker objects engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine pic_dir = settings['picture_directory'] session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet') config = Configurator(settings=settings, session_factory=session_factory) config.add_route('favicon.ico', '/favicon.ico') # Serves static directory (ie. css, js, bootstrap, etc) config.add_static_view('static', 'static', cache_max_age=3600) #config.add_static_view(pic_dir,pic_dir) # Serves up home page config.add_route('home', '/') # Product Routes config.add_route('product', '/product/{id:\d+}/{slug}') config.add_route('product_action', '/product/{action}') # ex. product/create # ex product/edit?id=number # Category Routes config.add_route('category', '/category/{id:\d+}/{slug}') # Cart Routes config.add_route('cart', '/cart') # Checkout Routes config.add_route('checkout', '/checkout') config.add_route('checkout_receipt', '/receipt') # Account Registration/Login/Logout config.add_route('login', '/login') #config.add_route('logout', '/logout') config.add_route('register', '/register') #config.add_route('add_card') # Sign authorization - added later config.add_route('auth', '/sign/{action}') config.scan() return config.make_wsgi_app()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def wsgi_app():\n return bottle.default_app()", "def wsgi_app():\n return bottle.default_app()", "def bootstrap_wsgi():\n return get_wsgi_application()", "def app():\n return create_app()", "def app():\n app = create_app()\n return app", "def create_app():\n from server.web import cr...
[ "0.78450423", "0.78450423", "0.77413297", "0.770514", "0.7661694", "0.75318485", "0.7400592", "0.72658414", "0.7241545", "0.72377515", "0.71705705", "0.71670246", "0.714194", "0.71155995", "0.7101749", "0.7096859", "0.70582855", "0.7028316", "0.7028151", "0.70058817", "0.7002...
0.0
-1
Create a BDT with some trees
def __init__(self, *items, **kw): self.dTrees = [] self.ntrees = 50 # TODO self.beta = 0.5
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def construct_tree():\n root = TreeNode(5)\n root.left = TreeNode(3)\n root.right = TreeNode(8)\n root.left.left = TreeNode(2)\n root.left.right = TreeNode(4)\n root.right.left = TreeNode(7)\n return root", "def _gen_test_tree_6():\n tree = BinaryNode(20)\n tree.left = BinaryNode(10)\n tr...
[ "0.68108326", "0.6772506", "0.67162484", "0.67155635", "0.67095953", "0.6641939", "0.66419315", "0.66286445", "0.658514", "0.6475259", "0.64652383", "0.6458261", "0.6430485", "0.6366659", "0.634264", "0.631714", "0.6273454", "0.62638414", "0.6260716", "0.62589467", "0.6194391...
0.5919498
40
load the data samples that are used
def load(self,sigData,bkgData): self.sigData = sigData self.bkgData = bkgData self.nVars = sigData.shape[1] self.nSig = sigData.shape[0] self.nBkg = bkgData.shape[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_sample(self):\n\n self.load_images(self.folder + \"/sampleSet.txt\")\n self.load_traces(self.folder + \"/sampleLabel.txt\")", "def _preload_all_samples(self):\n if self.mode in ['train_noval', 'train_with_val']:\n\n self._images_train, self._labels_train = [], []\n ...
[ "0.73953384", "0.713623", "0.71360576", "0.7046007", "0.7029139", "0.7012496", "0.691182", "0.6855628", "0.6850381", "0.68215597", "0.6801296", "0.67527807", "0.6750066", "0.67280877", "0.6723853", "0.66835517", "0.66824424", "0.6658515", "0.66440684", "0.66392", "0.66277313"...
0.0
-1
Build each tree in the 'forest' of trees. After each iteration, evaluate the tree and reweight the input sample such that incorrect events are weighted up and correct events are weighted down
def build(self): # weights to apply to training samples, updated on each # iteration of the boosting algo, normalised to 1 sigWeights = np.ones(self.nSig, dtype=float) bkgWeights = np.ones(self.nBkg, dtype=float) reweight = 1.0/(np.sum(sigWeights)+np.sum(bkgWeights)) sigWeights *= reweight bkgWeights *= reweight # Weight of each tree, strong classifers have higher weight self.treeWeights = np.zeros(self.ntrees, dtype=float) for i in xrange(self.ntrees): # build new tree newTree = Tree() newTree.load(self.sigData,self.bkgData,weights=(sigWeights,bkgWeights)) newTree.build() self.dTrees.append(newTree) # evaluate trees # keep track of each event err = 0.0 sigWrong = np.zeros(self.nSig) bkgWrong = np.zeros(self.nBkg) for j in range(self.nSig): if newTree.classify(np.array((self.sigData[j,])))<0: sigWrong[i]=1 err+=sigWeights[j] for j in range(self.nBkg): if newTree.classify(np.array((self.bkgData[j,])))>0: bkgWrong[i]=1 err+=bkgWeights[j] alpha = self.beta*math.log((1.0-err)/err) print err,alpha corFactor = math.exp(-alpha) wrongFactor = math.exp(alpha) if (err<1e-20 or err >= 0.5): print "SOEMTHING WRONG!!" self.treeWeights[i] = alpha # reweight training samples for j in range(self.nSig): if sigWrong[j]: sigWeights[j]*=wrongFactor else : sigWeights[j]*=corFactor for j in range(self.nBkg): if bkgWrong[j]: bkgWeights[j]*=wrongFactor else : bkgWeights[j]*=corFactor # normalise weights reweight = 1.0/(np.sum(sigWeights)+np.sum(bkgWeights)) sigWeights *= reweight bkgWeights *= reweight
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _build_trees(tree, forest, X, Y, sample_weight, tree_idx, n_trees,\n n_samples_bootstrap=None):\n # Initialize the number of samples input data\n n_samples = X.shape[0]\n\n # If the samples are drawn with replacement, then,\n # weight the sample weights by the number of times\n #...
[ "0.7096626", "0.6913265", "0.6533237", "0.6523216", "0.63476014", "0.6344354", "0.61861014", "0.61825013", "0.6182119", "0.61536306", "0.6152425", "0.61442596", "0.608408", "0.60710186", "0.60495037", "0.6023182", "0.60046387", "0.59995925", "0.5979982", "0.59393513", "0.5876...
0.75269973
0
classify a given event. Iterates over each tree in the forest and then returns the weighted average of the results
def classify(self, event): results = np.zeros(self.ntrees, dtype=float) for i,dt in enumerate(self.dTrees): results[i] = self.treeWeights[i]*dt.classify(event) return np.sum(results)*(1.0/np.sum(self.treeWeights))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _classify(tree, x):\n # YOUR CODE HERE\n # begin answer\n feature_name=list(tree.keys())[0] #first element\n secondDict=tree[feature_name] \n key=x.loc[feature_name] #extract value from x\n for key_val in secondDict:\n ...
[ "0.6027639", "0.5959959", "0.5897434", "0.5878511", "0.58665943", "0.58361167", "0.5765075", "0.5708641", "0.5605437", "0.55976415", "0.5585661", "0.55516666", "0.5534588", "0.55194116", "0.5513875", "0.5391394", "0.5380517", "0.5374991", "0.5372819", "0.5360519", "0.535744",...
0.8286223
0
Node frontiers generator using breadthfirst search.
def bfs_nodes_generator(graph, source, reverse=...): ...
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def breadthfirst(self):\n import os\n cwd = os.getcwd()\n os.chdir('/Users/raj/Documents/algorithms_in_python/linked_lists/')\n from linked_collections import LinkedQueue\n os.chdir(cwd) # change to cwd\n if not self.is_empty():\n lq = LinkedQueue()\n ...
[ "0.71898806", "0.7085778", "0.70385784", "0.6970572", "0.6837096", "0.67863566", "0.6713473", "0.66816336", "0.6657518", "0.6647682", "0.66333216", "0.6629434", "0.6573334", "0.6550337", "0.6511887", "0.65066606", "0.64886534", "0.6471162", "0.64685374", "0.64553446", "0.6401...
0.74444324
0
Edges frontiers generator using breadthfirst search.
def bfs_edges_generator(graph, source, reverse=...): ...
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def bfs_nodes_generator(graph, source, reverse=...):\n ...", "def breadthfirst(self):\n import os\n cwd = os.getcwd()\n os.chdir('/Users/raj/Documents/algorithms_in_python/linked_lists/')\n from linked_collections import LinkedQueue\n os.chdir(cwd) # change to cwd\n ...
[ "0.7032013", "0.65871656", "0.6558607", "0.6494155", "0.6486353", "0.64773285", "0.6464884", "0.6462215", "0.64562446", "0.64025325", "0.63937354", "0.6391087", "0.6381573", "0.6365035", "0.6322902", "0.6297517", "0.6248023", "0.623094", "0.6225877", "0.62127507", "0.6212067"...
0.7154378
0
Node frontiers generator using topological traversal.
def topological_nodes_generator(graph, reverse=...): ...
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def bfs_nodes_generator(graph, source, reverse=...):\n ...", "def _create_node_iterator(self) -> Iterator[GraphNode]:\n return\n yield", "def pre_order(self):\n for node_data in self._pre_order_helper(self._root):\n yield node_data", "def breadth_first_iterate(execution_gra...
[ "0.65818083", "0.631488", "0.60523885", "0.60450137", "0.60366327", "0.5984799", "0.59832644", "0.5886222", "0.5862201", "0.5833745", "0.57818055", "0.5777673", "0.57532954", "0.5735733", "0.5725604", "0.5718208", "0.5704789", "0.5663648", "0.5657863", "0.56538856", "0.564333...
0.75308436
0
Edge frontiers generator using depthfirstsearch (DFS). Multiple source nodes can be specified to start the DFS traversal. One needs to make sure that each source node belongs to different connected component, so the frontiers can be easily merged. Otherwise, the behavior is undefined.
def dfs_edges_generator(graph, source, reverse=...): ...
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def bfs_nodes_generator(graph, source, reverse=...):\n ...", "def main():\n n = int(input(\"Enter the number of nodes: \"))\n m = int(input(\"Enter the number of edges: \"))\n \n adjList = [[] for i in range(n)]\n \n print(\"Enter the edges: \")\n for i in range(m):\n x, y = input(...
[ "0.66623896", "0.65276676", "0.64679134", "0.64623046", "0.6430159", "0.63167006", "0.6277863", "0.625629", "0.625629", "0.6231696", "0.6226393", "0.6226135", "0.6202045", "0.6167126", "0.61345613", "0.61269605", "0.61263084", "0.6116274", "0.61129403", "0.60858756", "0.60563...
0.71058327
0
Produce edges in a depthfirstsearch (DFS) labeled by type.
def dfs_labeled_edges_generator(graph, source, reverse=..., has_reverse_edge=..., has_nontree_edge=..., return_labels=...): # -> tuple[Unknown, Unknown]: ...
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_edges_by_vertex(self, id, type=0):\n edges = []\n for (source, target) in self.edges.keys():\n if type == 1:\n if source == id:\n edges.append((source, target))\n elif type == 2:\n if target == id:\n edg...
[ "0.6322782", "0.5792171", "0.5745061", "0.5557453", "0.55496603", "0.54645675", "0.5460162", "0.5454831", "0.53846216", "0.5355307", "0.5339173", "0.5338952", "0.53288114", "0.53112", "0.5310598", "0.52910846", "0.52882874", "0.5266239", "0.5237493", "0.52122957", "0.5211946"...
0.53314835
12
find the feature to use for the next node split and also find where the plit should be in that feature This loops through the split options within a feature to find the best gini score, then it loops through each feature to compare optimal gini scores
def find_split(self, X, y): choices = y.size if choices <= 1: return None, None # find the number of each option in the current node. options_parent = [np.sum(y == c) for c in range(self.num_outcomes)] # find the gini of current node. best_gini = 1.0 - sum((n / choices) ** 2 for n in options_parent) best_idx, best_split = None, None # loop through the features to get splits and options. for idx in range(self.num_features): splits, options = zip(*sorted(zip(X[:, idx], y))) num_left = [0] * self.num_outcomes num_right = options_parent.copy() for i in range(1, choices): c = options[i - 1] num_left[c] += 1 num_right[c] -= 1 gini_left = 1.0 - sum( (num_left[x] / i) ** 2 for x in range(self.num_outcomes) ) gini_right = 1.0 - sum( (num_right[x] / i) ** 2 for x in range(self.num_outcomes) ) gini = (i * gini_left + (choices - i) * gini_right) / choices if splits[i] == splits[i - 1]: continue if gini < best_gini: best_gini = gini best_idx = idx best_split = (splits[i] + splits[i - 1]) / 2 return best_idx, best_split
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_split(data):\n \"\"\" gets the best feature, and best value \"\"\"\n\n best_feature = None\n best_value = 0.0\n columns = data.columns\n gini_base = gini_impurity(data)\n n_rows = len(data.index) # total number of rows of data before split\n\n # Fininding which split yie...
[ "0.7151503", "0.64216876", "0.6352301", "0.6302367", "0.62781364", "0.62125915", "0.6181519", "0.6135771", "0.60826075", "0.6048427", "0.5933168", "0.590119", "0.5873095", "0.58700764", "0.5845192", "0.583579", "0.5818668", "0.5818668", "0.58096075", "0.5801238", "0.5736901",...
0.66302925
1
Predict class for a single sample.
def _predict(self, inputs): node = self.tree_ while node.left: if inputs[node.feature_index] < node.split: node = node.left else: node = node.right return node.predicted_class
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def predict(self, sample, **kwargs):\r\n return self.model.predict(sample, **kwargs)", "def predict_class(self, feature):\n return self._clf.predict(feature)", "def predict_class(self, feature):\n return self._clf.predict(feature)", "def predict(self, sample, **kwargs):\n return s...
[ "0.7528597", "0.7466587", "0.7466587", "0.7458586", "0.7371801", "0.73080134", "0.7273918", "0.7189897", "0.70958567", "0.7088658", "0.702793", "0.70140815", "0.6998257", "0.6997045", "0.6972628", "0.69581044", "0.6956856", "0.6954656", "0.6954656", "0.6954656", "0.6941434", ...
0.0
-1
A class without the key_fields annotation should raise a RuntimeError
def testNoKeyFields(): with pytest.raises(RuntimeError): class AnnotatedNode(Node): x: str y: int def __init__(self, x: str, y: int): self.x = x self.y = y @property def _display(self) -> str: return self.x
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_key_no_data(self):\n key = Key({})\n\n assert key.warning is None\n assert key.in_car is None", "def _validate(self):\n fields, schema = self.__dict__, self._def.default\n extra_fields = fields.viewkeys() - schema.viewkeys()\n if len(extra_fields) > 0:\n ...
[ "0.664005", "0.64458597", "0.63761204", "0.63392276", "0.620251", "0.61894745", "0.6169179", "0.611666", "0.60839826", "0.60760987", "0.6069411", "0.6068303", "0.60593605", "0.60562086", "0.6022622", "0.60070866", "0.5998208", "0.59926015", "0.59468085", "0.59364104", "0.5934...
0.7018351
0
First node's fields should be updated with the second nodes
def testMergeRejectsUnequalNodes(): n1 = DummyNode(x=1, y=2, z=4) n2 = DummyNode(x=1, y=3, z=3) with pytest.raises(TypeError): n1.merge_with(n2)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mergeNodes(new, t1, t2):\n \n if t1 and t2:\n new.val = t1.val + t2.val\n elif not t1:\n new.val = t2.val\n elif not t2:\n new.val = t1.val", "def update(self, other):\n self._start = other._start\n self._e...
[ "0.65650755", "0.63940614", "0.6173685", "0.61118114", "0.6035203", "0.6019497", "0.59971595", "0.5948517", "0.5918453", "0.5903322", "0.5868278", "0.57634944", "0.57632744", "0.57355", "0.57273066", "0.57142293", "0.56911355", "0.56886685", "0.56635535", "0.5628927", "0.5605...
0.0
-1
First node's fields should be updated with the second nodes
def testMergeNoEdges(): n1 = DummyNode(x=1, y=2, z=4) n2 = DummyNode(x=1, y=2, z=3) assert n1.z == 4 n1.merge_with(n2) assert n1.z == 3
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mergeNodes(new, t1, t2):\n \n if t1 and t2:\n new.val = t1.val + t2.val\n elif not t1:\n new.val = t2.val\n elif not t2:\n new.val = t1.val", "def update(self, other):\n self._start = other._start\n self._e...
[ "0.65650755", "0.63940614", "0.6173685", "0.61118114", "0.6035203", "0.6019497", "0.59971595", "0.5948517", "0.5918453", "0.5903322", "0.5868278", "0.57634944", "0.57632744", "0.57355", "0.57273066", "0.57142293", "0.56911355", "0.56886685", "0.56635535", "0.5628927", "0.5605...
0.5121291
87
creates randomized colors of shape size_x by size_y
def create_world(size_x = 100, size_y=100): colors = np.random.randint(0,2,(size_x,size_y)).tolist() for row in range(len(colors)): for col in range(len(colors[row])): if (colors[row][col]== 1): colors[row][col] = 'R' else: colors[row][col] = 'G' r = [[10.0 for i in range(size_y)] for i in range(size_x)] g = [[10.0 for i in range(size_y)] for i in range(size_x)] b = [[10.0 for i in range(size_y)] for i in range(size_x)] RGB = [] for i in range(size_x): for j in range(size_y): if colors[i][j] == 'R': r[i][j] = 255.0 else: b[i][j] = 255.0 RGB.append(b[i][j]) RGB.append(r[i][j]) RGB.append(g[i][j]) RGB = np.array(RGB).reshape(size_x,size_y,3) return RGB, colors
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def randColor():\r\n return np.array([random.random(), random.random(), random.random()]).reshape((1, 1, 3))", "def random_color_gen():\n r = randint(0, 255)\n g = randint(0, 255)\n b = randint(0, 255)\n return [r, g, b]", "def random_color(num):\n # 为每个类别的边界框随机匹配相应颜色\n np.random.seed(80)\...
[ "0.72354615", "0.681743", "0.67759746", "0.65923506", "0.647772", "0.6391293", "0.6389239", "0.6381156", "0.63713896", "0.6345931", "0.6305542", "0.62956303", "0.62650055", "0.62281466", "0.6208814", "0.6204611", "0.61832035", "0.617489", "0.6139714", "0.6136026", "0.6124625"...
0.7120646
1
r"""Return the current running average.
def get_current(self): return self.x
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def calculate(self):\n avg = self.sum / self.n if self.n != 0 else 0\n self.running_avg.append(avg)\n return avg", "def average(self):\n return (self.current + self.last) / 2.0", "def current_mean(self):\r\n values = self._timings\r\n return np.mean(values)", "def av...
[ "0.8117838", "0.7966467", "0.7702329", "0.73908114", "0.7304135", "0.72477657", "0.72477657", "0.72477657", "0.7218233", "0.7120395", "0.7092222", "0.7014438", "0.6919139", "0.6896268", "0.6838284", "0.6832612", "0.6796031", "0.67581385", "0.6699277", "0.6677944", "0.6667284"...
0.0
-1
Finds a dihedral angle adjacent to the selected atoms that includes a new atom
def _find_dihedral(selected): atom_name = lambda atom: atom.fullName() atom_mass = lambda atom: atom.mass() # Loop over possible nearest neighbors for a2 in selected: # Find the new atom attached_to_a2 = sorted([a for a in a2.bondedTo() \ if a not in selected], key=atom_name) for a1 in sorted(attached_to_a2, key=atom_mass, reverse=True): # Find the third atom attached_to_a3 = sorted([a for a in a2.bondedTo() \ if (a in selected) and (a!=a1)], key=atom_name) for a3 in sorted(attached_to_a3, key=atom_mass, reverse=True): # Find the last atom attached_to_a4 = sorted([a for a in a3.bondedTo() \ if (a in selected) and (a!=a2)], key=atom_name) for a4 in sorted(attached_to_a4, key=atom_mass, reverse=True): return (a1, a2, a3, a4) print 'Selected atoms:', selected raise Exception('No new dihedral angle found!')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def dihedral_calculator():\n\n\t# Prime with first 3 points\n\tp1 = Vector3((yield None))\n\tp2 = Vector3((yield None))\n\tp3 = Vector3((yield None))\n\n\t# Set up for first angle\n\tlastpoint = p3\n\tlastdisp = p3 - p2\n\tlastnormal = ((p2 - p1) @ lastdisp).normalize()\n\n\tangle = None\n\n\t# For each point star...
[ "0.6646527", "0.63952506", "0.6240537", "0.5905683", "0.588075", "0.5806025", "0.5764874", "0.56130666", "0.5525293", "0.5508618", "0.5460365", "0.53958726", "0.535405", "0.53534824", "0.5297335", "0.5294864", "0.52534354", "0.52349055", "0.52014965", "0.51829153", "0.5158568...
0.8237362
0
Indices of the first torsions in the BAT array
def getFirstTorsionInds(self, extended): offset = 6 if extended else 0 torsionInds = np.array(range(offset + 5, self.natoms * 3, 3)) primaryTorsions = sorted(list(set(self._firstTorsionTInd))) return list(torsionInds[primaryTorsions])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_agent_indices(array):\t\n\tagent_indices = np.argwhere(array != 0)\n\treturn agent_indices", "def get_vacancy_indices(array):\t\n\tvacancy_indices = np.argwhere(array == 0)\n\treturn vacancy_indices", "def _get_indx(self, t):\n t = np.array(t)\n a = (t[:, np.newaxis] <= self._data['stop']...
[ "0.6661381", "0.6593251", "0.62259746", "0.622321", "0.6037638", "0.60303926", "0.602448", "0.5961824", "0.59254426", "0.59253204", "0.58767104", "0.58369315", "0.58064735", "0.58055794", "0.579832", "0.5781476", "0.5770356", "0.57517385", "0.5733817", "0.5665305", "0.5646749...
0.57871866
15
Conversion from Cartesian to BondAngleTorsion coordinates
def BAT(self, XYZ, extended=False): root = [distance(XYZ[self.rootInd[0]],XYZ[self.rootInd[1]]),\ distance(XYZ[self.rootInd[1]],XYZ[self.rootInd[2]]),\ angle(XYZ[self.rootInd[0]],XYZ[self.rootInd[1]],XYZ[self.rootInd[2]])] import itertools internal = root + \ [val for val in itertools.chain.from_iterable([\ BAT4(XYZ[a1],XYZ[a2],XYZ[a3],XYZ[a4]) \ for (a1,a2,a3,a4) in self._torsionIndL])] torsions = internal[5::3] phase_torsions = [(torsions[n] - torsions[self._firstTorsionTInd[n]]) \ if self._firstTorsionTInd[n]!=n else torsions[n] \ for n in range(len(torsions))] internal[5::3] = phase_torsions if not extended: return np.array(internal) external = self.extended_coordinates(XYZ[self.rootInd[0]], \ XYZ[self.rootInd[1]], XYZ[self.rootInd[2]]) return np.array(list(external) + list(internal))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def Cartesian(self, BAT):\n # Arrange BAT coordinates in convenient arrays\n offset = 6 if len(BAT) == (3 * self.natoms) else 0\n bonds = BAT[offset + 3::3]\n angles = BAT[offset + 4::3]\n phase_torsions = BAT[offset + 5::3]\n torsions = [(phase_torsions[n] + phase_torsions[self._firstTorsionTInd...
[ "0.6777609", "0.6658217", "0.6547693", "0.6523295", "0.63220453", "0.6290984", "0.62786305", "0.6244212", "0.62430567", "0.6160538", "0.61536187", "0.6145556", "0.61396515", "0.61340433", "0.60545677", "0.60487115", "0.6047855", "0.6031376", "0.6025377", "0.6023894", "0.60146...
0.0
-1
Conversion from (internal or extended) BondAngleTorsion to Cartesian coordinates
def Cartesian(self, BAT): # Arrange BAT coordinates in convenient arrays offset = 6 if len(BAT) == (3 * self.natoms) else 0 bonds = BAT[offset + 3::3] angles = BAT[offset + 4::3] phase_torsions = BAT[offset + 5::3] torsions = [(phase_torsions[n] + phase_torsions[self._firstTorsionTInd[n]]) \ if self._firstTorsionTInd[n]!=n else phase_torsions[n] \ for n in range(self.ntorsions)] p1 = np.array([0., 0., 0.]) p2 = np.array([0., 0., BAT[offset]]) p3 = np.array([BAT[offset+1]*np.sin(BAT[offset+2]), 0., \ BAT[offset]-BAT[offset+1]*np.cos(BAT[offset+2])]) # If appropriate, rotate and translate the first three atoms if offset == 6: # Rotate the third atom by the appropriate value (phi, theta, omega) = BAT[3:6] co = np.cos(omega) so = np.sin(omega) Romega = np.array([[co, -so, 0], [so, co, 0], [0, 0, 1]]) p3 = Romega.dot(p3) # Rotate the second two atoms to point in the right direction cp = np.cos(phi) sp = np.sin(phi) ct = np.cos(theta) st = np.sin(theta) Re = np.array([[cp * ct, -sp, cp * st], [ct * sp, cp, sp * st], [-st, 0, ct]]) p2 = Re.dot(p2) p3 = Re.dot(p3) # Translate the first three atoms by the origin origin = np.array(BAT[:3]) p1 += origin p2 += origin p3 += origin XYZ = np.zeros((self.natoms, 3)) XYZ[self.rootInd[0]] = p1 XYZ[self.rootInd[1]] = p2 XYZ[self.rootInd[2]] = p3 for ((a1,a2,a3,a4), bond, angle, torsion) in \ zip(self._torsionIndL,bonds,angles,torsions): sphere = Sphere(Vector(XYZ[a2]), bond) cone = Cone(Vector(XYZ[a2]), Vector(XYZ[a3] - XYZ[a2]), angle) plane123 = Plane(Vector(XYZ[a4]), Vector(XYZ[a3]), Vector(XYZ[a2])) points = sphere.intersectWith(cone).intersectWith(plane123) p = points[0] if (Plane(Vector(XYZ[a3]), Vector( XYZ[a2]), points[0]).normal * plane123.normal) > 0 else points[1] p = rotatePoint(Vector(p), Line(Vector(XYZ[a2]), Vector(XYZ[a2] - XYZ[a3])), torsion) XYZ[a1] = p.array return XYZ for ((a1,a2,a3,a4), bond, angle, torsion) in \ zip(self._torsionIndL,bonds,angles,torsions): p2 = XYZ[a2] p3 = XYZ[a3] p4 = XYZ[a4] # circle = sphere.intersectWith(cone) n23 = normalize(p3 - p2) # points = circle.intersectWith(plane123) # plane.intersectWith(Plane(circle.center, circle.normal)) is a line # line_direction = cross(normalize(cross(p4-p3,n23)),n23) # Rotate the point about the p2-p3 axis by the torsion angle v21 = (bond * np.cos(angle)) * n23 - (bond * np.sin(angle)) * cross( normalize(cross(p4 - p3, n23)), n23) s = np.sin(torsion) c = np.cos(torsion) XYZ[a1] = p2 - cross(n23, v21) * s + np.sum( n23 * v21) * n23 * (1.0 - c) + v21 * c
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _cartesian_to_internal(self, atom_position, bond_position, angle_position, torsion_position):\n # TODO: _cartesian_to_internal and _internal_to_cartesian should accept/return units and have matched APIs\n\n check_dimensionality(atom_position, unit.nanometers)\n check_dimensionality(bond_po...
[ "0.68272", "0.68232924", "0.6670016", "0.6668133", "0.6666709", "0.66622704", "0.6632937", "0.6616939", "0.6595138", "0.6567005", "0.6544198", "0.65291274", "0.6471032", "0.6468995", "0.63908124", "0.63474804", "0.63316333", "0.63281065", "0.631877", "0.6312516", "0.6256514",...
0.68568003
0
Opens the molecule in VMD
def showMolecule(self, colorBy=None, label=False, dcdFN=None): # Write PDB file # To set Occupancy, change atom.occupancy # To set Beta, change atom.temperature_factor import os.path pdbFN = os.path.join(MMTK.Database.molecule_types.directory, 'showMolecule.pdb') outF = MMTK.PDB.PDBOutputFile(pdbFN) outF.write(self.molecule) outF.close() # Write VMD script script = 'set ligand [mol new ' + pdbFN + ']\n' if colorBy is not None: script += 'mol modcolor 0 $ligand ' + colorBy + '\n' script += 'mol modstyle 0 0 CPK 1.000000 0.300000 10.000000 10.000000\n' if label: script += """ proc label_atoms { molid seltext } { set sel [atomselect $molid $seltext] set atomlist [$sel list] foreach {atom} $atomlist { set atomlabel [format "%d/%d" $molid $atom] label add Atoms $atomlabel } $sel delete } label_atoms 0 all """ if dcdFN is not None: script += 'animate delete all $ligand\n' script += 'mol addfile ' + dcdFN + ' type dcd waitfor all\n' scriptF = open('showMolecule.vmd', 'w') scriptF.write(script) scriptF.close() # Find and run vmd import AlGDock vmdCommand = AlGDock.findPath(AlGDock.search_paths['vmd']) import subprocess subprocess.call([vmdCommand, '-e', 'showMolecule.vmd']) # Remove files os.remove(pdbFN) os.remove('showMolecule.vmd')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def viewNMDinVMD(filename):\n\n vmd = pathVMD()\n if vmd:\n os.system('{0} -e {1}'.format(vmd, abspath(filename)))", "def _vmd_script_molecule(mole, filename=\"molecule.xyz\"):\n output = \"# load new molecule\\n\"\n if len(mole.atom) == 0:\n raise ValueError(\"Need at least one molecul...
[ "0.612638", "0.6115121", "0.60250276", "0.6011934", "0.5911261", "0.57081985", "0.568981", "0.5678963", "0.5570185", "0.5564583", "0.5564583", "0.5564583", "0.5531796", "0.5531796", "0.54938924", "0.54809994", "0.5477402", "0.5396461", "0.5377517", "0.5377517", "0.5375009", ...
0.6395765
0
Test read and write ints.
def test_message_int(): result = True message = msg.Message() for i in range(num_it): message.appendInt(i) if message.length != msg.HEADER_SIZE + (i+1)*msg.intStruct.size: print("Size is ", message.length, " but should be ", msg.HEADER_SIZE + (i+1)*msg.intStruct.size) print("Error : message.appendInt") result = False message.resetCursor() for i in range(num_it): r = message.readInt() if r != i: print(r, " vs ", i) print("Error : message.read/appendInt") result = False return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read(self) -> int:\n ...", "def test_int_field():", "def read(self) -> int:", "def test_numbers_roundtrip():\n for num in (0, 1, 2, 178, 300, BIG_NUMBER):\n num2 = UnsignedInt.read(UnsignedInt.to_bytes(num))\n assert num2 == num", "def test_integer(self):\n esnA = ESN(N_i...
[ "0.62519395", "0.6250594", "0.62442267", "0.61574054", "0.5960592", "0.59363145", "0.5931189", "0.5928802", "0.59218436", "0.587367", "0.5865747", "0.58532387", "0.57997644", "0.5783584", "0.57745636", "0.5768972", "0.5754527", "0.57348996", "0.57348996", "0.57081896", "0.569...
0.625918
0
Test read and write floats.
def test_message_float(): result = True message = msg.Message() for i in range(num_it): message.appendFloat(i/128.789456) if message.length != msg.HEADER_SIZE + (i+1)*msg.floatStruct.size: print("Size is ", message.length, " but should be ", msg.HEADER_SIZE + (i+1)*msg.floatStruct.size) print("Error : message.appendFloat") result = False message.resetCursor() for i in range(num_it): r = message.readFloat() if abs(r - i/128.789456) > 0.000001: print(r, " vs ", i/128.789456) print("Error : message.read/appendFloat") result = False return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_float():\n floatify = fields.FloatField().adapt\n\n for input, expect in [\n (1.1, 1.1),\n (11, 11.0),\n (int(5.7), 5)\n ]:\n assert floatify(input) == expect", "def test_float_storage():\n values = [2.3434, 124012.2323209999, -12.39212445433389]\n\n for value ...
[ "0.71284944", "0.7088308", "0.6970931", "0.6921978", "0.68760276", "0.6846847", "0.68283427", "0.67947567", "0.67181623", "0.6711072", "0.66815597", "0.65003604", "0.6471494", "0.6447859", "0.6403583", "0.63836086", "0.6375022", "0.63572294", "0.629849", "0.62963325", "0.6284...
0.7005608
2
Test read and write booleans.
def test_message_boolean(): result = True message = msg.Message() for i in range(num_it): message.appendBoolean(True if i % 2 == 0 else False) if message.length != msg.HEADER_SIZE + (i+1)*msg.boolStruct.size: print("Size is ", message.length, " but should be ", msg.HEADER_SIZE + (i+1)*msg.boolStruct.size) print("Error : message.appendBoolean") result = False message.resetCursor() for i in range(num_it): r = message.readBoolean() if r != (True if i % 2 == 0 else False): print(r, " vs ", (True if i % 2 == 0 else False)) print("Error : message.read/appendBoolean") result = False return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_boolean_roundtrip():\n for b in (True, False):\n assert b == Boolean.read(Boolean.to_bytes(b))", "def read(reader: BitStreamReader, _index: int) -> bool:\n\n return reader.readBool()", "def test_bool_field():", "def test_for_bool(self, parse_input_mocked_metadata):\n bb = par...
[ "0.6882313", "0.66271466", "0.65398455", "0.63707685", "0.6339095", "0.62233245", "0.6203335", "0.6150687", "0.6148839", "0.61370564", "0.5970456", "0.5936587", "0.59159636", "0.59159636", "0.5886013", "0.5855655", "0.5835535", "0.58087593", "0.5781061", "0.5776412", "0.57715...
0.6360841
4
Test read and write strings.
def test_message_string(): result = True message = msg.Message() size = 0 for i in range(num_it): message.appendString(str(i) + "azertyuiopqsdfghjklmwxcvbn") size += len(str(i) + "azertyuiopqsdfghjklmwxcvbn") if message.length != msg.HEADER_SIZE + (i+1)*msg.intStruct.size + size: print("Size is ", message.length, " but should be ", msg.HEADER_SIZE + (i+1)*msg.intStruct.size + size) print("Error : message.appendString") result = False message.resetCursor() for i in range(num_it): r = message.readString() if r != str(i) + "azertyuiopqsdfghjklmwxcvbn": print(r, " vs ", str(i) + "azertyuiopqsdfghjklmwxcvbn") print("Error : message.read/appendString") result = False return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_file_ascii_readwrite(self):\n FileWriter(self.ascii_path).write(self.ascii_string) # file write\n ascii_text = FileReader(self.ascii_path).read() # file read\n self.assertEqual(ascii_text, self.ascii_string)", "def test_string():", "def test_file_ascii_readwrite_append(self):\n ...
[ "0.6916156", "0.6884965", "0.65640235", "0.6562629", "0.6518813", "0.64406925", "0.6423337", "0.6257812", "0.62549824", "0.6238165", "0.62272376", "0.6220291", "0.6190515", "0.61704606", "0.6157264", "0.6138941", "0.6124542", "0.6122053", "0.61147743", "0.6111996", "0.605968"...
0.56046695
65
Test read and write mixed datatypes.
def test_message_mixed(): result = True message = msg.Message() size = 0 for i in range(num_it): message.appendInt(8848) message.appendBoolean(True) message.appendFloat(128.789456) message.appendString(str(i) + "azertyuiopmlkjhgfdsqwxcvbn") size += msg.intStruct.size + msg.boolStruct.size + msg.floatStruct.size + msg.intStruct.size + len(str(i) + "azertyuiopqsdfghjklmwxcvbn") if message.length != msg.HEADER_SIZE + size: print("Size is ", message.length, " but should be ", msg.HEADER_SIZE + size) print("Error : message.appendMixed") result = False message.resetCursor() for i in range(num_it): a = message.readInt() b = message.readBoolean() c = message.readFloat() d = message.readString() if a != 8848: print("Error in int", i, a) result = False if not b is True: print("Errro in boolean", i, b) result = False if abs(c- 128.789456) > 0.00001: print("Error in float", i, c) result = False if d != str(i) + "azertyuiopmlkjhgfdsqwxcvbn": print("Error in string", i, d) result = False return result # // mixed # message = new Message(); # for(int j = 0 ; j < 1024 ; j++){ # message.resetCursor(); # message.appendInt(8848); # message.appendBoolean(true); # message.appendFloat((float) 128.789456); # message.appendString("azertyuiopmlkjhgfdsqwxcvbn"); # message.resetCursor(); # if(message.readInt() != 8848){ # System.out.println("Error in Int"); # System.exit(0); # } # if(message.readBoolean() != true){ # System.out.println("Error in Boolean"); # System.exit(0); # } # if(message.readFloat() != (float) 128.789456){ # System.out.println("Error in Float"); # System.exit(0); # } # if(message.readString().compareTo("azertyuiopmlkjhgfdsqwxcvbn") != 0){ # System.out.println("Error in String"); # System.exit(0); # } # } # System.out.println("OK : mixed types");
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_datatype():\n\n assert isinstance(pf.get_datatype(), torch.dtype)\n assert pf.get_datatype() == torch.float32\n\n pf.set_datatype(torch.float64)\n assert isinstance(pf.get_datatype(), torch.dtype)\n assert pf.get_datatype() == torch.float64\n pf.set_datatype(torch.float32)\n\n with py...
[ "0.67663014", "0.6662102", "0.66280866", "0.65572697", "0.6511266", "0.64390135", "0.6435044", "0.63185567", "0.63012403", "0.62329113", "0.6192442", "0.6122348", "0.6109678", "0.606131", "0.6042542", "0.6038543", "0.59518325", "0.5944244", "0.5932898", "0.5906418", "0.590104...
0.53594905
89
Handles a join game request. Adds the user to the game if it is not full. Otherwise, rejects the user from joining.
def join_game(players_cursor, states_cursor, user, room_id): # Make sure player isn't already in the game joined_query = '''SELECT * FROM players_table WHERE user = ? AND room_id = ?;''' joined = players_cursor.execute(joined_query, (user, room_id)).fetchall() if len(joined) > 0: # TODO: Return proper message for already in game raise KeyError # Check if the game is already full players_query = '''SELECT * FROM players_table WHERE room_id = ?;''' players = players_cursor.execute(players_query, (room_id,)).fetchall() if len(players) == MAX_PLAYERS: # TODO: Return proper message for joining full game raise ValueError # Since the game is not full, add the player to the game insert_player = '''INSERT into players_table VALUES (?,?,?,?,?,?,?);''' players_cursor.execute(insert_player, (user, STARTING_STACK, 0, 0, "", len(players), room_id)) FRAMES.append(display_game(players_cursor, states_cursor, user, room_id))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def join(self, ctx):\n if lobby.count(f\"{ctx.author.mention}\") == 0:\n add(lobby, ctx.author.mention)\n await ctx.channel.send(\"You've been added to the queue!\")\n else:\n await ctx.channel.send(\"You're already queued for a match!\")\n await ctx.chan...
[ "0.6783792", "0.67832756", "0.664182", "0.6565777", "0.653179", "0.6504052", "0.6492886", "0.6466361", "0.643423", "0.6424354", "0.63196415", "0.6313337", "0.63049585", "0.6297384", "0.6251035", "0.6194082", "0.6171204", "0.61612934", "0.61388975", "0.61386853", "0.6117116", ...
0.6428327
9
Handles a start game request. Starts the game if the request was sent by the host, and there are at least two players.
def start_game(players_cursor, states_cursor, user, room_id): users_query = '''SELECT * FROM players_table WHERE room_id = ?;''' users = players_cursor.execute(users_query, (room_id,)).fetchall() if users[0][USERNAME] == user: # Insert a game state entry into the states_table deck = ",".join(cards) board = "" dealer = random.randint(0, len(users) - 1) action = (dealer + 3) % len(users) pot = 0 new_state = '''INSERT into states_table VALUES (?,?,?,?,?,?);''' states_cursor.execute(new_state, (deck, board, dealer, action, pot, room_id)) start_new_hand(players_cursor, states_cursor, dealer, user, room_id) else: raise ValueError
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def game_start(self):\r\n\t\tself._comm_server.broadcast_message(\"game-start\")\r\n\t\tself._is_game_started = True\r\n\t\tself._handlers[\"game-start\"].invoke()\r\n\t\t_logger.info(\"Game is started.\")", "def start_game(self, **kwargs):\n\n success, info = self.gms.start_game(\n player=kwar...
[ "0.7171834", "0.7154305", "0.68895155", "0.67457765", "0.6644632", "0.6629957", "0.66196835", "0.66131645", "0.6558208", "0.652107", "0.64768547", "0.6432589", "0.64246315", "0.6315022", "0.6312065", "0.621343", "0.6191547", "0.6181988", "0.61723584", "0.6163077", "0.6129981"...
0.5490905
76
Handles a leave game request. Deletes the user from the game.
def leave_game(players_cursor, states_cursor, user, room_id): leave_query = '''DELETE FROM players_table WHERE user = ? AND room_id = ?''' players_cursor.execute(leave_query, (user, room_id)) FRAMES.append(display_game(players_cursor, states_cursor, user, room_id))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def leave(msg: telebot.types.Message):\n if utils.in_menu(msg.from_user):\n bot.reply_to(\n msg,\n 'This command outside of game is useless.'\n )\n return\n\n game, user, opponent = utils.get_game_user_opponent(msg.from_user)\n if not game or not user:\n #...
[ "0.7001719", "0.6419002", "0.63921964", "0.639108", "0.6370939", "0.633421", "0.63169086", "0.6268317", "0.6229235", "0.61546296", "0.6119499", "0.6118067", "0.60932064", "0.6045495", "0.6015096", "0.5974975", "0.59517586", "0.59031034", "0.59014386", "0.5897309", "0.5892574"...
0.66279423
1
Select Relationships associated with specified fact_id.
def select_by_fact_id(cls, fact_id): return db.session.query(cls).filter_by(fact_id=fact_id).all()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read_relationships(person_id):\n try:\n conn = sqlite3.connect(settings.database_name)\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n c.execute(\"PRAGMA foreign_keys = ON\")\n c.execute(relationship_query, (person_id,)) # note a tuple is needed as a parameter valu...
[ "0.58382934", "0.514626", "0.50882876", "0.5030613", "0.5016771", "0.49949938", "0.4898808", "0.48690563", "0.48584178", "0.48120192", "0.47925648", "0.47674325", "0.47505498", "0.473037", "0.473037", "0.473037", "0.47198808", "0.47121876", "0.46776888", "0.46749067", "0.4671...
0.68101376
0
Select Relationship with specified subject, object and relationship type.
def select_by_foreign_keys(cls, subject_id=None, object_id=None, relationship_type_id=None): filter_clause = sa.and_( sa.and_(cls.subject_id == subject_id, cls.object_id == object_id), cls.relationship_type_id == relationship_type_id) return db.session.query(cls).filter(filter_clause).first()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def select_by_values(cls, relationship_type_name=None, relationship_number=None,\n subject_name=None, object_name=None):\n query = db.session.query(cls).\\\n join(RelationshipType).\\\n filter(RelationshipType.relationship_type_name==relationship_type_name)\n ...
[ "0.6398576", "0.59592456", "0.58598846", "0.5763038", "0.5670848", "0.56461585", "0.5524951", "0.5501221", "0.5444976", "0.5378021", "0.53130275", "0.5282662", "0.5178828", "0.51488453", "0.5099441", "0.50218856", "0.501885", "0.49724635", "0.48888737", "0.4885239", "0.487039...
0.72244817
0
Select Relationships with specified relationship_type, count, subject, and object.
def select_by_values(cls, relationship_type_name=None, relationship_number=None, subject_name=None, object_name=None): query = db.session.query(cls).\ join(RelationshipType).\ filter(RelationshipType.relationship_type_name==relationship_type_name) if relationship_number: query = query.filter(Relationship.count==relationship_number) if subject_name: subject_concept = sa_orm.aliased(Concept) query = query.\ join(subject_concept, Relationship.subject_id==subject_concept.concept_id).\ filter(subject_concept.concept_name==subject_name) if object_name: object_concept = sa_orm.aliased(Concept) query = query.\ join(object_concept, Relationship.object_id==object_concept.concept_id).\ filter(object_concept.concept_name==object_name) return query.all()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def select_by_foreign_keys(cls, subject_id=None, object_id=None, relationship_type_id=None):\n filter_clause = sa.and_(\n sa.and_(cls.subject_id == subject_id, cls.object_id == object_id),\n cls.relationship_type_id == relationship_type_id)\n return db.session.query(cls).filter(...
[ "0.6642475", "0.6234097", "0.61171645", "0.5905707", "0.573527", "0.5697212", "0.558768", "0.55415577", "0.5488156", "0.5187914", "0.5047478", "0.50362355", "0.5031117", "0.5009696", "0.5007061", "0.4995968", "0.4954581", "0.49293298", "0.49109417", "0.48943478", "0.4888402",...
0.7105433
0
Validate requests decorator with Cerberus
def validate_request_cerberus(schema): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): body_json = request.get_json() current_app.logger.info(body_json) v = Validator(schema, require_all=True) v.allow_unknown = True # TODO: allow request params other then the ones defined on the schema level if not v.validate(body_json): valid_params_list = ', '.join(schema.keys()) return response_fail(f"You must call with all request params: {valid_params_list}") return func(*args, **kwargs) return wrapper return decorator
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def valid_request(func):\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except BadRequest as e:\n raise InvalidRequest(description='request parameters, queries or body format are invalid.',\n code=e....
[ "0.68247503", "0.6648503", "0.6610281", "0.65511626", "0.64839965", "0.5961608", "0.59245205", "0.5921186", "0.589062", "0.5860312", "0.5833157", "0.5833084", "0.5802698", "0.57723325", "0.5756725", "0.5740091", "0.57035977", "0.5687878", "0.5684185", "0.5676626", "0.5673376"...
0.70384467
0
Construct the core application.
def create_app(): app = Flask(__name__, instance_relative_config=False) app.register_blueprint(auth_bp, url_prefix='/auth') app.register_blueprint(errors_bp, url_prefix='/error') app.config.from_object('config.Config') db.init_app(app) store.bind(db) login_manager.init_app(app) Session(app) captcha = FlaskSessionCaptcha(app) captcha.init_app(app) with app.app_context(): from . import routes # Import routes db.create_all() # Create sql tables for our data models return app
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _make_core_app():\n app = web.Application(middlewares=[middleware.error_middleware])\n management_routes.setup(app, is_core=True)\n return app", "def main():\n LOGGER.info('Loading Application')\n main_app = Application()\n parser = argparse.ArgumentParser()\n parser.add_argu...
[ "0.7207223", "0.70791864", "0.6998072", "0.6950758", "0.6818118", "0.68160903", "0.67678857", "0.6719606", "0.66488445", "0.6626063", "0.65972114", "0.65353584", "0.65281093", "0.6521015", "0.64897716", "0.6488322", "0.6431467", "0.6392214", "0.6355824", "0.6346588", "0.63364...
0.59344965
82
Plots the graph. If the nodes have a position, the nodes will be placed there. Otherwise, they will be placed in a random but elegant manner.
def plot_graph(self) -> None:
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def plot_graph(self) -> None:\n\n nodes_on_graph = self.dw_graph.get_all_v()\n for k, v in nodes_on_graph.items():\n if v.position is None:\n x_rand = random.uniform(0.5, self.dw_graph.v_size())\n y_rand = random.uniform(0.5, self.dw_graph.v_size())\n ...
[ "0.7539952", "0.69758826", "0.6917775", "0.6841799", "0.6772024", "0.66144824", "0.66071594", "0.65934306", "0.65229076", "0.65064275", "0.6494702", "0.6480308", "0.6477845", "0.6361443", "0.63394064", "0.6281064", "0.62662697", "0.6260735", "0.6240371", "0.62216246", "0.6214...
0.7134664
1
Poll for workers to wake up wait up to 10 seconds
def wait_for_workers(self, workers_db_key): timeout = time.time() + 10 while True: n_workers = self.tempstore.conn.scard(workers_db_key) self.logger.info('Got redis scard resp: %s', n_workers) if n_workers > 0: break if time.time() > timeout: raise Exception('Workers did not come up - please check syslog') time.sleep(1) self.logger.info('Workers successfully started')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def monitor(self):\r\n while True:\r\n for worker, start_time in self.workers.items():\r\n if (not worker.isAlive() or\r\n self.timeout\r\n and datetime.now() - start_time > self.timeout): \r\n\r\n self.work_count.get_nowait(...
[ "0.7244954", "0.68966836", "0.6490199", "0.64271986", "0.63700104", "0.63443273", "0.6310271", "0.6221005", "0.62040955", "0.6180912", "0.61787575", "0.61787575", "0.61787575", "0.61610657", "0.6151061", "0.6140504", "0.6097463", "0.60734135", "0.6073053", "0.6060509", "0.605...
0.66818553
2
Formats comparison as a strings
def format_comparison(objs): def formatter(comp): if not isinstance(comp, tuple): return str(comp) output = [] return "\n".join([comp.type] + [" "+errmessage for errmessage in output]) results = map(formatter,objs) return "\n".join(results) #obj1,obj2 = comp ### Sections #for i,s1,s2 in diffs: # if s1 and s2: # output.append(f"Section {i} does not match:") # result = compare_sections(s1,s2) # output.extend(almethods.linepadder(result)) # else: # if s1: # output.append(f"Door 2 missing Section {i}") # else: # output.append(f"Door 1 missing Section {i}")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def comparison(self) -> str:\n return self._values.get('comparison')", "def generate_comparison_output_string(comparisons: List[Dict[str, Any]]) -> str:\n result_dict = generate_comparison_dict(comparisons)\n result_string = json.dumps(result_dict, sort_keys=True, indent=4)\n return result_string...
[ "0.7065585", "0.6774839", "0.66851884", "0.66676676", "0.6445696", "0.64411914", "0.64020616", "0.63991475", "0.6312643", "0.6112813", "0.6112813", "0.610843", "0.6023886", "0.6010248", "0.59334326", "0.5931873", "0.59163105", "0.5899037", "0.5899037", "0.5896669", "0.5889875...
0.69769394
1
Catches a difference when one or both of the objects are None (since it is handled the same across methods)
def none_comparison(func): @functools.wraps(func) def inner(obj1,obj2): if obj1 is not None and obj2 is not None: return func(obj1, obj2) if obj1 is None and obj2 is None: return [] if obj1 is not None and obj2 is None: return Difference(f"Second {obj1.__class__.__name__} is None",(obj1,None)) return Difference(f"First {obj2.__class__.__name__} is None",(None,obj2)) return inner
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _check_none(self) -> PossibleResult[T]:\n if self.constructor == type(None):\n if not self.obj is None:\n raise DeserializeError(\n type(None), self.obj, self.new_depth, self.key\n )\n return self.obj # type: ignore\n return ...
[ "0.6248695", "0.5997152", "0.59885675", "0.59798694", "0.5903614", "0.5886935", "0.58787954", "0.5814186", "0.58113503", "0.57685584", "0.5712491", "0.56863844", "0.56762654", "0.56702787", "0.56702787", "0.5659557", "0.563092", "0.5625755", "0.5596324", "0.55960506", "0.5590...
0.7289079
0
Compares Attributes between 2 objects via getattr, returning the attribute values as a tuple if they do not match
def attr_comparison(obj1,obj2,attrs): return [Difference(f"{obj1.__class__.__name__}.{attr}",(result1,result2)) for attr in attrs if (result1 := getattr(obj1,attr)) != (result2 := getattr(obj2,attr))]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attrs_to_tuple(obj):\n return tuple(getattr(obj, a) for a in attrs)", "def compare(current_formation):\n\n attribute_tuple = ()\n for attr in attributes:\n\n if attr in current_formation:\n attribute_tuple += (current_formation[attr],)\n ...
[ "0.6573749", "0.64668816", "0.6218231", "0.61928684", "0.61631376", "0.6161874", "0.61611706", "0.61574703", "0.5891995", "0.58485514", "0.5843817", "0.5834111", "0.57660866", "0.57439977", "0.5732433", "0.5712868", "0.56471366", "0.5642409", "0.5622416", "0.5610146", "0.5576...
0.73285353
0
Given a list of tuples comparised of (subcomparison method, attr name for comparison), returns any Difference tuple retunred by each method using the given attr of obj1 and obj2 as arguments (if that method is not None)
def sub_comparison(obj1,obj2,translate): return [Difference(f"{obj1.__class__.__name__} > {meth.__name__}",result) for (meth,attr) in translate if (result := meth(getattr(obj1,attr),getattr(obj2,attr))) is not None]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_comparison(obj1,obj2,attrs):\n return [Difference(f\"{obj1.__class__.__name__}.{attr}\",(result1,result2)) for attr in attrs if (result1 := getattr(obj1,attr)) != (result2 := getattr(obj2,attr))]", "def with_cmp(attrs):\n def attrs_to_tuple(obj):\n \"\"\"\n Create a tuple of all valu...
[ "0.6840443", "0.57526386", "0.5622923", "0.54995364", "0.54768133", "0.5458876", "0.5385492", "0.5371001", "0.5325865", "0.5241565", "0.51938784", "0.5181397", "0.51578325", "0.51564384", "0.5137712", "0.50981116", "0.50660944", "0.50567687", "0.50435317", "0.5015092", "0.500...
0.7408652
0
Postmortem, using a custom debug function if passed
def post_mortem(*args, debug_fn: Optional[Callable] = None, **kwargs) -> None: if debug_fn is None: import pdb debug_fn = pdb.post_mortem debug_fn()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def debug():", "def debug_run(self):\n raise NotImplementedError", "def xpm(Pdb=Pdb):\n info = sys.exc_info()\n print(traceback.format_exc())\n post_mortem(info[2], Pdb)", "def after_step(context, step):\n if context.config.userdata.getbool(\"debug\") and step.status == \"failed\":\n ...
[ "0.7278622", "0.69504553", "0.68875915", "0.6863419", "0.6848077", "0.6839908", "0.6770106", "0.66839147", "0.66665906", "0.66077083", "0.660491", "0.6530755", "0.6507357", "0.6416765", "0.63856596", "0.63856345", "0.6353304", "0.63263094", "0.6322992", "0.6319444", "0.630869...
0.8282989
0
Process batch and produce inputs for the model.
def process_batch(batch): args = get_args() tokens = batch['text'].long().cuda().contiguous() types = batch['types'].long().cuda().contiguous() labels = batch['label'].long().cuda().contiguous() attention_mask = batch['padding_mask'].float().cuda().contiguous() if args.fp16: attention_mask = attention_mask.half() return tokens, types, labels, attention_mask
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def process_batch(self, inputs):\n for key, ipt in inputs.items():\n inputs[key] = ipt.to(self.device)\n\n # we only feed the image with frame_id 0 through the depth encoder\n features = self.models[\"encoder\"](inputs[\"color_aug\", 0, 0])\n outputs = self.models[\"depth\"](...
[ "0.75249064", "0.7168187", "0.7088052", "0.69800156", "0.69082737", "0.6876216", "0.67433715", "0.6727425", "0.67233706", "0.67233706", "0.6711491", "0.66323096", "0.6620821", "0.662077", "0.6583442", "0.65692496", "0.65633017", "0.6563035", "0.65559244", "0.65559244", "0.653...
0.6349032
32
Simple forward step with crossentropy loss.
def _cross_entropy_forward_step(batch, model): timers = get_timers() # Get the batch. timers('batch-generator', log_level=2).start() try: batch_ = next(batch) except BaseException: batch_ = batch tokens, types, labels, attention_mask = process_batch(batch_) timers('batch-generator').stop() # Forward model. output_tensor = model(tokens, attention_mask, tokentype_ids=types) return output_tensor, partial(cross_entropy_loss_func, labels)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def forward_train(self, preds_T: torch.Tensor) -> torch.Tensor:\n fake_label = preds_T.data.max(1)[1]\n return F.cross_entropy(preds_T, fake_label)", "def train_step(self, X_batch: np.ndarray, Y_batch: np.ndarray):\n\n # Almost the same as previous task, calculates the cross entropy loss for...
[ "0.7079546", "0.7007037", "0.6882113", "0.67776626", "0.6773821", "0.6759933", "0.6734602", "0.67251396", "0.66867614", "0.66795677", "0.6665437", "0.66561353", "0.6633398", "0.66322726", "0.6624705", "0.6619393", "0.6619258", "0.6606617", "0.65844935", "0.65608215", "0.65534...
0.7801202
0
Data loader. Note that batchsize is the local (per GPU) batchsize.
def build_data_loader(dataset, micro_batch_size, num_workers, drop_last, task_collate_fn=None): # Sampler. world_size = mpu.get_data_parallel_world_size() rank = mpu.get_data_parallel_rank() sampler = torch.utils.data.distributed.DistributedSampler( dataset, num_replicas=world_size, rank=rank) # Data loader. Note that batch size is the per GPU batch size. data_loader = torch.utils.data.DataLoader(dataset, batch_size=micro_batch_size, sampler=sampler, shuffle=False, num_workers=num_workers, drop_last=drop_last, pin_memory=True, collate_fn=task_collate_fn) return data_loader
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def data_loader(\n self, batch_size: int = 1, iter_steps: int = 0, batch_as_list: bool = True\n ) -> DataLoader:\n data = self.data\n datasets = []\n\n for _, dat in data.items():\n datasets.append(dat.dataset())\n\n if len(datasets) < 1:\n raise FileNotF...
[ "0.7391102", "0.7355233", "0.7307113", "0.7191186", "0.7188778", "0.71511465", "0.7052301", "0.69866663", "0.6968007", "0.69573814", "0.6949311", "0.69279605", "0.6880958", "0.68485147", "0.6814167", "0.68017983", "0.6782323", "0.6779926", "0.67751354", "0.67704856", "0.67450...
0.6592258
37
Build a looped dataloader with infinite size.
def _build_infinite_size_dataloader(dataloader): iterator = dataloader.__iter__() while True: try: yield iterator.__next__() except StopIteration: iterator = dataloader.__iter__()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, len):\n self.data = []\n i = 0\n while i < len:\n i += 1\n self.data.append(self.Data())\n self.length = len", "def __iter__(self):\n\t\tfor i, data in enumerate(self.dataloader):\n\t\t\tif i * self.opt.batch_size >= self.opt.max_dataset_size:\...
[ "0.62806386", "0.62140703", "0.62047887", "0.6165703", "0.6139719", "0.5913532", "0.5898376", "0.58914024", "0.5870807", "0.58379287", "0.5795319", "0.5757869", "0.5757244", "0.57561076", "0.57423776", "0.5669886", "0.5666476", "0.5624543", "0.5618841", "0.5613911", "0.560385...
0.83487415
0
Traing and validation dataloaders.
def _build_train_valid_dataloaders(train_dataset, valid_dataset, task_collate_fn=None): args = get_args() print_rank_0('building train and validation dataloaders ...') # Training dataset. train_dataloader = build_data_loader(train_dataset, args.micro_batch_size, args.num_workers, not args.keep_last, task_collate_fn) # Set the training iterations. args.train_iters_per_epoch = len(train_dataloader) args.train_iters = args.epochs * args.train_iters_per_epoch # Validation dataset. For this dataset, we do not need to set up # shuffling so we can just use a simple infinite loop. valid_dataloader_ = build_data_loader(valid_dataset, args.micro_batch_size, args.num_workers, not args.keep_last, task_collate_fn) valid_dataloader = _build_infinite_size_dataloader(valid_dataloader_) # Now that we've built the data loaders, set batch_size arguments # to the actual batch size the model will see for this dataset. # This is necessary so pipeline transfers know what size they are # and the LR schedule, which is based on samples seen, gets set # correctly. args.orig_micro_batch_size = args.micro_batch_size args.orig_global_batch_size = args.global_batch_size if hasattr(train_dataset, 'sample_multiplier'): # If our dataset as a sample_multiplier attribute that means # each "sample" from the dataset actually has multiple samples # that will collapse into the batch dimension (for example in # the RACE dataset that has several options), we need to # account for that when setting the micro batch size. args.micro_batch_size *= train_dataset.sample_multiplier args.global_batch_size *= train_dataset.sample_multiplier return train_dataloader, valid_dataloader
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_data_loaders(args, tokenizer):\n personachat = get_dataset(tokenizer, args.dataset_path, args.dataset_cache, args.train_lang)\n _ = personachat.pop(\"test\", None)\n logger.info(\"Build inputs and labels\")\n datasets = {\"train\": [], \"valid\": []}\n\n if args.train_lang in [\"En\", \"Fr\"...
[ "0.68130106", "0.6807883", "0.67034125", "0.6500614", "0.6431421", "0.63997084", "0.62811214", "0.6247464", "0.6246502", "0.6224758", "0.6217445", "0.61995816", "0.6196357", "0.613247", "0.6116584", "0.6099218", "0.60890913", "0.60885996", "0.6040629", "0.60174674", "0.598177...
0.6290276
6
Main finetune function used across all tasks.
def finetune(train_valid_datasets_provider, model_provider, model_type=ModelType.encoder_or_decoder, forward_step=_cross_entropy_forward_step, end_of_epoch_callback_provider=None, task_collate_fn=None): args = get_args() timers = get_timers() assert args.rampup_batch_size is None, \ 'batch size scaling is not supported for finetuning' # Train and validation data loaders. timers('train/valid/test dataset/dataloder', log_level=0).start() if args.epochs > 0: train_dataset, valid_dataset = train_valid_datasets_provider() train_dataloader, valid_dataloader = _build_train_valid_dataloaders( train_dataset, valid_dataset, task_collate_fn) else: args.train_iters = 0 timers('train/valid/test dataset/dataloder').stop() # Build calback function. timers('callback function', log_level=0).start() end_of_epoch_callback = None if end_of_epoch_callback_provider is not None: end_of_epoch_callback = end_of_epoch_callback_provider() timers('callback function').stop() # Build model, optimizer and learning rate scheduler. timers('model and optimizer', log_level=0).start() model, optimizer, opt_param_scheduler = setup_model_and_optimizer(model_provider, model_type) timers('model and optimizer').stop() # If pretrained checkpoint is provided and we have not trained for # any iteration (i.e., iteration is zero), then load the pretrained # checkpoint. timers('pretrained checkpoint', log_level=0).start(barrier=True) if args.iteration == 0 and args.pretrained_checkpoint is not None: original_load = args.load args.load = args.pretrained_checkpoint original_rng = args.no_load_rng args.no_load_rng = True _ = load_checkpoint(model, None, None) args.load = original_load args.no_load_rng = original_rng # This is critical when only model is loaded. We should make sure # main parameters are also updated. optimizer.reload_model_params() timers('pretrained checkpoint').stop() # Print setup timing. print_rank_0('done with setups ...') timers.log(['train/valid/test dataset/dataloder', 'callback function', 'model and optimizer', 'pretrained checkpoint'], barrier=True) print_rank_0('training ...') # Finetune the model. if args.epochs > 0: _train(model, optimizer, opt_param_scheduler, forward_step, train_dataloader, valid_dataloader, end_of_epoch_callback) # Or just evaluate. else: if end_of_epoch_callback is not None: print_rank_0('evaluation only mode, setting epoch to -1') end_of_epoch_callback(model, epoch=-1, output_predictions=True) print_rank_0('done :-)')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tasks():", "def task():", "def main():\n run_test_all()", "def finetune(ft_ds, model, task, epochs=10, eval_ds=None):\n\n print('==========FINETUNE==========')\n\n # Filter out undesired examples with excluded_label\n ds = ft_ds.filter(lambda x: x['label'] != task['excluded_label'])\n ds =...
[ "0.6263237", "0.6186667", "0.6184663", "0.60012114", "0.59752226", "0.59752226", "0.5871787", "0.58552486", "0.58440095", "0.58113", "0.579075", "0.57533723", "0.5727783", "0.57255954", "0.572342", "0.5712383", "0.5693964", "0.5688711", "0.567766", "0.56723386", "0.56669414",...
0.0
-1
Get absolute path to resource, works for dev and for PyInstaller
def resource_path(relative_path): try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_resource_path():\n return os.path.join(os.path.dirname(__file__), \"resources\") + os.path.sep", "def resourcePath(relative):\r\n try:\r\n # PyInstaller creates a temp folder and stores path in _MEIPASS\r\n base_path = sys._MEIPASS\r\n except Exception:\r\n base_path = os.pa...
[ "0.8370706", "0.8281029", "0.8249505", "0.81395245", "0.81143504", "0.80990154", "0.8094557", "0.8080119", "0.8068112", "0.8067861", "0.806291", "0.806291", "0.806291", "0.806291", "0.806291", "0.806291", "0.806291", "0.80574095", "0.80550015", "0.80407953", "0.80257154", "...
0.8045328
29
Treats wildcards as errors
def custom_score(stats): convention = stats['convention'] error = stats['error'] refactor = stats['refactor'] warning = stats['warning'] statement = stats['statement'] wildcards = stats['by_msg'].get('wildcard-import', False) if wildcards: warning = warning - wildcards error = error + wildcards return 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) return stats['global_note']
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_wildcard_all(self):\n with self.assertRaisesRegex(\n ValueError, \"WILDCARD_ALL passed with other key information\"):\n _path.RootOper.Foo(_defs.WILDCARD_ALL, 4)", "def test_wildcard_at_opening_of_string(self):\n with self.assertRaises(index.QueryError):\n ...
[ "0.6498623", "0.645085", "0.6279789", "0.6237322", "0.58695716", "0.57996774", "0.56907517", "0.5679271", "0.5674153", "0.55909884", "0.5565901", "0.5562286", "0.5515654", "0.5460359", "0.5418555", "0.5417609", "0.5408707", "0.53870875", "0.53637373", "0.53242457", "0.5293056...
0.0
-1
Returns the data representation of the timer, will be used to send it over the web socket.
def get_list_data(self): key = 'timer' if self.repeated: key += '_repeat' return '%s %s' % (key, self.data.get_list_data())
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_timer_data(self):\n return {\"sRef\": self._timer_service_ref_entry.get_text(),\n \"begin\": int(datetime.strptime(self._timer_begins_entry.get_text(), self._TIME_STR).timestamp()),\n \"end\": int(datetime.strptime(self._timer_ends_entry.get_text(), self._TIME_STR).time...
[ "0.7045231", "0.6424909", "0.63322824", "0.61530703", "0.61145544", "0.6017771", "0.592645", "0.59186465", "0.59073746", "0.5903025", "0.5891447", "0.58581436", "0.5799672", "0.5785056", "0.575003", "0.5743803", "0.5738986", "0.5706574", "0.5649952", "0.5620999", "0.5616731",...
0.63464636
2
Return a dictionary version json serializable
def to_dict(self) -> Dict[str, Any]: return {'solver_type': type(self).__name__, 'lr_policy': self.lr_policy, 'base_lr': self.base_lr, 'gamma': self.gamma, 'momentum': self.momentum, 'max_iter': self.max_iter, 'weight_decay': self.weight_decay, 'iter_size': self.iter_size, 'stepsize': self.stepsize, 'stepvalues': self.stepvalues, 'cold_start': self.cold_start, 'cold_start_lr': self.cold_start_lr, 'cold_start_duration': self.cold_start_duration, 'from_prototxt': str(self.from_prototxt)}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def json(self) -> Dict[str, Union[List, Dict, str, int, float]]:", "def asdict():\n pass", "def dict(self):\n\t\treturn self.json", "def to_json(self) -> Dict[str, Any]:\n return self.__dict__", "def to_dict(self) -> dict:", "def to_obj(self):\n return dict()", "def _as_dict(self):...
[ "0.8122776", "0.8008097", "0.79259527", "0.7621561", "0.7570507", "0.7563755", "0.7456708", "0.73646736", "0.7295484", "0.72896343", "0.72842276", "0.7273497", "0.72578883", "0.7255007", "0.7255007", "0.72454506", "0.7242269", "0.72290695", "0.72273296", "0.7204922", "0.71749...
0.0
-1
Load parameters from dictionary.
def from_dict(cls, dictionary: Dict[str, Any]): return cls(**dictionary)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _load(self, load_dict):\n if self.v_locked:\n raise pex.ParameterLockedException(\n \"Parameter `%s` is locked!\" % self.v_full_name\n )\n\n if \"data\" in load_dict:\n self._data = load_dict[\"data\"][\"data\"][0]\n self._default = self....
[ "0.72479516", "0.7205833", "0.69779885", "0.69117165", "0.68091863", "0.67698336", "0.67271155", "0.66972244", "0.66640526", "0.65984803", "0.6589829", "0.65780336", "0.65641016", "0.6548739", "0.6544162", "0.6452717", "0.6443524", "0.642245", "0.6406009", "0.63931835", "0.63...
0.56534404
98
Construct solver from Caffe solver prototxt file.
def from_caffe_solver_protoxt(cls, caffe_solver_prototxt_file: Path): solver_param = caffe_pb2.SolverParameter() with open(caffe_solver_prototxt_file, 'rt') as f: pb2.text_format.Merge(f.read(), solver_param) dictionary = {'lr_policy': solver_param.lr_policy, 'base_lr': solver_param.base_lr, 'gamma': solver_param.gamma, 'momentum': solver_param.momentum, 'max_iter': solver_param.max_iter, 'stepsize': solver_param.stepsize, 'stepvalues': solver_param.stepvalue, 'weight_decay': solver_param.weight_decay, 'iter_size': solver_param.iter_size, 'from_prototxt': caffe_solver_prototxt_file} return cls(**dictionary)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_solver(self):\n # Create a temporary solver file.\n fname = '__solver__.prototxt'\n f = open(fname, 'w')\n f.write(self.to_proto())\n f.close()\n # Get solver from file.\n solver = caffe.get_solver_from_file(fname)\n # Remove the temporary solver file...
[ "0.6062727", "0.5984447", "0.5803342", "0.57631385", "0.55716205", "0.5436299", "0.54261035", "0.53917223", "0.532022", "0.52781713", "0.52740806", "0.52685714", "0.52685714", "0.5249456", "0.5244701", "0.52160436", "0.51900196", "0.5182835", "0.5182635", "0.5168049", "0.5160...
0.78207666
0
Refreshes the Job's details by querying the workspace.
def refresh(self): self.details = self.workspace.get_job(self.id).details
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def refresh(self): # noqa\n data = self.connection.hgetall(self.key)\n if not data:\n raise NoSuchJobError('No such job: {0}'.format(self.key))\n self.restore(data)", "def reload(self):\n self.job_proto = self.serving_stub.GetJob(GetJobRequest(job=self.job_proto)).job", ...
[ "0.7204651", "0.6387912", "0.5996785", "0.5930605", "0.58091706", "0.5802573", "0.5802573", "0.5802573", "0.5802573", "0.5802385", "0.57152075", "0.5710763", "0.5668991", "0.5663364", "0.56334144", "0.5627976", "0.5627976", "0.5627976", "0.56269634", "0.56071436", "0.56027734...
0.80415493
0
Keeps refreshing the Job's details until it reaches a finished status.
def wait_until_completed(self, max_poll_wait_secs=30): self.refresh() poll_wait = 0.2 while not self.has_completed(): logger.debug( f"Waiting for job {self.id}," + f"it is in status '{self.details.status}'" ) print(".", end="", flush=True) time.sleep(poll_wait) self.refresh() poll_wait = ( max_poll_wait_secs if poll_wait >= max_poll_wait_secs else poll_wait * 1.5 )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def refresh(self):\n self.details = self.workspace.get_job(self.id).details", "def wait(self):\r\n self.jobs.join()", "def jobComplete(self):\n self._Finished = True\n return", "def wait_till_jobs_complete(self, collection_name: str, job_id: str, job_name: str):\n status = ...
[ "0.7560717", "0.6975098", "0.69365853", "0.68282324", "0.6777694", "0.6736639", "0.6731939", "0.6727907", "0.6715797", "0.6674043", "0.6674043", "0.6674043", "0.6674043", "0.66640437", "0.6595647", "0.65691817", "0.6568777", "0.6568164", "0.65348256", "0.6516131", "0.6487494"...
0.61918545
41
Checks if job (self) matches the given properties if any.
def matches_filter( self, name_match: str = None, status: Optional[JobStatus] = None, created_after: Optional[datetime] = None ) -> bool: if name_match is not None and re.search(name_match, self.details.name) is None: return False if status is not None and self.details.status != status.value: return False if created_after is not None: # if supplied date is date we must convert to datetime first if type(created_after) is date: created_after = datetime(created_after.year, created_after.month, created_after.day) # if supplied date is naive, assume local and convert to timezone aware object if created_after.tzinfo is None: created_after = created_after.astimezone() if self.details.creation_time.replace(tzinfo=timezone.utc) < created_after: return False return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def matchesProperties(self, *args):\n return _libsbml.SBMLRuleConverter_matchesProperties(self, *args)", "def matchesProperties(self, *args):\n return _libsbml.SBMLConverter_matchesProperties(self, *args)", "def _matchcondition_holds(self, matchconditions, src_sheet):\n matches=True\n ...
[ "0.5983222", "0.5968996", "0.5967254", "0.5961163", "0.5783931", "0.5742514", "0.56300825", "0.5572125", "0.55432945", "0.55259526", "0.55190766", "0.5497851", "0.5486585", "0.5448529", "0.5427197", "0.5398042", "0.53733146", "0.5355467", "0.5347236", "0.5345044", "0.53402734...
0.47501066
99
Create a unique id for a new job.
def create_job_id() -> str: return str(uuid.uuid1())
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _generate_job_id():\n # CAIP job id can contains only numbers, letters and underscores.\n unique_tag = str(uuid.uuid4()).replace(\"-\", \"_\")\n return \"tf_cloud_train_{}\".format(unique_tag)", "def _get_job_id(self):\n return uuid.uuid4().hex", "def create_task_id():\n return str(int(round...
[ "0.7751475", "0.7743574", "0.74370795", "0.73037905", "0.7232655", "0.7232655", "0.6982425", "0.6982323", "0.6908271", "0.6889731", "0.68492854", "0.67642814", "0.6763294", "0.6702419", "0.6602108", "0.65147835", "0.65133655", "0.65115803", "0.6507985", "0.64827", "0.6455972"...
0.88138694
0
Runs the supplied runners sequentially.
def run( runners, data_loader=None, warm_up=None, use_subprocess=None, subprocess_timeout=None, subprocess_polling_interval=None, save_inputs_path=None, ): warm_up = util.default(warm_up, 0) data_loader = util.default(data_loader, DataLoader()) use_subprocess = util.default(use_subprocess, False) subprocess_polling_interval = util.default(subprocess_polling_interval, 30) loader_cache = DataLoaderCache(data_loader, save_inputs_path=save_inputs_path) def execute_runner(runner, loader_cache): with runner as active_runner: # DataLoaderCache will ensure that the feed_dict does not contain any extra entries # based on the provided input_metadata. loader_cache.set_input_metadata(active_runner.get_input_metadata()) if warm_up: G_LOGGER.start(f"{active_runner.name:35} | Running {warm_up} warm-up run(s)") try: feed_dict = loader_cache[0] except IndexError: G_LOGGER.warning( f"{warm_up} warm-up run(s) were requested, but data loader did not supply any data. Skipping warm-up run(s)" ) else: G_LOGGER.ultra_verbose(f"Warm-up Input Buffers:\n{util.indent_block(feed_dict)}") # First do a few warm-up runs, and don't time them. for _ in range(warm_up): active_runner.infer(feed_dict=feed_dict) G_LOGGER.finish(f"{active_runner.name:35} | Finished {warm_up} warm-up run(s)") # Then, actual iterations. index = 0 iteration_results = [] total_runtime = 0 for index, feed_dict in enumerate(loader_cache): G_LOGGER.info( f"{active_runner.name:35}\n---- Inference Input(s) ----\n{TensorMetadata().from_feed_dict(feed_dict)}", mode=LogMode.ONCE, ) G_LOGGER.extra_verbose( lambda: f"{active_runner.name:35} | Feeding inputs:\n{util.indent_block(dict(feed_dict))}" ) outputs = active_runner.infer(feed_dict=feed_dict) runtime = active_runner.last_inference_time() total_runtime += runtime # Without a deep copy here, outputs will always reference the output of the last run iteration_results.append( IterationResult(outputs=copy.deepcopy(outputs), runtime=runtime, runner_name=active_runner.name) ) G_LOGGER.info( f"{active_runner.name:35}\n---- Inference Output(s) ----\n{TensorMetadata().from_feed_dict(outputs)}", mode=LogMode.ONCE, ) G_LOGGER.extra_verbose( lambda: f"{active_runner.name:35} | Inference Time: {runtime * 1000.0:.3f} ms | Received outputs:\n{util.indent_block(dict(outputs))}" ) total_runtime_ms = total_runtime * 1000.0 G_LOGGER.finish( f"{active_runner.name:35} | Completed {index + 1} iteration(s) in {total_runtime_ms:.4g} ms | Average inference time: {total_runtime_ms / float(index + 1):.4g} ms." ) return iteration_results # Wraps execute_runner to use a queue. def execute_runner_with_queue(runner_queue, runner, loader_cache): iteration_results = None try: iteration_results = execute_runner(runner, loader_cache) except: # Cannot necessarily send the exception back over the queue. G_LOGGER.backrace() util.try_send_on_queue(runner_queue, iteration_results) # After finishing, send the updated loader_cache back. util.try_send_on_queue(runner_queue, loader_cache) # Do all inferences in one loop, then comparisons at a later stage. # We run each runner in a separate process so that we can provide exclusive GPU access for each runner. run_results = RunResults() if not runners: G_LOGGER.warning( "No runners were provided to Comparator.run(). Inference will not be run, and run results will be empty." ) for runner in runners: G_LOGGER.start(f"{runner.name:35} | Activating and starting inference") if use_subprocess: runner_queue = Queue() process = Process(target=execute_runner_with_queue, args=(runner_queue, runner, loader_cache)) process.start() # If a subprocess hangs in a certain way, then process.join could block forever. Hence, # we need to keep polling the process to make sure it really is alive. iteration_results = None while process.is_alive() and iteration_results is None: try: iteration_results = util.try_receive_on_queue( runner_queue, timeout=subprocess_polling_interval / 2 ) # Receive updated loader cache, or fall back if it could not be sent. loader_cache = util.try_receive_on_queue(runner_queue, timeout=subprocess_polling_interval / 2) except queue.Empty: G_LOGGER.extra_verbose("Polled subprocess - still running") try: assert iteration_results is not None run_results.append((runner.name, iteration_results)) process.join(subprocess_timeout) except: G_LOGGER.critical( f"{runner.name:35} | Terminated prematurely. Check the exception logged above. If there is no exception logged above, make sure not to use the --use-subprocess flag or set use_subprocess=False in Comparator.run()." ) finally: process.terminate() if loader_cache is None: G_LOGGER.critical( "Could not send data loader cache to runner subprocess. Please try disabling subprocesses " "by removing the --use-subprocess flag, or setting use_subprocess=False in Comparator.run()" ) else: run_results.append((runner.name, execute_runner(runner, loader_cache))) G_LOGGER.verbose(f"Successfully ran: {[r.name for r in runners]}") return run_results
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run_test_suites(self, suites):\n for suite_class in suites:\n test_suite = suite_class(self)\n results = test_suite.run()\n self.test_results += results", "def test_serial_runs(make_runner: Callable[..., TargetFunctionRunner]) -> None:\n runner = make_runner(target_...
[ "0.6145495", "0.60319495", "0.59287375", "0.5832656", "0.5831884", "0.5669822", "0.5645586", "0.56302845", "0.5623436", "0.5600219", "0.5553108", "0.55371404", "0.55194783", "0.55185175", "0.55181295", "0.55050325", "0.5497241", "0.54962456", "0.54926574", "0.5487635", "0.548...
0.56467295
6
Applies post processing to all the outputs in the provided run results. This is a convenience function to avoid the need for manual iteration over the run_results dictionary.
def postprocess(run_results, postprocess_func): G_LOGGER.start(f"Applying post-processing to outputs: {postprocess_func.__name__}") for _, iteration_results in run_results: for index, iter_res in enumerate(iteration_results): iteration_results[index] = postprocess_func(iter_res) G_LOGGER.finish("Finished applying post-processing") return run_results
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def process(self, results):\n raise NotImplementedError", "def process_results(self, results=None, **value): # pragma: no cover\n return default_result_processor(results=results, **value)", "def _post_process_result(result: Any) -> Any:\n return result", "def process_results(self, respo...
[ "0.65581095", "0.64528775", "0.62099826", "0.61681396", "0.61681396", "0.6150747", "0.61191654", "0.6098182", "0.6078971", "0.60327035", "0.6017863", "0.60096914", "0.59998536", "0.59641546", "0.5962654", "0.593701", "0.5910838", "0.5900604", "0.5772284", "0.5731572", "0.5715...
0.8450894
0
Turns Freshbooks tickets from the past x days into Toggl projects.
def sync(self, no_of_days=1): zd = Zendesk() tg = Toggl() try: self.print("Syncing...") self.print_divider(30) tickets = zd.get_tickets(no_of_days) for ticket in tickets: project_title = self.format_title(ticket.id, ticket.subject) if ticket.organization: client_id = tg.get_client_id(name=ticket.organization.name) if not client_id: new_client = tg.create_client(ticket.organization.name) client_id = new_client['id'] else: client_id = False self.print("Ticket '%s' has no associated organization!" % (project_title)) all_projects = tg.get_projects() if not self.already_created(ticket.id, all_projects): self.print("Creating project '%s'..." % (project_title)) result = tg.create_project(project_title, client_id, is_private=False) self.print("Toggl response:") self.log(result, silent=False) else: self.print("There is already a Toggl project for Zendesk ticket #%s!" % ticket.id) pass # TODO: edit Toggl project # tg.edit_project(project_id, name=ticket.subject) self.print_divider(30) self.print("Done!") except: self.log(traceback.format_exc(), silent=False)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def resume():\n # We now retrieve all entries in the previous month.\n # Getting the current date and the date from a month before.\n time_year = time.localtime()[0] \n time_month = time.localtime()[1]\n time_day = time.localtime()[2]\n if time_month == 1:\n prev_time_month = 12\n p...
[ "0.5335107", "0.52704185", "0.5256979", "0.5130906", "0.50964624", "0.5023923", "0.5006047", "0.49849492", "0.4897661", "0.4888886", "0.4882372", "0.486753", "0.4858375", "0.48496896", "0.4849528", "0.48321384", "0.48075008", "0.47820213", "0.47624293", "0.4758167", "0.475298...
0.58926123
0
Starts interactive time tracking session. Updates Freshbooks based on Toggl entries.
def time_tracking(self): fb = FreshBooks() tg = Toggl() self.print_splash() self.print("Tip: You can always enter 'skip' when you want to skip a time entry.", format='warn') days = self.get_interactive_days() # number of days to go back self.print("OK, I'll run you through the Toggl time entries of the past %i day(s)." % (days)) timestamp = self.get_timestamp(days) # unix timestamp including tz time_entries = tg.get_time_entries(timestamp) if len(time_entries) == 0: self.print("No Toggl entries in this time span!", 'warn') return False time_entries = self.merge_toggl_time_entries(time_entries) # merge Toggl entries fb_projects = fb.get_projects() # Loop through merged Toggl time entries: for entry in time_entries: # Get and convert all necessary info: client_id = tg.get_client_id(project_id=entry.get('pid')) client_name = tg.get_client_name(client_id) project = tg.get_project(entry.get('pid')) duration = int(entry['duration']) / 60 / 60 # convert duration to hours duration = round(duration * 4 ) / 4 # round hours to nearest .25 description = self.format_description(project['name'], entry['description']) date = str(parser.parse(entry['start']).date()) # Print info in a nice way: self.print_divider(30) self.print("Description: " + description) self.print("Date: " + date) self.print("Hours spent: " + str(duration)) # Skip if Toggl entry is already booked: if entry.get('tags') and tg.BOOKED_TAG in entry['tags']: self.print("Skipping this entry because it is already in Freshbooks.", 'cross') # Skip if duration is below 0.25: elif duration < 0.25: self.print("Skipping this entry because there are less than 0.25 hours spent.", 'cross') # If billable, add to Freshbooks: elif entry['billable']: # Get FreshBooks project name through interactive search: try: self.print("Project: \U0001F50D ") fb_project_name = self.interactive_search(fb_projects.keys(), client_name) # Handle KeyboardInterrupt except KeyboardInterrupt: answer = input("\nKeyboardInterrupt! Skip current entry or quit time tracking? (S/q) ") if answer.lower() == 's' or answer == '': self.clear_lines(1) self.print("Skipping this entry.", 'cross') continue else: self.clear_lines(1) self.print("Ok, stopping time tracking.", 'cross') sys.exit() # If user requests so, skip this entry: self.clear_lines(1) if not fb_project_name: self.print("Skipping this entry.", 'cross') continue # Otherwise, add entry to FreshBooks and tag Toggl entry/entries: self.print("Project: " + fb_project_name) project_id = fb.get_project_id(fb_project_name) fb.add_entry(project_id, duration, description, date) tg.tag_projects(entry['merged_ids'], tg.BOOKED_TAG) # If not billable, skip entry: else: self.print("Skipping this entry because it is not billable.", 'cross') self.print_divider(30) answer = input("All done! Open FreshBooks in browser to verify? (Y/n) ") if answer.lower() == 'y' or answer == '': webbrowser.open('https://%s.freshbooks.com/timesheet' % fb.fb_creds['subdomain'])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n\n # check database for tracking options\n # if empty prompt to add subject\n\n # present tracking options\n\n # calculate timedelta\n\n # printing/updating the time", "def setTrackStartTime() :\n s.startTrack()", "def time_automation_listener(now):\n action()", "def mai...
[ "0.6347523", "0.576873", "0.5634519", "0.56242204", "0.56151354", "0.5609387", "0.56086725", "0.55940264", "0.5576316", "0.5486407", "0.54707676", "0.5469594", "0.5462939", "0.54449016", "0.5444178", "0.5436368", "0.54061335", "0.53546655", "0.53450114", "0.5342797", "0.53191...
0.69116616
0
Starts interactive search, allows user to make a selection. Accepts array of strings and optional (user) query. Returns string chosen by user.
def interactive_search(self, choices, query=None): if query: match = self.get_interactive_match(choices, query) if match: self.print("Matched query to '%s'." % (match)) answer = input("Is that correct? (Y/n) ") self.clear_lines(1) if answer.lower() == 'y' or answer == '': self.clear_lines(1) return match else: self.clear_lines(1) return self.interactive_search(choices) else: return None else: query = input("Please type a query: ") self.clear_lines(1) return self.interactive_search(choices, query)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __ask_query(self):\n self.__output = list()\n return input(form('What do you want to search?\\n> '))", "def search():\n query = input('Please enter your search query\\n')\n # For now, we will just print the whole database\n #db_actions.display()\n db_actions.search(query)", "def ...
[ "0.6945267", "0.6146135", "0.60944784", "0.6077637", "0.6019907", "0.5902816", "0.58127916", "0.58041674", "0.5797001", "0.5792282", "0.5770086", "0.5716065", "0.56671447", "0.5661047", "0.5658922", "0.56546295", "0.56507295", "0.5648148", "0.56405544", "0.56253314", "0.56142...
0.67623794
1
Returns string that best matches query out of a list of choices. Prompts user if unsure about best match.
def get_interactive_match(self, choices, query): if query in self.SKIP_KEYWORDS: return None results = process.extract(query, choices, limit=10) # fuzzy string matching best_match = results[0] second_best_match = results[1] if best_match[1] == second_best_match[1] or best_match[1] < 50: # if inconclusive or low score self.print("Couldn't find a conclusive match for '%s'. Best matches:" % (query)) i = 0 for result in results: i += 1 print(" [%i] %s" % (i, result[0])) answer = input("Choose one or specify a less ambiguous query: ") self.clear_lines(2 + len(results)) if answer.isdigit() and int(answer) <= len(results): return results[int(answer) - 1][0] else: return self.get_interactive_match(choices, answer) else: return best_match[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def interactive_search(self, choices, query=None):\n if query:\n match = self.get_interactive_match(choices, query)\n if match:\n self.print(\"Matched query to '%s'.\" % (match))\n answer = input(\"Is that correct? (Y/n) \")\n self.clear_lin...
[ "0.6642002", "0.6545624", "0.6269913", "0.623575", "0.6235035", "0.62169236", "0.6010412", "0.60037553", "0.6000231", "0.59865594", "0.5913682", "0.59093326", "0.5877843", "0.5836029", "0.5736314", "0.57017106", "0.5665372", "0.56378025", "0.5632232", "0.5620297", "0.55832994...
0.7756389
0
Asks an user how many days to go back. Returns int.
def get_interactive_days(self): answer = input("Press return to get entries of past day or input number of days to go back in time: ") if answer == '': days = 1 else: try: days = int(answer) except: print("You didn't enter a number, assuming 1 day.") days = 1 return days
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def decreases_remaining(self):\n return 2 - self.decreases_today", "def remain():\r\n global total\r\n global user_pick\r\n total = int(total - user_pick)\r\n print(\"Remaining \" + str(total))", "def remaining_days_in_cycle(self) -> int:\n if not self.expiration:\n return ...
[ "0.6136943", "0.59328794", "0.5877445", "0.58612114", "0.57502425", "0.5743318", "0.55419844", "0.55365306", "0.55009514", "0.5493947", "0.54851043", "0.5480768", "0.5478333", "0.54070824", "0.5393414", "0.53924155", "0.5386575", "0.5374631", "0.52890193", "0.52890193", "0.52...
0.70395863
0
Hacky way to check if this function already made a Toggl project based on a Zendesk ticket ID.
def already_created(self, ticket_id, toggl_projects): project_prepends = [p['name'].split()[0][1:] for p in toggl_projects] if str(ticket_id) in project_prepends: return True return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def check_if_is_ticket(ctx):\n channel : TextChannel = ctx.channel\n return 'ticket-' in channel.name", "def sync(self, no_of_days=1):\n zd = Zendesk()\n tg = Toggl()\n try:\n self.print(\"Syncing...\")\n self.print_divider(30)\n tickets =...
[ "0.60784185", "0.584883", "0.56591004", "0.55432487", "0.5472561", "0.5453476", "0.5446431", "0.54430735", "0.54305506", "0.54244524", "0.54243267", "0.5412555", "0.53918374", "0.5391034", "0.5389106", "0.5382748", "0.53724587", "0.53702873", "0.535847", "0.5357751", "0.53424...
0.7632334
0
Formats id and subject into a suitable (Freshbooks) title.
def format_title(self, ticket_id, subject): # TODO: strip block tags? title = "#%i %s" % (ticket_id, subject) return title.strip()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _make_title(self):\n ret = self.properties['reason'].capitalize()\n ret += ' has been reported near ' + self.properties['address'].split(',')[0]\n time = datetime.strptime(self.properties['when'], '%Y-%m-%dT%H:%M:%S')\n times = [time.strftime(i).lstrip('0') for i in ('%m', '%d', '%I...
[ "0.63595736", "0.6318129", "0.6200423", "0.61921966", "0.6153127", "0.60798085", "0.6040445", "0.6013723", "0.6009649", "0.59691554", "0.59691554", "0.5925276", "0.58930725", "0.5861564", "0.5843622", "0.5807595", "0.57983005", "0.57983005", "0.5792964", "0.57914525", "0.5784...
0.78905237
0
Formats Toggl project name and description into (Freshbooks) description.
def format_description(self, project_name, description): description = description if description else '' return "%s %s" % (project_name, '- ' + description)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def description():", "def get_descriptive_name(self):\n description = (f\"{self.year} {self.manufacturer.title()} \"\n f\"{self.model.title()}\")\n\n return description", "def get_describe_name(self):\n long_name = str(self.year)+ ' ' + self.make.title()+ ' ' +self.mo...
[ "0.6330707", "0.5992437", "0.59294826", "0.59286237", "0.58890724", "0.584214", "0.5832703", "0.5818409", "0.5808963", "0.5762168", "0.5734125", "0.5720652", "0.5715829", "0.5715829", "0.56770307", "0.5670249", "0.56625277", "0.5661302", "0.56451756", "0.5631556", "0.5621286"...
0.7948996
0
Merges toggle time entries with same project name. Sums duration if billable.
def merge_toggl_time_entries(self, time_entries): tg = Toggl() d = {} for entry in time_entries: if entry.get('billable'): if entry.get('tags') and tg.BOOKED_TAG in entry['tags']: status = 'booked' else: status = 'not-booked' date = parser.parse(entry['start']).date() if not entry.get('pid'): self.log("Couldn't find associated project for entry: %s" % (str(entry))) continue unique_id = str(entry['pid']) + str(date) + status if not entry.get('description'): entry['description'] = "" if d.get(unique_id): d[unique_id]['duration'] += entry['duration'] d[unique_id]['merged_ids'].append(entry['id']) if d[unique_id].get('description'): if entry['description'].strip() not in d[unique_id]['description']: d[unique_id]['description'] += ' / ' + entry['description'] else: d[unique_id]['description'] = entry['description'] else: entry['merged_ids'] = [entry['id']] d[unique_id] = entry return d.values()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def break_time(self):\n\t\ts = timedelta()\n\t\tfor i in xrange(1, len(self.toggles)-1, 2):\n\t\t\ts += self.toggles[i+1] - self.toggles[i]\n\n\t\t# If not working need to add the last period of time\n\t\tif not self.status():\n\t\t\ts += datetime.now() - self.toggles[-1]\n\t\treturn s", "def _task_data(self):\n...
[ "0.52670914", "0.521612", "0.5171499", "0.49770486", "0.49408284", "0.49355707", "0.47276974", "0.47106627", "0.4675955", "0.4652707", "0.46401706", "0.46156195", "0.45833963", "0.4529443", "0.45191568", "0.44983798", "0.44943383", "0.4493547", "0.4472287", "0.44453704", "0.4...
0.6820048
0
Returns isoformat string of beginning of past x day(s). Assumes Europe/Amsterdam locale.
def get_timestamp(self, days=1): offset = datetime.datetime.utcnow().date() - datetime.timedelta(days=days-1) # est = tz.gettz('Europe/Amsterdam') # temporary dirty fix for timezone: timezone = '+02:00' start = datetime.datetime(offset.year, offset.month, offset.day) return start.isoformat() + timezone
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_past_date(self, days):\n past_date = datetime.now() - timedelta(days=days)\n return past_date.isoformat()", "def xlDateISO(xdate):\n # QuantLib doesn't support dates prior to 1901\n # which saves us from dealing with the leap year problem\n if xdate < 367:\n return \"#Dat...
[ "0.58592373", "0.57152444", "0.57139474", "0.55301887", "0.5470207", "0.5442907", "0.5421798", "0.54160655", "0.53812414", "0.53812414", "0.5367235", "0.5362113", "0.5331076", "0.5325458", "0.5298497", "0.5294768", "0.5270717", "0.5265063", "0.52353704", "0.5232425", "0.52232...
0.5205546
22
Private utility to get routes from an extended class
def __get_parent_routes(self, router: APIRouter): for route in router.routes: options = {key: getattr(route, key) for key in __router_params__} # inherits child tags if presents if len(options["tags"]) == 0 and self.openapi_tag: options["tags"].append(self.openapi_tag["name"]) self.router.add_api_route(route.path, route.endpoint, **options)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getRoutes(self):\n pass", "def get_routes(self):\n return [\n (route, handler.handler_class, handler.init_kwargs)\n for route, handler in self._routes.iteritems()\n ]", "def get_routes():\n return sum([load_module(m).ROUTES for m in settings.INSTALLED_HANDLERS], []) + ROUTES", "...
[ "0.7202516", "0.67574275", "0.6573126", "0.6540048", "0.62880886", "0.62165105", "0.6130403", "0.6115117", "0.6013663", "0.60105985", "0.5981652", "0.59521013", "0.593293", "0.59178156", "0.59062076", "0.58861256", "0.5860622", "0.57698715", "0.57652", "0.5759567", "0.5740232...
0.5733189
21
Mark a class as Controller Resource
def add_resource(self, cls): # check if the same controller was already used for another cls (Resource) if ( hasattr(self, Controller.RESOURCE_CLASS_KEY) and getattr(self, Controller.RESOURCE_CLASS_KEY) != cls ): raise MultipleResourceException() # check if cls (Resource) was exteded from another if hasattr(cls, Controller.RC_KEY): self.__get_parent_routes(cls.__router__) setattr(cls, Controller.RC_KEY, self.router) setattr(self, Controller.RESOURCE_CLASS_KEY, cls) cls.router = lambda: Controller.__parse_controller_router(cls) return cls
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_resource():\n return wsgi.Resource(Controller())", "def setController(self, controller):\n self.__controller = controller", "def __init__(self, controller):\n self._controller = controller", "def resource(self, prefix):\n def wrapper(cls):\n # Save the original i...
[ "0.6103949", "0.6056706", "0.59474033", "0.5917977", "0.58889747", "0.58889747", "0.5795911", "0.5779954", "0.57289934", "0.5706962", "0.5686955", "0.5658022", "0.55966556", "0.55881155", "0.5557832", "0.55321854", "0.5516671", "0.55104506", "0.5504374", "0.5495111", "0.54755...
0.6852721
0
A decorator function to mark a Class as a Controller
def resource(self): return self.add_resource
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def use(_):\n\n def wrapper(cls):\n __app_controllers__.append(cls)\n return cls\n\n return wrapper", "def create_controller() -> Controller:\n _controller = Controller()\n return _controller", "def controller(code):\n\n def register_controller(func):\n CONTR...
[ "0.65690434", "0.6126933", "0.5997419", "0.5680925", "0.5661249", "0.5657938", "0.5650889", "0.5638046", "0.55720645", "0.55620176", "0.5495032", "0.54726076", "0.547135", "0.54366666", "0.5421368", "0.54175097", "0.5387649", "0.5378564", "0.52877134", "0.5242758", "0.5221134...
0.0
-1
A decorator function to mark a Class to be automatically loaded by the Controller
def use(_): def wrapper(cls): __app_controllers__.append(cls) return cls return wrapper
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def register(cls, D: DONLOADER_CLASS) -> DONLOADER_CLASS:\r\n ...", "def identify_class(self, cls):", "def register(cls, class_to_register):\n cls.registered_loaders.append(class_to_register)\n return class_to_register", "def register(cls):\n register(cls, cls.provided_class)", ...
[ "0.6117717", "0.6076721", "0.6028413", "0.59642714", "0.5934709", "0.5934709", "0.5899243", "0.5899243", "0.58098847", "0.5786942", "0.57629675", "0.57629675", "0.573222", "0.56865835", "0.5675948", "0.56697935", "0.56556857", "0.5631191", "0.56014067", "0.56014067", "0.55763...
0.5904735
6
Private utility to parse the router controller property and extract the correct functions handlers
def __parse_controller_router(cls): router = getattr(cls, Controller.RC_KEY) dependencies = None if hasattr(cls, "dependencies"): dependencies = deepcopy(cls.dependencies) delattr(cls, "dependencies") for route in router.routes: # add class dependencies if dependencies: for depends in dependencies[::-1]: route.dependencies.insert(0, depends) # get the signature of the endpoint function signature = inspect.signature(route.endpoint) # get the parameters of the endpoint function signature_parameters = list(signature.parameters.values()) # replace the class instance with the itself FastApi Dependecy signature_parameters[0] = signature_parameters[0].replace( default=Depends(cls) ) # set self and after it the keyword args new_parameters = [signature_parameters[0]] + [ parameter.replace(kind=inspect.Parameter.KEYWORD_ONLY) for parameter in signature_parameters[1:] ] new_signature = signature.replace(parameters=new_parameters) setattr(route.endpoint, Controller.SIGNATURE_KEY, new_signature) return router
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_handlers():\n handlers = list()\n\n #login\n handlers.append((r'/login', Login))\n handlers.append((r'/logout', Logout))\n\n # main\n handlers.append((r'/', Index))\n\n\n #user\n handlers.extend(get_routes(UserController))\n\n #role\n handlers.extend(get_routes(RoleController)...
[ "0.5602386", "0.5543036", "0.5451026", "0.53584725", "0.5357934", "0.5338533", "0.5338533", "0.52820855", "0.5260781", "0.5229428", "0.5228598", "0.52258754", "0.520842", "0.50448126", "0.50413436", "0.49797627", "0.495311", "0.49384397", "0.49170753", "0.49129686", "0.490438...
0.5382797
3
It returns all the Classes marked to be used by the "use" decorator
def routers(): routers = [] for app_controller in __app_controllers__: routers.append(app_controller.router()) return routers
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def classes(self):\n if self.classname:\n return [self.classname]\n return []", "def get_classes(self):\n return", "def return_classes(self):\n\n\t\t \n\t\t \n\t\treturn self.classes", "def classes(self):\n raise NotImplementedError(\"Please implement this yourself....
[ "0.73976636", "0.7189597", "0.7136581", "0.7131603", "0.6812443", "0.6812443", "0.6812443", "0.6812443", "0.6812443", "0.6812443", "0.67753637", "0.676244", "0.67491084", "0.6672196", "0.66617703", "0.6578411", "0.6575741", "0.6558602", "0.6541815", "0.6495872", "0.6475694", ...
0.0
-1
It returns the FastAPI router. Use it as if you are using the original one.
def route(self) -> APIRouter: return self.router
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __call__(self, req):\n return self._router", "def create_router(self, environment, *, router=None):\n\n if router is None:\n router = self.router\n\n return utils.objects.ensure_instance(router, environment=environment)", "def __parse_controller_router(cls):\n router ...
[ "0.75668126", "0.62573475", "0.6220323", "0.61085886", "0.6030978", "0.602395", "0.60006815", "0.59523207", "0.5933353", "0.58949184", "0.5879139", "0.5846796", "0.5825418", "0.5804262", "0.57789963", "0.5770383", "0.5753781", "0.57239616", "0.56978655", "0.5636582", "0.56365...
0.81418586
0
Checks if two shards overlap.
def _check_shard_metadata_pair_overlap(shard1: ShardMetadata, shard2: ShardMetadata): # For each dim of each shard, check if one shard resides on the other # end of second shard with respect to that dim. As an example for a 2D # shard, we would check if one shard is above or on the left of the # other shard. ndims = len(shard1.shard_offsets) for i in range(ndims): if shard1.shard_offsets[i] >= shard2.shard_offsets[i] + shard2.shard_lengths[i]: return False if shard2.shard_offsets[i] >= shard1.shard_offsets[i] + shard1.shard_lengths[i]: return False return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def can_overlap(self):\n return False", "def overlaps(self, other): # -> bool:\n ...", "def check_overlap(a, b):\n if a[0] >= b[2] or a[1] >= b[3] or a[2] <= b[0] or a[3] <= b[1]:\n return False\n return True", "def span_overlap(a: Tuple[int, int], b: Tuple[int, int]) -> bool:\n ...
[ "0.72638744", "0.7062225", "0.7060286", "0.69966316", "0.6907729", "0.68349934", "0.6770295", "0.6767552", "0.67658687", "0.6728309", "0.66423035", "0.6638168", "0.66367257", "0.6632385", "0.66321814", "0.6605467", "0.6596014", "0.65437245", "0.65411097", "0.6536112", "0.6519...
0.7538921
0
Ensures none of the shards overlap with each other.
def validate_non_overlapping_shards_metadata(shards: List[ShardMetadata]): # TODO: evaluate optimizing this if needed. for i in range(len(shards)): for j in range(i + 1, len(shards)): if _check_shard_metadata_pair_overlap(shards[i], shards[j]): raise ValueError(f'Shards {shards[i]} and {shards[j]} overlap')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def can_overlap(self):\n return False", "def _check_shard_metadata_pair_overlap(shard1: ShardMetadata, shard2: ShardMetadata):\n\n # For each dim of each shard, check if one shard resides on the other\n # end of second shard with respect to that dim. As an example for a 2D\n # shard, we would che...
[ "0.6780764", "0.66072226", "0.6300442", "0.62059945", "0.62039727", "0.618798", "0.6161772", "0.61248296", "0.60674876", "0.60540277", "0.59775466", "0.59660643", "0.5925951", "0.59135264", "0.58842605", "0.58602405", "0.5835803", "0.5722045", "0.5703409", "0.57028174", "0.56...
0.7294196
0
Checks if the shards_metadata is compatible with the provided tensor dims.
def check_tensor(shards_metadata, tensor_dims) -> None: # If the tensor's volume matches the total volume of all shards and # all shard boundaries are within tensor dims, we have a compatible # sharding spec for this tensor. Note that we have already verified # we don't have overlapping shards. tensor_rank = len(tensor_dims) shards_rank = len(shards_metadata[0].shard_offsets) if tensor_rank != shards_rank: raise ValueError(f'Rank of tensor is {tensor_rank}, but shards rank is {shards_rank}') total_shard_volume = 0 for shard in shards_metadata: shard_volume = 1 for i, shard_length in enumerate(shard.shard_lengths): shard_volume *= shard_length if shard.shard_offsets[i] + shard.shard_lengths[i] > tensor_dims[i]: raise ValueError( f'Shard offset {shard.shard_offsets[i]} and length ' f'{shard.shard_lengths[i]} exceeds tensor dim: {tensor_dims[i]} for shard {shard}') total_shard_volume += shard_volume tensor_volume = 1 for size in tensor_dims: tensor_volume *= size if total_shard_volume != tensor_volume: # TODO: Can we improve this error message to point out the gaps? raise ValueError( f'Total volume of shards: {total_shard_volume} ' f'does not match tensor volume: {tensor_volume}, in other words ' f'all the individual shards do not cover the entire tensor')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def has_dims(xobj, dims, kind):\n if isinstance(dims, str):\n dims = [dims]\n\n if not all(dim in xobj.dims for dim in dims):\n raise DimensionError(\n f'Your {kind} object must contain the '\n f'following dimensions at the minimum: {dims}'\n )\n return True", ...
[ "0.70428336", "0.6533978", "0.6469752", "0.6321749", "0.6268698", "0.6185657", "0.6185021", "0.605668", "0.5926702", "0.5918645", "0.5908207", "0.58480775", "0.57827824", "0.5772328", "0.5762425", "0.57193136", "0.57082486", "0.5685897", "0.5651482", "0.5640664", "0.562222", ...
0.83699447
0
Shorthand way to compose context, for maximum reuse.
def getContext(self, form): context = { 'form': form, 'projectList': self.projectList, 'subnav_location': self.subnav_location, 'curr_project': self.curr_project } return context
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_context(self, engine, args):\n args = self.normalize_args(args)\n _, ctx = self._make_argkey_and_context(engine, args)\n return ctx", "def __call__(self, **kwargs):\n return Context(self, kwargs)", "def _createContext(instance, args, kwargs, settings):\n context = kwargs...
[ "0.68892765", "0.6741356", "0.650719", "0.6487625", "0.647903", "0.64450336", "0.641441", "0.64143896", "0.63976085", "0.6372777", "0.63546556", "0.63230544", "0.6281274", "0.62207276", "0.6192012", "0.61908066", "0.61687595", "0.6161329", "0.6132779", "0.609645", "0.6085159"...
0.0
-1
The GET view method.
def get(self, request): context = self.getContext(GeoPostForm()) return render(request, 'geopost/home.html', context)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get(self, *args, **kwargs):\n return self._hit(\"GET\", *args, **kwargs)", "def get(self, *args, **kwargs):\n self.request(\"get\", *args, **kwargs)", "def get(self, *args, **kwargs):\n return self._request('get', *args, **kwargs)", "def get(self):\n self.get_or_post(method='G...
[ "0.8008264", "0.7953128", "0.79350144", "0.7772235", "0.7749338", "0.77399784", "0.77047", "0.7682195", "0.7652674", "0.7584354", "0.7562804", "0.7562804", "0.74978745", "0.74978745", "0.74978745", "0.74978745", "0.74978745", "0.7471668", "0.74600196", "0.745688", "0.7411558"...
0.0
-1
Render with blank form...
def get(self, request): context = self.getContext(GeoPostForm()) return render(request, 'geopost/entry.html', context)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def render_form():", "def render_form_content(self):\n return mark_safe(self.render_as_object() + self.render_missing_fields())", "def form():\n return render_template(\n 'form.html'\n )", "def render_form(self, title=\"\", body=\"\", error=\"\"):\n self.render(\"newpost.html\"...
[ "0.75872487", "0.67509174", "0.6683415", "0.663064", "0.651448", "0.6472087", "0.6457773", "0.63893735", "0.63662237", "0.6326461", "0.6302796", "0.6278228", "0.6275536", "0.6245083", "0.623302", "0.6206928", "0.617771", "0.61495304", "0.61495304", "0.6138811", "0.60955083", ...
0.0
-1
Process newly submitted GeoPost entry... PROCEEDURE 1) Get data from POST body 2) Validate form 3) Upload photo to bucket 4) Make WFS transaction with GeoServer
def post(self, request): # GET REQUEST DATA fid = request.POST.get('fid', False) uuid = request.POST.get('uuid', False) title_text = request.POST.get('title', False) body = request.POST.get('body', False) photo = request.FILES.get('photo', False) # FOR STORAGE wfsxml = request.POST.get('wfsxml', False) # FOR GEOSERVER data = { 'uuid': uuid, 'title_text': title_text, 'body': body, 'wfsxml': wfsxml } # VALIDATE FORM form = GeoPostForm(data, request.FILES) logger.info("\ninstantiate Geopost form\n") # IF FORM VALIDATION ERROR if not form.is_valid(): return server_error(request.body) #context = self.getContext(form) #return render(request, 'geopost/entry.html', context) else: pass # GET CLEAN VALUES uuid = form.cleaned_data['uuid'] wfsxml = form.cleaned_data['wfsxml'] # UPLOAD PHOTO TO BUCKET # if editing existing entry, first delete existing photo if fid: delete_from_bucket(uuid, self.imageBucket) else: pass photo.open('rb') error = upload_to_bucket( photo, self.imageBucket, photo.content_type, uuid) photo.close() # IF ERROR UPLOADING IMAGE if error: return server_error(error) else: pass # MAKE GEOSERVER WFS TRANSACTION error = post_to_geoserver(wfsxml, self.wfsURL) # ALL GOOD if not error: return HttpResponseRedirect(reverse('geopost_home')) # IF WFS TRANSACTION ERROR else: delete_from_bucket(uuid, self.imageBucket) return server_error(error)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def do_POST(self):\n global pages, devices, settings\n try:\n ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))\n if ctype == 'application/x-www-form-urlencoded':\n length = int(self.headers.getheader('content-length'))\n postv...
[ "0.6062715", "0.59630567", "0.58975375", "0.58711004", "0.5809544", "0.5728217", "0.5689963", "0.55832034", "0.5559245", "0.5515752", "0.54731184", "0.54603994", "0.54473406", "0.5440826", "0.5434373", "0.54309976", "0.5366671", "0.53177875", "0.5264689", "0.5257757", "0.5244...
0.8015848
0
Delete an entry and its associated photo. A workaround to AJAX.
def delete(request): wfsxml = request.POST.get('wfsxml', False) # FOR GEOSERVER uuid = request.POST.get('uuid', False) # MAKE GEOSERVER WFS TRANSACTION error = post_to_geoserver(wfsxml, GeoPostBase.wfsURL) # ALL GOOD if error: return server_error(error) # IF WFS TRANSACTION ERROR else: pass # Delete photo from bucket delete_from_bucket(uuid, GeoPostBase.imageBucket) return HttpResponseRedirect(reverse('geopost_home'))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def photo_delete(sender, instance, **kwargs):\n\tinstance.photo.delete(False)", "def picture_delete(request, pk):\n picture = get_object_or_404(Picture, pk=pk)\n\n if picture.author != request.user:\n data = {\n 'status': 'failed',\n 'details': 'Not allowed'\n }\n ...
[ "0.73588145", "0.70873886", "0.69900006", "0.69221896", "0.68318427", "0.68305916", "0.67875415", "0.67865944", "0.67163795", "0.6713444", "0.6629518", "0.65691507", "0.65677196", "0.6564613", "0.6494717", "0.64877266", "0.6412482", "0.6381852", "0.6367966", "0.6347049", "0.6...
0.6766004
8
The GeoPost view method for retrieving photos
def photo(request, entry_uuid): resp = HttpResponse() metadata, photo = download_from_bucket(entry_uuid, GeoPostBase.imageBucket) resp.write(base64.b64encode(photo)) resp['Content-Type'] = metadata['contentType'] return resp
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def feed(self, request, pk):\n photographer = Photographer.objects.get(id=pk)\n photo_feed = (Photo\n .objects\n .filter(Q(location__istartswith=photographer.location) |\n Q(uploaded_by__in=photographer.following.all()))\n ...
[ "0.6741567", "0.6559008", "0.6350902", "0.6310838", "0.62246984", "0.6191355", "0.618758", "0.618606", "0.6176454", "0.61532885", "0.61340106", "0.6112136", "0.61067706", "0.6101333", "0.6097831", "0.6021922", "0.6020295", "0.5962198", "0.5938344", "0.5936891", "0.59121317", ...
0.61628646
9
Download pdf of VanTechy presentation slideshow.
def vantechy(request): return FileResponse(open('/files/presentation.pdf', 'rb'))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fetch_pdf(url, browser):\n\tpass\n\n\t# grab link page\n\n\t# search soup for pdf file\n\n\t# grab pdf file and return it", "def download(filename):\n return send_from_directory(directory='pdf', filename=filename)", "def download(request, ef_id):\n ef = get_object_or_404(ExamFile, id=ef_id)\n path...
[ "0.63570714", "0.6327665", "0.6183838", "0.60757995", "0.6060038", "0.60584295", "0.6054394", "0.59414095", "0.586487", "0.5839018", "0.5790814", "0.57728595", "0.57418793", "0.57275844", "0.57084584", "0.56971765", "0.56889516", "0.5683005", "0.56304324", "0.5624967", "0.559...
0.658064
0
Records the hosts and connects to one of them
def setup( hosts, default_keyspace, consistency=ConsistencyLevel.ONE, lazy_connect=False, retry_connect=False, **kwargs): global cluster, session, default_consistency_level, lazy_connect_args if 'username' in kwargs or 'password' in kwargs: raise CQLEngineException("Username & Password are now handled by using the native driver's auth_provider") if not default_keyspace: raise UndefinedKeyspaceException() from cqlengine import models models.DEFAULT_KEYSPACE = default_keyspace default_consistency_level = consistency if lazy_connect: kwargs['default_keyspace'] = default_keyspace kwargs['consistency'] = consistency kwargs['lazy_connect'] = False kwargs['retry_connect'] = retry_connect lazy_connect_args = (hosts, kwargs) return cluster = Cluster(hosts, **kwargs) try: session = cluster.connect() except NoHostAvailable: if retry_connect: kwargs['default_keyspace'] = default_keyspace kwargs['consistency'] = consistency kwargs['lazy_connect'] = False kwargs['retry_connect'] = retry_connect lazy_connect_args = (hosts, kwargs) raise session.row_factory = dict_factory
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def establish_hosts(self):\n scheme = self._config['scheme']\n hosts = self._config['hosts']\n port = self._config['port']\n for hostname in hosts:\n url = '{}://{}:{}/gremlin'.format(scheme, hostname, port)\n host = await driver.GremlinServer.open(\n ...
[ "0.66659623", "0.6463537", "0.64295864", "0.63148797", "0.6137244", "0.5938947", "0.59179175", "0.59135944", "0.5890323", "0.58860373", "0.5849516", "0.5825648", "0.5824897", "0.5793935", "0.5786246", "0.57649606", "0.57589364", "0.57583195", "0.57563883", "0.5731571", "0.572...
0.0
-1
List all available charts
def list_charts(): charts_root = Path(R".\charm\data\charts") charts = list(charts_root.rglob("*.chart")) return charts
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def list_charts(self, app):\n return self._list(self._path() + '?app_name=' + app, 'charts')", "def charts(self):\n return self.container['charts']", "def list(self, **params):\n\n _, _, account_charts = self.http_client.get(\"/accountcharts\", params=params)\n return account_charts...
[ "0.7755798", "0.7449958", "0.71319413", "0.7110359", "0.66801405", "0.6495061", "0.63652325", "0.6342188", "0.6272101", "0.62555903", "0.6250946", "0.6006704", "0.60066587", "0.6001703", "0.597355", "0.59719837", "0.58516073", "0.5850192", "0.5838608", "0.5827216", "0.5812616...
0.8125694
0
r""" Convert a chart Path object to a string path relative to .\charm\data\charts
def strch(chart): charts_root = Path(R".\charm\data\charts") return str(chart.relative_to(charts_root))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_data_path(path):\n\n data_path = Path(self.kard.meta.get('data_path', 'data'))\n\n if data_path.is_absolute():\n return str(data_path / path)\n\n return str(self.kard_folder_path / self.kard.name / data_path /\n path)", "def get_path(s...
[ "0.6196704", "0.5926172", "0.5841862", "0.56423295", "0.56181204", "0.5596763", "0.5596409", "0.5583181", "0.5562562", "0.55594707", "0.552106", "0.55162907", "0.55162907", "0.54929805", "0.54887694", "0.54884666", "0.54857177", "0.5473863", "0.5469934", "0.54631054", "0.5450...
0.7617498
0
Set the map grid cell as obstacle
def set_obstacle(self, pos: tuple): if self.within_map(pos): self.map[round(pos[0]), round(pos[1])] = OBSTACLE return True else: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_obstacle(self, x, y):\n self.BOARD[y][x].traversable = False\n self.board_array[y][x] = 1", "def add_obstacle(self, x, y):\n self.BOARD[y][x].traversable = False\n self.board_array[y][x] = 1", "def update_obstacles(self, new_obs):\n self.obstacles = new_obs", "def s...
[ "0.6904903", "0.6904903", "0.6622904", "0.6531364", "0.6457762", "0.6457762", "0.6451341", "0.6433322", "0.6425923", "0.6391529", "0.637739", "0.63555276", "0.63377327", "0.6329692", "0.62948984", "0.6285746", "0.62847567", "0.625142", "0.62377983", "0.62250537", "0.6216072",...
0.7163415
0
Set the map grid cell as free
def set_free(self, pos: tuple): if self.within_map(pos): self.map[round(pos[0]), round(pos[1])] = FREE return True else: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reset(self):\r\n # replace with your code\r\n self._cells = [[0 for dummy_col in range(self._grid_width)] for dummy_row in range(self._grid_height)]\r\n self.new_tile()\r\n self.new_tile()", "def reset(self):\r\n # replace with your code\r\n for row in range(0, self....
[ "0.6971801", "0.68636346", "0.68111646", "0.67715645", "0.65903765", "0.6576617", "0.65482694", "0.6525577", "0.6496585", "0.6484593", "0.6477412", "0.64727926", "0.6461644", "0.64541066", "0.6445413", "0.6372728", "0.6361504", "0.6346274", "0.6346274", "0.63288206", "0.63155...
0.6799247
3
Check if the specified grid cell is occupied.
def is_obstacle(self, pos: tuple): if self.within_map(pos): return self.map[round(pos[0]), round(pos[1])] == OBSTACLE else: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _check_occupied(self, col, row):\n if self.board[row - 1][col - 1] == EMPTY:\n return False\n else:\n return True", "def _is_occupied(\n grid: List[List[str]], row: int, col: int, dx: int, dy: int) -> bool:\n while 0 <= (row + dy) < len(grid) and 0 <= (col + dx) < len(...
[ "0.8251217", "0.7962079", "0.7710803", "0.7681166", "0.74803954", "0.727737", "0.7273842", "0.72004473", "0.71587", "0.71319115", "0.7091942", "0.7075044", "0.7071857", "0.69793457", "0.6965492", "0.69624925", "0.692557", "0.69222736", "0.6915808", "0.6904662", "0.6853385", ...
0.0
-1
Check if the specified grid cell is free.
def is_free(self, pos: tuple): if self.within_map(pos): return self.map[round(pos[0]), round(pos[1])] == FREE else: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def checkAvailable(self, x, y):\n return 0 <= x < self.rows and 0 <= y < self.cols and not self.gridBusy[x][y]", "def check_free(self, arr):\n cell_location = self.cartesian_to_cell(arr)\n cell = self.occ_matrix[cell_location[0], cell_location[1]]\n return cell == 0", "def isFree(po...
[ "0.719573", "0.71511495", "0.7138081", "0.7021418", "0.69615394", "0.6675433", "0.6662159", "0.6597767", "0.65975684", "0.65579695", "0.6411737", "0.6411211", "0.6347452", "0.6343232", "0.62552905", "0.6222179", "0.61862236", "0.61669767", "0.6163536", "0.61213267", "0.611213...
0.6975477
4
Get neighbouring vertices of a location, which are within map bounds.
def get_neighbours(self, pos: tuple): x, y = pos[0], pos[1] neighbours = [(x + 1, y), (x + 1, y + 1), (x, y + 1), (x - 1, y + 1), (x - 1, y), (x - 1, y - 1), (x, y - 1), (x + 1, y - 1)] return {k: self.move_cost(pos, k) for k in neighbours if self.within_map(k)}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_neighbour(self, loc):\n y_lim, x_lim = np.shape(self.map)\n y, x = loc\n neighbour_cords = [(y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)]\n neighbour_cells = []\n for cords in neighbour_cords:\n curr_y, curr_x = cords\n if curr_y < 0 or curr_y >= y...
[ "0.7313774", "0.6526953", "0.6480245", "0.6299469", "0.6191116", "0.6134625", "0.609304", "0.6080118", "0.60728604", "0.60651284", "0.606193", "0.6058646", "0.6022795", "0.60064405", "0.6004463", "0.6003909", "0.5977814", "0.59745324", "0.59657377", "0.594686", "0.59358627", ...
0.5916195
22