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
import data from file asset = Only import for the asset that you want searchAndReplace = Change any part of the objects name to another word
def importData( self, asset = '', searchAndReplace = ['',''] ): pickleData = pickle.load( open( self.dataPath.path, "rb" ) ) layers = [RenderLayerData(l,d) for l,d in pickleData.items() if not ':' in l] for l in layers: if not searchAndReplace [0]== '' or not searchAndReplace[1] == '': l.filterMe( asset, searchAndReplace ) l.create() l.addObjects() l.makeOverrides() l.makeOverrideConnections() l.makeShaderOverride()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def replace(name, newobject):", "def renameAssetObjects(self):\n\t\tfor i,o in enumerate( self.objects ):\n\t\t\tmn.Node( o ).name = self.name + '%i'%i", "def loadAssetTypeSpecialCaseFromFile(file):\n\tstringToTuple = compose(\n\t\ttuple\n\t , partial(map, lambda s: s.strip())\n\t , lambda s: s.split(',')\n\...
[ "0.61271197", "0.5805997", "0.5651167", "0.5605872", "0.5587787", "0.5498569", "0.54969203", "0.53437096", "0.53432715", "0.5332981", "0.532139", "0.53159696", "0.5253007", "0.52161473", "0.52138823", "0.51546794", "0.5153983", "0.5098517", "0.5057885", "0.5048195", "0.504511...
0.67480993
0
import master settings from data file
def importMasterSettings(self): pickleData = pickle.load( open( self.masterPath.path, "rb" ) ) master = rlayer.RenderLayer( 'defaultRenderLayer' ) master.makeCurrent() for a in pickleData.keys(): try: a.v = pickleData[a] except: continue
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_settings(self, config):\n user = config.get(self.bot.client.host, 'master')\n # Replace old master\n if ':master' in self.users and user != self.users[':master']:\n self.users[self.users[':master']]['rank'] = 'none'\n if not user in self.users:\n self.user...
[ "0.62687576", "0.6112625", "0.60982084", "0.599278", "0.59767", "0.5931371", "0.5877606", "0.58080935", "0.5805709", "0.58034456", "0.57821137", "0.57619953", "0.57555234", "0.5754049", "0.5751691", "0.57266325", "0.5715067", "0.5707333", "0.5681978", "0.56536126", "0.5650209...
0.7781248
0
return the objects in the layer
def dataObjects(self): return self._objects
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def GetObjects(self): \r\n return self.model.GetObjects()", "def objects(self):", "def objects(self):\n\t\treturn self._objects", "def objects(self):\r\n return self._objects", "def getAllLayers(self):\n jobItem = self.item(0, 0)\n layerObjects = [jobItem.child(row, 0).da...
[ "0.76588994", "0.7365626", "0.7147258", "0.69459087", "0.69181466", "0.6739161", "0.670558", "0.6694696", "0.65370286", "0.6459321", "0.6447105", "0.64106923", "0.63908225", "0.6376006", "0.6317398", "0.63025784", "0.63025784", "0.63025784", "0.63025784", "0.63025784", "0.630...
0.6658779
8
return the overrides in the layer
def dataOverrides(self): return self._overrides
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def overrides(self) -> ConfigNodePropertyArray:\n return self._overrides", "def default_binding_overrides(self):\n return self.__default_binding_overrides", "def ComponentOverrides(self):\n return tuple(self._json_obj.get('component_overrides', {}).items())", "def makeOverrides(self):\n\t\tself....
[ "0.6976614", "0.6493725", "0.6390087", "0.6375561", "0.6312835", "0.6241755", "0.60139596", "0.59983903", "0.5893521", "0.5878425", "0.5835658", "0.5816514", "0.5811458", "0.58073103", "0.5771545", "0.5764795", "0.57407266", "0.5684022", "0.5561158", "0.5544201", "0.55372936"...
0.72761494
0
return the overrided connections
def dataOverconns(self): return self._overconns
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_connections(self) -> _ConnectionsMap:\n seen: Dict[int, Any] = {}\n for parent in self.target.ancestors:\n if not isinstance(parent, NodeInstance):\n continue\n if parent is self.target.root:\n break\n if self.operation_host:\n ...
[ "0.72107756", "0.719677", "0.71520996", "0.71520996", "0.71160644", "0.6827614", "0.68155587", "0.67435443", "0.6729093", "0.66902184", "0.6677647", "0.66670907", "0.6593339", "0.6425765", "0.639215", "0.63865095", "0.6366969", "0.63638633", "0.63590074", "0.6348137", "0.6316...
0.6257197
23
return the overrided shader
def dataShader(self): return self._shader
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getFragmentShader(self):\n return self.fshader", "def convert_shaders(self):\n raise NotImplementedError()", "def setShader(self, *args):\n return _osgAnimation.RigTransformHardware_setShader(self, *args)", "def get_shader_codes(self):\n vs = VS_TEMPLATE\n fs = FS_TEMPL...
[ "0.71515524", "0.6992073", "0.65359896", "0.64718676", "0.6368677", "0.63054544", "0.62507594", "0.59390277", "0.59311384", "0.5861681", "0.584541", "0.5813607", "0.5793342", "0.5786723", "0.5785204", "0.578408", "0.57676625", "0.57501054", "0.57129234", "0.5711793", "0.57105...
0.6786076
2
filter data based on asset name and searchAndReplace data
def filterMe(self, asset = '', sAr = ['', ''] ): if self._objects: self._objects = [ mn.Node( o.name.replace( sAr[0], sAr[1] ) ) for o in self._objects ] if self._overrides: self._overrides = dict( [ (mn.Node( a.name.replace( sAr[0], sAr[1] )), self._overrides[a] ) for a in self._overrides.keys() ] ) if self._overconns: self._overconns = dict( [(mn.Node(a.name.replace( sAr[0], sAr[1] )), mn.Node(self._overconns[a].name.replace( sAr[0], sAr[1] ))) for a in self._overconns.keys() ] )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def healthcare_filter(df_all): \n #get requested assets under healthcare tag \n df_filtered = pandas.DataFrame(columns=['osm_id','asset','geometry']) #create df for saving data\n for row in range(len(df_all.index)): \n if 'healthcare' in df_all[\"asset\"][row]: #check if healthcare key ...
[ "0.6367185", "0.59256476", "0.5885273", "0.5829923", "0.5723036", "0.5712686", "0.5658041", "0.55008304", "0.5442001", "0.543063", "0.5343348", "0.53341204", "0.5302959", "0.5286173", "0.52814966", "0.5254674", "0.5248854", "0.5234224", "0.5183874", "0.5160617", "0.51445144",...
0.52709234
15
make the overrdies based on data
def makeOverrides(self): self.overridesWithValues = self.dataOverrides
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def crossover(p1, p2):\n genotype = []\n \n #Your code here\n \n return {'genotype': genotype, 'fitness': None}", "def crossover(x1,x2):\n for chromo in x1.chromosomes:\n result_chromos = [np.zeros((chromo.shape))]\n #result_chromos = [np.zeros((chromo.shape)) for chromo in x1.chromos...
[ "0.5584811", "0.55532134", "0.5427016", "0.5426902", "0.53494334", "0.53424084", "0.5334913", "0.52737105", "0.5264165", "0.52625084", "0.52520084", "0.5175564", "0.51129985", "0.5108802", "0.5096884", "0.5085431", "0.50571185", "0.50070727", "0.5000612", "0.49764836", "0.497...
0.0
-1
When the user posts the find_org_to_create_account form, redirect to that page
def find_org_to_create_account(request): if request.method != 'POST' or not request.POST.get('organization_slug'): return HttpResponseRedirect(reverse('home')) else: org_slug = request.POST.get('organization_slug') return HttpResponseRedirect(reverse('create_org_account', args=[org_slug]))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def oauth_start_flow():\n # Have to do authentication!\n rest.default_user_authentication()\n\n account_type = flask.request.args.get('type')\n if account_type is None:\n flask.abort(400)\n\n cls = ACCOUNT_TYPES.get(account_type, None)\n if cls is None:\n flask.about(400)\n\n key = str(uuid.uuid4())\n...
[ "0.603463", "0.6004999", "0.5971245", "0.5959396", "0.5919654", "0.58651173", "0.58611304", "0.58471966", "0.582282", "0.57899594", "0.578932", "0.57571214", "0.57511485", "0.574679", "0.57035786", "0.56987613", "0.56865185", "0.5668221", "0.5650241", "0.5633905", "0.5633754"...
0.81982374
0
runs gradient descent to find a minimum of x^2 + y^2
def run_gradient_descent(seed=0): random.seed(seed) colors = [color for color in matplotlib.colors.cnames] def random_point(): return (2 * random.random() - 1, 2 * random.random() - 1) def df(x_i): """this is the gradient of x^2 + y^2""" return [2 * x_ij for x_ij in x_i] for color in random.sample(colors, 50): path = take(10, gradient_descent(df, random_point())) for i, (x, y) in enumerate(path): plt.plot(x, y, color=color, marker='*', markersize=20-2*i) plt.show()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gradient_descent(self, x, y):\n # Initialize weights vector\n self.weights = np.zeros(len(x[0]))\n\n # Storing number of training example in a variable \n n = len(x)\n\n # Initiate variables to keep track of the current and smallest loss recorded\n lowest_loss = sys.fl...
[ "0.6790553", "0.66664946", "0.6630496", "0.64925885", "0.6476258", "0.64171803", "0.6405911", "0.6358458", "0.63555044", "0.6333278", "0.6325413", "0.62547517", "0.62520844", "0.624353", "0.6242326", "0.62349296", "0.62339544", "0.622683", "0.62201583", "0.61891985", "0.61857...
0.5771183
93
this is the gradient of x^2 + y^2
def df(x_i): return [2 * x_ij for x_ij in x_i]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gradient(self, x):\n pass", "def compute_gradient (w, x, y):\n (n,d) = x.shape\n g = np.zeros(d)\n for i in range(0,d):\n g[i] = (w*x-y)*np.transpose(x[i])\n g += 0.5*w\n return g", "def gradient(self, x):\n return 0.0", "def calculate_gradient(...
[ "0.8220284", "0.7768869", "0.7596814", "0.7590641", "0.7536355", "0.7535873", "0.7492485", "0.74524486", "0.74460936", "0.74246055", "0.7422228", "0.73773456", "0.7359993", "0.73566616", "0.73448485", "0.7335415", "0.7270468", "0.72532976", "0.7230785", "0.7145674", "0.711091...
0.0
-1
this is the gradient of x^2 + y^2
def df(x_i): return [2 * x_ij for x_ij in x_i]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gradient(self, x):\n pass", "def compute_gradient (w, x, y):\n (n,d) = x.shape\n g = np.zeros(d)\n for i in range(0,d):\n g[i] = (w*x-y)*np.transpose(x[i])\n g += 0.5*w\n return g", "def gradient(self, x):\n return 0.0", "def calculate_gradient(...
[ "0.8220871", "0.7769543", "0.7597072", "0.7590164", "0.75366026", "0.7535663", "0.7492575", "0.7453598", "0.7445228", "0.7424073", "0.74229896", "0.73769474", "0.73603284", "0.735691", "0.73446774", "0.7335506", "0.727039", "0.7253472", "0.7231205", "0.7145222", "0.71104634",...
0.0
-1
runs gradient descent to find a minimum of exp(x^3 / 3 + x y^2)
def run_gradient_descent2(seed=0): colors = [color for color in matplotlib.colors.cnames] def random_point(): return (3 * random.random() - 1, 3 * random.random() - 1) def f(x): """has min at (1,0), saddle point at (-1,0)""" return -math.exp(x[0]**3/-3 + x[0] - x[1]**2) def df(x): return ((1 - x[0]**2) * f(x), -2 * x[1] * f(x)) for color in random.sample(colors, 50): path = take(100, gradient_descent(df, random_point())) for i, (x, y) in enumerate(path): plt.plot(x, y, color=color, marker='*', markersize=25-i/4) plt.show()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gradient_ascent(self, w, X, y, lr):\r\n # INSERT YOUR CODE HERE\r\n #raise Exception('Function not yet implemented!')\r\n # gradient = x_j*(y-σ(wTX))\r\n return np.dot(X.T, y-self.sigmoid(np.dot(X, w)))", "def gradient_descent(self, x, y):\n # Initialize weights vector\n ...
[ "0.69871354", "0.683685", "0.68088645", "0.6712275", "0.6709997", "0.66748154", "0.664998", "0.66304016", "0.6604216", "0.6590052", "0.65628034", "0.655809", "0.65575576", "0.647663", "0.64651537", "0.6445425", "0.64412385", "0.6429857", "0.64228696", "0.64162236", "0.6411271...
0.5987452
75
has min at (1,0), saddle point at (1,0)
def f(x): return -math.exp(x[0]**3/-3 + x[0] - x[1]**2)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def saddle_point(self):\n\n maxmin_value, maxmin_strategy_set = self.maxmin(0)\n minmax_value, minmax_strategy_set = self.minmax(1)\n\n if maxmin_value == minmax_value:\n return maxmin_strategy_set.intersection(minmax_strategy_set)\n return None", "def exact_saddle(V,X,Y,Z,...
[ "0.71217895", "0.6409307", "0.6010213", "0.58238053", "0.5752256", "0.57095367", "0.56663626", "0.5627546", "0.55863583", "0.5570218", "0.55443054", "0.55192417", "0.54011667", "0.53589064", "0.5356541", "0.53509325", "0.5303866", "0.5300293", "0.52988297", "0.5297635", "0.52...
0.0
-1
has min at (1,0), saddle point at (1,0)
def f(x): return -math.exp(x[0]**3/-3 + x[0] - x[1]**2)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def saddle_point(self):\n\n maxmin_value, maxmin_strategy_set = self.maxmin(0)\n minmax_value, minmax_strategy_set = self.minmax(1)\n\n if maxmin_value == minmax_value:\n return maxmin_strategy_set.intersection(minmax_strategy_set)\n return None", "def exact_saddle(V,X,Y,Z,...
[ "0.712052", "0.6408869", "0.60100293", "0.5823926", "0.57521075", "0.5708044", "0.56659967", "0.5627963", "0.5585765", "0.5570389", "0.5544212", "0.5519314", "0.5401504", "0.5359145", "0.53573614", "0.5350745", "0.5303898", "0.53009754", "0.5297841", "0.529778", "0.5294022", ...
0.0
-1
df is a function of x_i, y_i, beta
def sgd_step(df, alpha, prev_beta, xy_i): x_i, y_i = xy_i gradient = df(x_i, y_i, prev_beta) return [beta_j + alpha * df_j for beta_j, df_j in zip(prev_beta, gradient)]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_beta(self,df,tick,ind):\n cov = get_cov(df,tick,ind)\n var = df[ind].var()\n beta = cov / var\n return beta", "def create_beta_posteriors(df):\n goods = df.num_matured - df.fpd\n df['alpha_p'] = df.alpha + df.fpd\n df['beta_p'] = df.beta + goods\n return df", "de...
[ "0.68780404", "0.6571103", "0.65438884", "0.6472203", "0.62649596", "0.622851", "0.6134441", "0.6110367", "0.6021685", "0.5859265", "0.5851953", "0.5832189", "0.57926506", "0.5776251", "0.5776251", "0.5743775", "0.56781954", "0.56520283", "0.5651162", "0.5608268", "0.5604049"...
0.66248494
1
Just a simple decorator to make the process of generating tests easier.
def Generatable(cls): if hasattr(cls, 'generate_tests') and callable(cls.generate_tests): def create_test_func(name, test_func): setattr(cls, 'test_' + name.replace(' ', '_').lower(), test_func) cls.generate_tests(create_test_func) return cls
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def spec_tests():\n pass", "def test_something():", "def unitary_test():", "def test_dummy():", "def tests():", "def test_generate_all_testing(self):\n pass", "def test_1():", "def test_func():\n pass", "def test_dummy_test():\n pass", "def test_T1():", "def test_T1():", "def ...
[ "0.78306496", "0.76522076", "0.76440585", "0.7547918", "0.7521638", "0.73572", "0.7326144", "0.7307783", "0.7230892", "0.7225894", "0.7225894", "0.7212739", "0.7207286", "0.71436405", "0.7143635", "0.71356994", "0.71356994", "0.71143264", "0.711168", "0.7106708", "0.7092831",...
0.6944086
34
Get the color of the mask at position. Using 2 bits as a color.
def get_color(mask: int, position: int): return (mask >> (position << 1)) & 3
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mask_color(self):\n return self._mask_color", "def set_color(mask: int, position: int, color: int):\n return mask | (color << (position << 1))", "def get_color(self, point):\n \n d = point - self._origin\n dist = int(d.dot(d) ** 0.5) % 2\n if dist == 0:\n ...
[ "0.6762996", "0.6617752", "0.6400042", "0.6352335", "0.6179756", "0.607116", "0.60303086", "0.5943762", "0.59284455", "0.58960706", "0.58665735", "0.58665735", "0.58594924", "0.5858215", "0.58338976", "0.57897294", "0.5776139", "0.5772793", "0.5763152", "0.5751781", "0.574337...
0.8632774
0
Set the color of the mask at position. Using 2 bits as a color.
def set_color(mask: int, position: int, color: int): return mask | (color << (position << 1))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_color(mask: int, position: int):\n return (mask >> (position << 1)) & 3", "def SetMaskColour(*args, **kwargs):\n return _gdi_.Bitmap_SetMaskColour(*args, **kwargs)", "def setColorIndex(idx):\n dislin.setclr(idx)", "def set_pixel(framebuf, x, y, color):\n index = (y >> 3) *...
[ "0.67938983", "0.67375386", "0.6516931", "0.6429108", "0.64179796", "0.6417907", "0.63744414", "0.6285334", "0.61303943", "0.6114359", "0.61034447", "0.6082238", "0.6080526", "0.6059235", "0.60527635", "0.6043658", "0.60351825", "0.59847206", "0.5964086", "0.5936446", "0.5918...
0.8528009
0
Create a new ir.Set instance with given attributes. Absolutely all ir.Set instances must be created using this constructor.
def new_set(*, ctx: context.ContextLevel, **kwargs) -> irast.Set: ir_set = irast.Set(**kwargs) ctx.all_sets.append(ir_set) return ir_set
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, **attributes):\n self.set(**attributes)", "def __init__(self,\n *,\n attributes: List['Attribute'] = None) -> None:\n self.attributes = attributes", "def newChemAtomSet(self, **attrlinks):\n return ChemAtomSet(self, **attrlinks)", "def __ini...
[ "0.7283344", "0.6427488", "0.64081055", "0.621952", "0.620814", "0.6190213", "0.6113432", "0.6045844", "0.600017", "0.600017", "0.59091234", "0.59091234", "0.59091234", "0.58970034", "0.584854", "0.5807153", "0.5795997", "0.5795997", "0.579595", "0.57853985", "0.57681274", ...
0.7015722
1
Create a new ir.Set from another ir.Set. The new Set inherits source Set's scope, schema item, expression, and, if preserve_scope_ns is set, path_id. If preserve_scope_ns is False, the new Set's path_id will be namespaced with the currently active scope namespace.
def new_set_from_set( ir_set: irast.Set, *, preserve_scope_ns: bool=False, path_id: typing.Optional[irast.PathId]=None, stype: typing.Optional[s_types.Type]=None, ctx: context.ContextLevel) -> irast.Set: if path_id is None: path_id = ir_set.path_id if not preserve_scope_ns: path_id = path_id.merge_namespace(ctx.path_id_namespace) if stype is None: stype = ir_set.stype result = new_set( path_id=path_id, path_scope_id=ir_set.path_scope_id, stype=stype, expr=ir_set.expr, ctx=ctx ) result.rptr = ir_set.rptr return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new_set(*, ctx: context.ContextLevel, **kwargs) -> irast.Set:\n ir_set = irast.Set(**kwargs)\n ctx.all_sets.append(ir_set)\n return ir_set", "def create_set(self, setname='new_set', based_on='data file', included=None,\n excluded=None, strings='keep', arrays='masks', replace=None,\...
[ "0.6440217", "0.58299524", "0.56834817", "0.53686655", "0.5344023", "0.5315017", "0.52834666", "0.5264932", "0.5153018", "0.50790906", "0.5055263", "0.5012567", "0.49638426", "0.49290437", "0.49098164", "0.4880802", "0.48652387", "0.4844571", "0.48155996", "0.48035938", "0.47...
0.85868055
0
Create an ir.Set representing the given EdgeQL path expression.
def compile_path(expr: qlast.Path, *, ctx: context.ContextLevel) -> irast.Set: anchors = ctx.anchors path_tip = None if expr.partial: if ctx.partial_path_prefix is not None: path_tip = ctx.partial_path_prefix else: raise errors.QueryError( 'could not resolve partial path ', context=expr.context) extra_scopes = {} computables = [] path_sets = [] for i, step in enumerate(expr.steps): if isinstance(step, qlast.Source): # 'self' can only appear as the starting path label # syntactically and is a known anchor path_tip = anchors[step.__class__] elif isinstance(step, qlast.Subject): # '__subject__' can only appear as the starting path label # syntactically and is a known anchor path_tip = anchors[step.__class__] elif isinstance(step, qlast.ObjectRef): if i > 0: raise RuntimeError( 'unexpected ObjectRef as a non-first path item') refnode = None if not step.module and step.name not in ctx.aliased_views: # Check if the starting path label is a known anchor refnode = anchors.get(step.name) if refnode is not None: path_tip = new_set_from_set( refnode, preserve_scope_ns=True, ctx=ctx) else: stype = schemactx.get_schema_type( step, item_types=(s_objtypes.ObjectType,), ctx=ctx) if (stype.get_view_type(ctx.env.schema) is not None and stype.get_name(ctx.env.schema) not in ctx.view_nodes): # This is a schema-level view, as opposed to # a WITH-block or inline alias view. stype = stmtctx.declare_view_from_schema(stype, ctx=ctx) path_tip = class_set(stype, ctx=ctx) view_set = ctx.view_sets.get(stype) if view_set is not None: path_tip = new_set_from_set(view_set, ctx=ctx) path_scope = ctx.path_scope_map.get(view_set) extra_scopes[path_tip] = path_scope.copy() view_scls = ctx.class_view_overrides.get( stype.get_name(ctx.env.schema)) if view_scls is not None: path_tip.stype = view_scls elif isinstance(step, qlast.Ptr): # Pointer traversal step ptr_expr = step ptr_target = None direction = (ptr_expr.direction or s_pointers.PointerDirection.Outbound) if ptr_expr.target: # ... link [IS Target] ptr_target = schemactx.get_schema_type( ptr_expr.target.maintype, ctx=ctx) if not isinstance(ptr_target, s_objtypes.ObjectType): raise errors.QueryError( f'invalid type filter operand: ' f'{ptr_target.get_name(ctx.env.schema)} ' f'is not an object type', context=ptr_expr.target.context) ptr_name = ptr_expr.ptr.name if ptr_expr.type == 'property': # Link property reference; the source is the # link immediately preceding this step in the path. source = path_tip.rptr.ptrcls else: source = path_tip.stype with ctx.newscope(fenced=True, temporary=True) as subctx: if isinstance(source, s_abc.Tuple): path_tip = tuple_indirection_set( path_tip, source=source, ptr_name=ptr_name, source_context=step.context, ctx=subctx) else: path_tip = ptr_step_set( path_tip, source=source, ptr_name=ptr_name, direction=direction, ptr_target=ptr_target, ignore_computable=True, source_context=step.context, ctx=subctx) ptrcls = path_tip.rptr.ptrcls if _is_computable_ptr(ptrcls, ctx=ctx): computables.append(path_tip) else: # Arbitrary expression if i > 0: raise RuntimeError( 'unexpected expression as a non-first path item') with ctx.newscope(fenced=True, temporary=True) as subctx: path_tip = ensure_set( dispatch.compile(step, ctx=subctx), ctx=subctx) if path_tip.path_id.is_type_indirection_path(ctx.env.schema): scope_set = path_tip.rptr.source else: scope_set = path_tip extra_scopes[scope_set] = subctx.path_scope for key_path_id in path_tip.path_id.iter_weak_namespace_prefixes(): mapped = ctx.view_map.get(key_path_id) if mapped is not None: path_tip = new_set( path_id=mapped.path_id, stype=path_tip.stype, expr=mapped.expr, rptr=mapped.rptr, ctx=ctx) break path_sets.append(path_tip) path_tip.context = expr.context pathctx.register_set_in_scope(path_tip, ctx=ctx) for ir_set in computables: scope = ctx.path_scope.find_descendant(ir_set.path_id) if scope is None: # The path is already in the scope, no point # in recompiling the computable expression. continue with ctx.new() as subctx: subctx.path_scope = scope comp_ir_set = computable_ptr_set(ir_set.rptr, ctx=subctx) i = path_sets.index(ir_set) if i != len(path_sets) - 1: path_sets[i + 1].rptr.source = comp_ir_set else: path_tip = comp_ir_set path_sets[i] = comp_ir_set for ir_set, scope in extra_scopes.items(): node = ctx.path_scope.find_descendant(ir_set.path_id) if node is None: # The path portion not being a descendant means # that is is already present in the scope above us, # along with the view scope. continue fuse_scope_branch(ir_set, node, scope, ctx=ctx) if ir_set.path_scope_id is None: pathctx.assign_set_scope(ir_set, node, ctx=ctx) return path_tip
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new_set_from_set(\n ir_set: irast.Set, *,\n preserve_scope_ns: bool=False,\n path_id: typing.Optional[irast.PathId]=None,\n stype: typing.Optional[s_types.Type]=None,\n ctx: context.ContextLevel) -> irast.Set:\n if path_id is None:\n path_id = ir_set.path_id\n if...
[ "0.5790698", "0.5771053", "0.5408858", "0.5098475", "0.50746995", "0.49623165", "0.4907437", "0.48602664", "0.48467776", "0.48467776", "0.48342997", "0.4825272", "0.48136362", "0.4735757", "0.47344112", "0.47056362", "0.47041735", "0.46564844", "0.46460888", "0.4642975", "0.4...
0.5753197
2
Return a Set node representing the new path tip.
def extend_path( source_set: irast.Set, ptrcls: s_pointers.Pointer, direction: PtrDir=PtrDir.Outbound, target: typing.Optional[s_nodes.Node]=None, *, ignore_computable: bool=False, force_computable: bool=False, unnest_fence: bool=False, same_computable_scope: bool=False, ctx: context.ContextLevel) -> irast.Set: if ptrcls.is_link_property(ctx.env.schema): src_path_id = source_set.path_id.ptr_path() else: if direction != s_pointers.PointerDirection.Inbound: source = ptrcls.get_near_endpoint(ctx.env.schema, direction) if not source_set.stype.issubclass(ctx.env.schema, source): # Polymorphic link reference source_set = class_indirection_set( source_set, source, optional=True, ctx=ctx) src_path_id = source_set.path_id if target is None: target = ptrcls.get_far_endpoint(ctx.env.schema, direction) path_id = src_path_id.extend(ptrcls, direction, target, ns=ctx.path_id_namespace, schema=ctx.env.schema) target_set = new_set(stype=target, path_id=path_id, ctx=ctx) ptr = irast.Pointer( source=source_set, target=target_set, ptrcls=ptrcls, direction=direction ) target_set.rptr = ptr if (not ignore_computable and _is_computable_ptr( ptrcls, force_computable=force_computable, ctx=ctx)): target_set = computable_ptr_set( ptr, unnest_fence=unnest_fence, same_computable_scope=same_computable_scope, ctx=ctx) return target_set
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def xpathNewNodeSet(self):\n ret = libxml2mod.xmlXPathNewNodeSet(self._o)\n if ret is None:raise xpathError('xmlXPathNewNodeSet() failed')\n return xpathObjectRet(ret)", "def make_set(node):\n node.parent = node\n node.rank = 0", "def visit_Set(self, node):\n self.generic_visi...
[ "0.62189937", "0.5731682", "0.5512014", "0.55116665", "0.5465013", "0.5457394", "0.5436884", "0.5389255", "0.53820276", "0.5347002", "0.52735144", "0.52636284", "0.5250073", "0.5236279", "0.51947445", "0.51905155", "0.5184115", "0.5166615", "0.5112369", "0.510633", "0.5062499...
0.46827704
60
Return ir.Set for a pointer defined as a computable.
def computable_ptr_set( rptr: irast.Pointer, *, unnest_fence: bool=False, same_computable_scope: bool=False, ctx: context.ContextLevel) -> irast.Set: ptrcls = rptr.ptrcls source_set = rptr.source source_scls = source_set.stype # process_view() may generate computable pointer expressions # in the form "self.linkname". To prevent infinite recursion, # self must resolve to the parent type of the view NOT the view # type itself. Similarly, when resolving computable link properties # make sure that we use rptr.ptrcls.derived_from. if source_scls.is_view(ctx.env.schema): source_set = new_set_from_set( source_set, preserve_scope_ns=True, ctx=ctx) source_set.stype = source_scls.peel_view(ctx.env.schema) source_set.shape = [] if source_set.rptr is not None: schema = ctx.env.schema derived_from = source_set.rptr.ptrcls.get_derived_from(schema) if (derived_from is not None and not derived_from.generic(schema) and derived_from.get_derived_from(schema) is not None and ptrcls.is_link_property(schema)): source_set.rptr.ptrcls = derived_from try: qlexpr, qlctx, inner_source_path_id, path_id_ns = \ ctx.source_map[ptrcls] except KeyError: ptrcls_default = ptrcls.get_default(ctx.env.schema) if not ptrcls_default: ptrcls_sn = ptrcls.get_shortname(ctx.env.schema) raise ValueError( f'{ptrcls_sn!r} is not a computable pointer') if isinstance(ptrcls_default, s_expr.ExpressionText): qlexpr = astutils.ensure_qlstmt(qlparser.parse(ptrcls_default)) else: qlexpr = qlast.BaseConstant.from_python(ptrcls_default) qlctx = None inner_source_path_id = None path_id_ns = None if qlctx is None: # Schema-level computable, completely detached context newctx = ctx.detached else: newctx = _get_computable_ctx( rptr=rptr, source=source_set, source_scls=source_scls, inner_source_path_id=inner_source_path_id, path_id_ns=path_id_ns, same_scope=same_computable_scope, qlctx=qlctx, ctx=ctx) if ptrcls.is_link_property(ctx.env.schema): source_path_id = rptr.source.path_id.ptr_path() else: source_path_id = rptr.target.path_id.src_path() path_id = source_path_id.extend( ptrcls, s_pointers.PointerDirection.Outbound, ptrcls.get_target(ctx.env.schema), ns=ctx.path_id_namespace, schema=ctx.env.schema) with newctx() as subctx: subctx.view_scls = ptrcls.get_target(ctx.env.schema) subctx.view_rptr = context.ViewRPtr( source_scls, ptrcls=ptrcls, rptr=rptr) subctx.anchors[qlast.Source] = source_set subctx.empty_result_type_hint = ptrcls.get_target(ctx.env.schema) if isinstance(qlexpr, qlast.Statement) and unnest_fence: subctx.stmt_metadata[qlexpr] = context.StatementMetadata( is_unnest_fence=True) comp_ir_set = dispatch.compile(qlexpr, ctx=subctx) if ptrcls in ctx.pending_cardinality: comp_ir_set_copy = copy.copy(comp_ir_set) specified_card, source_ctx = ctx.pending_cardinality[ptrcls] stmtctx.get_pointer_cardinality_later( ptrcls=ptrcls, irexpr=comp_ir_set_copy, specified_card=specified_card, source_ctx=source_ctx, ctx=ctx) def _check_cardinality(ctx): if ptrcls.singular(ctx.env.schema): stmtctx.enforce_singleton_now(comp_ir_set_copy, ctx=ctx) stmtctx.at_stmt_fini(_check_cardinality, ctx=ctx) comp_ir_set.stype = ptrcls.get_target(ctx.env.schema) comp_ir_set.path_id = path_id comp_ir_set.rptr = rptr rptr.target = comp_ir_set return comp_ir_set
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getSet(unique_name):", "def getSet(unique_name):", "def set():", "def visit_Set(self, node):\n self.generic_visit(node)\n return to_call(to_attribute(self.operator, '__set__'), node.elts)", "def set_of(element: Type) -> SetType:\n return SetType(element)", "def __rxor__(self, other: ...
[ "0.63821733", "0.63821733", "0.6101638", "0.60650355", "0.5940626", "0.5939873", "0.5794654", "0.5785868", "0.5782201", "0.5721857", "0.5620131", "0.55960476", "0.559237", "0.55909944", "0.55824697", "0.5576209", "0.55492747", "0.5549152", "0.55308235", "0.551", "0.5487735", ...
0.69799614
0
Requests should have a section of the config file and variable/field in that section to be returned in the response body.
def on_get(self, req, resp, section, field): resp.content_type = 'text/text' resp.body = self.direct_get(field, section)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get(self, request, format=None):\n return Response({k: getattr(config, k) for k in list(dir(config))})", "def output_config() -> Response:\n c = dict(config)\n c['password'] = \"*********\"\n return jsonify(c)", "def get_config(req):\n #try:\n # user_id = req.user\n ...
[ "0.6424139", "0.610865", "0.6059112", "0.5978963", "0.5865252", "0.577705", "0.56624496", "0.55671096", "0.5566648", "0.55476516", "0.5478806", "0.54480094", "0.5438941", "0.5410219", "0.54032665", "0.5333807", "0.5330522", "0.53133196", "0.5285215", "0.5283924", "0.5283706",...
0.5230246
26
read the maps and get the set of unique rs
def getLCD(lbase=[]): listmf = [] rsdict = {} for i,basename in enumerate(lbase): # for each basename to be included mf = file('%s.map' % basename,'r').readlines() lmap = [x.strip().split() for x in mf] rslist = [x[1] for x in lmap] # chrom rs gendist physdist for x in lmap: rsdict[x[1]] = (x[0],int(x[3]),x[1]) # key by chrom,offset,rs setrs = set(rslist) listmf.append(setrs) # list of map lines for processing lcd = listmf.pop(0) # start with first - order doesn't matter for setrs in listmf: lcd = lcd & setrs # intersection lcd = list(lcd) # now have lowest common denom as a list of rs lcdmap = [rsdict[rs] for rs in lcd] # restore chrom,offset,rs for rs to keep lcdmap.sort() # now in genomic order print 'got lcdmap=',lcdmap[:10] return lcdmap # sorted common map
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getSet(unique_name):", "def getSet(unique_name):", "def getSets(unique_name=None):", "def _findUniqueMappingValues(mapping):\n uniqueMappingValues = set()\n for entries in viewvalues(mapping):\n if len(entries) == 1:\n uniqueMappingValues.update(entries)\n return uniqueMappingV...
[ "0.65541935", "0.65541935", "0.63683355", "0.6343676", "0.60978246", "0.6096743", "0.6089678", "0.595537", "0.58867276", "0.5861434", "0.577347", "0.57008076", "0.56791395", "0.5647053", "0.56417656", "0.5591158", "0.5569142", "0.5543664", "0.5527229", "0.5526804", "0.550279"...
0.0
-1
return founder and offspring subset of basename.ped containing only the markers in lcd lcd contains a sorted list of (chrom,offset,rs) for the common snps in all maps we need to keep genotypes all in the same column order
def subsetPed(basename="",lcdmap = [],faff='1', ofaff='2'): mf = file('%s.map' % basename,'r').readlines() lmap = [x.strip().split() for x in mf] rscols = {} # lookup marker table colrs = [] # lookup rs from column for i,m in enumerate(lmap): # get columns to keep in the order we want them rscols[m[1]] = i # keep track of where each rs is in this map colrs.append(m[1]) # and keep the list of rs for tracking alleles wewant = [rscols[x[2]] for x in lcdmap] # columns we want to keep print '#Subsetped faff=%s ofaff=%s keeping %d (%s) of potential lcd %d for %s' % \ (faff,ofaff,len(wewant),wewant[:20],len(lcdmap),basename) pf = file('%s.ped' % basename,'r') ogeno = [] # offspring new lines fgeno = [] # founders oped = [] # for pedigrees fped = [] rsadict = {} # keep a count of alleles - seems to be a problem for i,l in enumerate(pf): if (i+1) % 500 == 0: print '%s at line %d' % (basename,i+1) ll = l.strip().split() ped = ll[:6] founder = (ll[2] == '0' and ll[3] == '0') aff = faff if not founder: aff = ofaff ped[5] = aff # adjust as needed if founder: fped.append(ped) else: oped.append(ped) gt = ll[6:] geno = [] for snp in wewant: # columns in order thisrs = colrs[snp] base = snp*2 g1 = gt[base] g2 = gt[base+1] geno.append(g1) geno.append(g2) if not rsadict.get(thisrs,None): rsadict[thisrs] = {} if g1 <> '0': if not rsadict[thisrs].get(g1,None): rsadict[thisrs][g1] = 1 else: rsadict[thisrs][g1] += 1 if g2 <> '0': if not rsadict[thisrs].get(g2,None): rsadict[thisrs][g2] = 1 else: rsadict[thisrs][g2] += 1 keepgt = array.array('c',geno) if founder: fgeno.append(keepgt) else: ogeno.append(keepgt) print '#Subsetped %s %d fgeno %d ogeno' % (basename,len(fgeno),len(ogeno)) return fped,oped,fgeno,ogeno,rsadict
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getLCD(lbase=[]):\r\n listmf = []\r\n rsdict = {}\r\n for i,basename in enumerate(lbase): # for each basename to be included\r\n mf = file('%s.map' % basename,'r').readlines()\r\n lmap = [x.strip().split() for x in mf] \r\n rslist = [x[1] for x in lmap] # chrom rs gendist physdist...
[ "0.6327156", "0.61232364", "0.56347793", "0.56296253", "0.5618694", "0.5515025", "0.54627013", "0.5458853", "0.538327", "0.53801644", "0.53717375", "0.52709544", "0.5267916", "0.52162147", "0.5175573", "0.5166157", "0.51569754", "0.5155961", "0.51448816", "0.5137253", "0.5111...
0.675231
0
take a list of basenames, get lcd and merge set founder affection according to faff flag and offspring according to ofaff flag
def mergePed(bnlist=[],faff=[],ofaff=[],newbasename='newped',fo=0): lcdmap = getLCD(bnlist) # list of chr,offset,rs for all snp common to all files print 'got %d lcd snps-%s' % (len(lcdmap),lcdmap[:5]) cfped = [] coped = [] cfgeno = [] cogeno = [] allrsa = {} ignorers = {} for i,basename in enumerate(bnlist): fped,oped,fgeno,ogeno,trsadict = subsetPed(basename,lcdmap,faff[i],ofaff[i]) print '%s gave %d fgeno' % (basename,len(fgeno)) for rs in trsadict.keys(): tk = trsadict[rs].keys() if len(tk) > 2: print 'for %s, rs %s has alleles %s' % (basename, rs, trsadict[rs]) if not allrsa.get(rs,None): allrsa[rs] = {} for a in tk: if not allrsa[rs].get(a,None): allrsa[rs][a] = trsadict[rs][a] else: allrsa[rs][a] += trsadict[rs][a] tk = allrsa[rs].keys() if len(tk) > 2 and not ignorers.get(rs,None): # new #print 'After merge basename %s, rs %s has alleles %s' % (basename, rs,allrsa[rs]) ignorers[rs] = rs cfped += fped coped += oped cfgeno += fgeno cogeno += ogeno print 'after merge all have %d fgeno and %d ogeno' % (len(cfgeno),len(cogeno)) # now have offspring and founder rows in lcdmap order # write map file print '### found %d markers > 2 alleles' % (len(ignorers.keys())) keepmarkers = [x for x in range(len(lcdmap)) if not ignorers.get(lcdmap[x][2],None)] newmap = ['\t'.join((lcdmap[x][0],lcdmap[x][2],'0','%d' % lcdmap[x][1])) for x in keepmarkers] # chrom,offset,rs f = file('%s.map' % newbasename,'w') f.write('%s\n' % '\n'.join(newmap)) f.close() for i,geno in enumerate(cfgeno): # convert each array into a list and keep the good markers gs = ''.join(['%s%s' % (geno[2*x],geno[2*x + 1]) for x in keepmarkers]) g = array.array('c',gs) # good ones cfgeno[i] = g # replace print 'cfgeno converted' if not fo: # not founders only - note arrays are not lists! cfped += copy.copy(coped) # del coped for i,geno in enumerate(cogeno): # convert each array into a list and keep the good markers gs = ''.join(['%s%s' % (geno[2*x],geno[2*x + 1]) for x in keepmarkers]) g = array.array('c',gs) # good ones cfgeno.append(g) # extend founders del cogeno print 'after if not fo now have %d cfgeno' % (len(cfgeno)) f = file('%s.ped' % newbasename,'w') for n,ped in enumerate(cfped): l = ' '.join(ped + list(cfgeno[n])) if n % 100 == 0 and n > 0: print 'writing line %d' % n f.write(l) f.write('\n') f.close() print 'wrote %d map rows and %d ped rows to %s' % (len(newmap),len(cfped),newbasename)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def autocontext_forests(dirname):\n rf_files = []\n for filename in os.listdir(dirname):\n fullname = os.path.join(dirname, filename)\n if os.path.isfile(fullname) and len(filename) >= 8:\n base, middle, end = filename[:3], filename[3:-4], filename[-4:]\n if base == \"rf_\...
[ "0.58278376", "0.569089", "0.5623684", "0.56120443", "0.5441088", "0.53539836", "0.5308381", "0.5256427", "0.52116", "0.51895374", "0.5147063", "0.5108449", "0.51060414", "0.5100264", "0.5047533", "0.5038564", "0.5021236", "0.5014878", "0.50056285", "0.49947405", "0.49672922"...
0.64975625
0
Test list secrets when not connected to any cluster.
def test_secrets_list_server_not_reachable(): message = "REANA client is not connected to any REANA cluster." reana_token = "000000" runner = CliRunner() result = runner.invoke(cli, ["secrets-list", "-t", reana_token]) assert result.exit_code == 1 assert message in result.output
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def list_secrets(self):\n pass", "def test_read_namespaced_secret_list_secrets(self):\n pass", "def test_secrets_list_server_no_token():\n message = \"Please provide your access token\"\n env = {\"REANA_SERVER_URL\": \"localhost\"}\n runner = CliRunner(env=env)\n result = runner...
[ "0.7848596", "0.77356535", "0.73634505", "0.71850795", "0.7145914", "0.6926122", "0.674381", "0.655007", "0.64121014", "0.639309", "0.6267915", "0.6263949", "0.6144681", "0.61244977", "0.6104293", "0.6090162", "0.6053545", "0.60486376", "0.601324", "0.59840655", "0.59817785",...
0.77385426
1
Test list secrets when access token is not set.
def test_secrets_list_server_no_token(): message = "Please provide your access token" env = {"REANA_SERVER_URL": "localhost"} runner = CliRunner(env=env) result = runner.invoke(cli, ["secrets-list"]) assert result.exit_code == 1 assert message in result.output
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_read_namespaced_secret_list_secrets(self):\n pass", "def test_check_secrets(self):\n secrets.check_secrets([], argparse.Namespace())", "def test_secrets_list_server_not_reachable():\n message = \"REANA client is not connected to any REANA cluster.\"\n reana_token = \"000000\"\n ...
[ "0.71583724", "0.697432", "0.6764023", "0.6734302", "0.657616", "0.6429628", "0.63544613", "0.6260767", "0.6180775", "0.61721295", "0.61655974", "0.6159696", "0.6127158", "0.6099549", "0.60978544", "0.60681677", "0.60320014", "0.60044026", "0.59975713", "0.59924906", "0.59404...
0.77104926
0
Test list secrets successfull.
def test_secrets_list_ok(): status_code = 200 response = [{"name": "password", "type": "env"}] env = {"REANA_SERVER_URL": "localhost"} mock_http_response, mock_response = Mock(), Mock() mock_http_response.status_code = status_code mock_response = response reana_token = "000000" runner = CliRunner(env=env) with runner.isolation(): with patch( "reana_client.api.client.current_rs_api_client", make_mock_api_client("reana-server")(mock_response, mock_http_response), ): result = runner.invoke(cli, ["secrets-list", "-t", reana_token]) assert result.exit_code == 0 assert "password" in result.output assert "env" in result.output
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def list_secrets(self):\n pass", "def test_read_namespaced_secret_list_secrets(self):\n pass", "def test_secrets_list_server_no_token():\n message = \"Please provide your access token\"\n env = {\"REANA_SERVER_URL\": \"localhost\"}\n runner = CliRunner(env=env)\n result = runner...
[ "0.7842545", "0.7786088", "0.7250055", "0.7128142", "0.70077723", "0.69276756", "0.6661624", "0.6632881", "0.64265823", "0.640965", "0.64062554", "0.6279332", "0.6268154", "0.6260419", "0.6230832", "0.6193241", "0.6184802", "0.6167017", "0.6167011", "0.6167011", "0.6139364", ...
0.74387324
2
Test adding secrets with wrong format.
def test_secrets_add_wrong_format(secret): reana_token = "000000" env = {"REANA_SERVER_URL": "localhost"} runner = CliRunner(env=env) message = 'For literal strings use "SECRET_NAME=VALUE" format' result = runner.invoke(cli, ["secrets-add", "-t", reana_token, "--env", secret]) assert result.exit_code == 1 assert message in result.output
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_check_secrets(self):\n secrets.check_secrets([], argparse.Namespace())", "def test_generate_secret(self):\n random_secret = ef_password.generate_secret(24)\n self.assertEqual(len(random_secret), 24)\n assert not set('[~!@#$%^&*()_+{}\":;\\']+$').intersection(random_secret)", "def test_...
[ "0.75044936", "0.707541", "0.70254934", "0.6977966", "0.67734826", "0.67173374", "0.6702236", "0.66481084", "0.6610407", "0.6495734", "0.642665", "0.6363775", "0.63510156", "0.6331783", "0.6269925", "0.6216668", "0.6207249", "0.61964357", "0.61894506", "0.6124794", "0.6116386...
0.8482589
0
Test adding secrets when they already exist.
def test_secrets_add_already_exist(): status_code = 409 reana_token = "000000" env = {"REANA_SERVER_URL": "localhost"} message = "One of the secrets already exists. No secrets were added." mock_http_response = Mock( status_code=status_code, reason="Conflict", json=Mock(return_value={"message": "Conflict"}), ) rs_api_client_mock = Mock() rs_api_client_mock.api.add_secrets = Mock(side_effect=HTTPError(mock_http_response)) runner = CliRunner(env=env) with runner.isolation(): with patch("reana_client.api.client.current_rs_api_client", rs_api_client_mock): result = runner.invoke( cli, ["secrets-add", "-t", reana_token, "--env", "USER=reanauser"] ) assert message in result.output assert result.exit_code == 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_check_secrets(self):\n secrets.check_secrets([], argparse.Namespace())", "def test_secret(self, env: yaenv.Env):\n assert env.secret() == 'notsosecret'\n assert 'NEW_SECRET_KEY' not in env\n _secret = env.secret('NEW_SECRET_KEY')\n assert _secret is not None\n a...
[ "0.7291631", "0.7147517", "0.6715984", "0.6684597", "0.66473454", "0.66376173", "0.6494984", "0.6443271", "0.6437272", "0.6393369", "0.629985", "0.6255083", "0.62139803", "0.61440545", "0.602208", "0.5996874", "0.5979041", "0.5953571", "0.59042215", "0.58320487", "0.58229697"...
0.7203451
1
Optimized version of the generic paginate_query_across_partitioned_databases for case schedules queue_schedule_instances uses a lock to ensure that the same case_id cannot be queued within one hour of another instance The celery tasks handle_case_alert_schedule_instance and handle_case_timed_schedule_instance both use locks to ensure only one taks is operating on a case at one time. Each task also checks if the schedule is still valid on this case before processing it further Assumes that q_expression includes active = True
def _paginate_query_across_partitioned_databases(model_class, q_expression, load_source): from corehq.messaging.scheduling.scheduling_partitioned.models import ( CaseAlertScheduleInstance, CaseTimedScheduleInstance, ) if model_class not in (CaseAlertScheduleInstance, CaseTimedScheduleInstance): raise TypeError("Expected CaseAlertScheduleInstance or CaseTimedScheduleInstance") db_names = get_db_aliases_for_partitioned_query() for db_name in db_names: for row in _paginate_query(db_name, model_class, q_expression, load_source): yield row
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def scheduling_method(self, cur_time, es, es_dict):\n dispatching_plan = []\n\n resource_types = self.resource_manager.resource_types\n avl_resources = self.resource_manager.current_availability\n system_capacity = self.resource_manager.system_capacity('nodes')\n\n # ============...
[ "0.5548428", "0.5151464", "0.48518416", "0.47420847", "0.46796945", "0.46776414", "0.4667777", "0.4659418", "0.46430779", "0.46141425", "0.45946392", "0.45765543", "0.4571356", "0.45686328", "0.45587033", "0.45582697", "0.4556789", "0.45445147", "0.454312", "0.4534792", "0.45...
0.62616307
0
Exponential Linear Unit function.
def elu(x, alpha=1.0): # https://github.com/muupan/chainer-elu return ELU(alpha=alpha)(x)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def exponential(value):\n return math.exp(value)", "def calculate_exponent():\n pass", "def exp(x):\n raise NotImplementedError", "def inverse_exponential(x):\n return math.exp(-x)", "def exponential(self) -> np.ndarray:\n if self.is_real():\n return np.array([1.0,...
[ "0.6901193", "0.68407923", "0.6819991", "0.6726578", "0.667672", "0.66451716", "0.66354614", "0.6521205", "0.6373172", "0.6362633", "0.6341832", "0.6321374", "0.6235829", "0.6235829", "0.6159893", "0.6137865", "0.61260146", "0.6114578", "0.61126935", "0.60865015", "0.6084545"...
0.6120061
17
Rearrange Array Elements so as to form two number such that their sum is maximum.
def rearrange_digits(input_list): ## Corner cases: if len(input_list) == 0: return [0, 0] elif len(input_list) == 1: return [input_list[0], 0] # Sort an array using merge-sort sorted_list = merge_sort(input_list) # Create two empty array and pop largest number from an sorted_list # and push into each empty array one by one # This also ensures that the number of digits in both the numbers cannot differ by more than 1 first_num_list = list() second_num_list = list() while sorted_list: first_num_list.append(sorted_list.pop()) # Break the while loop if array is empty if not sorted_list: break second_num_list.append(sorted_list.pop()) first_num = int("".join(str(i) for i in first_num_list)) second_num = int("".join(str(i) for i in second_num_list)) # Create an output array of two nums out_list = [] out_list.append(first_num) out_list.append(second_num) return out_list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def max_pairwise_product_sort(array):\n if len(array) <= 1:\n return 0\n\n array.sort()\n\n return array[-1] * array[-2]", "def max_pairwise_product_linear(array):\n\n if len(array) <= 1:\n return 0\n\n two_biggest_values = [0, 0]\n\n for element in array:\n if element > tw...
[ "0.714988", "0.6825663", "0.65861666", "0.65528435", "0.6125746", "0.61184865", "0.611382", "0.60502493", "0.6019517", "0.5999914", "0.5950047", "0.5939359", "0.58605045", "0.5847725", "0.5821236", "0.58049685", "0.57983345", "0.576433", "0.57470614", "0.574322", "0.5742154",...
0.56220305
31
This method is used to terminate a job with the specified or a group of jobs job_id or job_name in a given cluster
def delete(cls, cluster, job, group=None): try: if group is not None: # get the job ids from the db arguments = {'cluster': cluster, 'group': group} db_jobs = cls.cm.find('batchjob', **arguments) list1 = [] for i in db_jobs: list1.append(db_jobs[i]['job_id']) # read active jobs active_jobs = json.loads(cls.queue(cluster)) list2 = [] for i in active_jobs: list2.append(active_jobs[i]['jobid']) # find intersection res = set(list1).intersection(set(list2)) if res is not None: for j in res: cmd = 'scancel {}'.format(str(j)) Shell.ssh(cluster, cmd) print("Deleted {}".format(j)) return "All jobs for group {} killed successfully".format(group) else: args = 'scancel ' if job.isdigit(): args += job else: args += "-n {}".format(job) Shell.ssh(cluster, args) return "Job {} killed successfully".format(job) except Exception as ex: print("in exceptio") print(ex) return ex
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def terminate(ctx):\n ctl = ctx.ctl\n jobs = ctl('list-avail', '--partition', 'main', flatten=False)\n\n for job in jobs:\n jobid = job['id']\n click.echo('Terminating {}'.format(jobid))\n ctl('terminate', '--jobid', jobid)", "def kill_job(self, job):\n\n if job.status == Job...
[ "0.69394773", "0.6439822", "0.6429004", "0.63975894", "0.6377325", "0.6343466", "0.6278735", "0.62779915", "0.62628543", "0.61729574", "0.6161055", "0.61369205", "0.6120452", "0.61027503", "0.60934454", "0.60848886", "0.60653436", "0.6043757", "0.5999601", "0.5956319", "0.595...
0.7375492
0
Constructor to create instance of the Line object.
def __init__(self, p1=None, p2=None, tolerance=None, l=None): if l is None: p1_arr = np.array(p1, dtype=float) p2_arr = np.array(p2, dtype=float) delta = p2_arr - p1_arr norm2 = delta[0] ** 2 + delta[1] ** 2 + delta[2] ** 2 norm1 = np.math.sqrt(norm2) if norm2 == 0: raise Exception("Norm is zero!") # Line direction. self.direction = delta / norm1 # Line point closest to the origin. self.zero = p1_arr - np.dot(p1_arr, delta) / norm2 # Tolerance below which points are considered identical. self.tolerance = 1e-10 if tolerance is None else tolerance else: # Tolerance below which points are considered identical. self.tolerance = l.tolerance # Line direction. self.direction = l.direction # Line point closest to the origin. self.zero = l.zero
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, vertices, **kwargs):\n super(Line, self).__init__(vertices, **kwargs)\n self._geotype = \"Line\"\n return", "def __init__(self, start, end, oldLine = None):\n self.__start = start\n self.__end = end\n if(self.__start == self.__end):\n \"\"\"...
[ "0.80231184", "0.7601697", "0.7555074", "0.74823064", "0.74259686", "0.73953325", "0.7313491", "0.6963556", "0.69590884", "0.6912488", "0.69103134", "0.68802094", "0.6859208", "0.6848757", "0.68076146", "0.6779403", "0.674837", "0.674837", "0.6747915", "0.6672266", "0.6634589...
0.65474164
23
Function to set the tolerance.
def set_tolerance(self, tol): self.tolerance = tol
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tolerance(self, tolerance: float) -> None:\n self._tolerance = tolerance", "def set_tolerance(self, value):\n\n self._tolerance = value", "def set_tolerance(self, tol):\n self.precision = tol\n return", "def tol(self, value):\n self._tol = value", "def set_tol(self, t...
[ "0.8269015", "0.81052655", "0.79584485", "0.7956575", "0.78157336", "0.7737034", "0.7723517", "0.76122135", "0.7429519", "0.7174162", "0.71566623", "0.7126722", "0.7088782", "0.68695533", "0.6833426", "0.676617", "0.66971606", "0.668103", "0.66773707", "0.665312", "0.6650963"...
0.8542296
0
Function to get the tolerance. Returns
def get_tolerance(self): return self.tolerance
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tolerance(self):\n return self.params['tolerance']", "def tolerance(self):\n return self._tolerance", "def tolerance(self) -> float:\n return self._tolerance", "def tol(self):\n return self._tol", "def get_tolerance(self):\n\n if Test.global_tolerance is None:\n ...
[ "0.8676137", "0.8571045", "0.84762627", "0.8150256", "0.8027628", "0.80256224", "0.7848701", "0.7472672", "0.73756516", "0.7373416", "0.71266186", "0.69214386", "0.6822433", "0.6734726", "0.6684235", "0.6613367", "0.6550089", "0.6541348", "0.6453469", "0.63813984", "0.6317363...
0.8477005
2
Function to revert the direction of the current line. Returns
def revert(self): reverted = Line(l=self) reverted.direction *= -1.0 return reverted
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fliped(self):\n return Line(self.end, self.start, self)", "def reversed(self):\n return LINE(*self.elems,**{'reverse':(not self.reverse)})", "def _inverse_lines(self):\n pass", "def revert(self, *args, **kwargs):", "def _backup_line(self):\n if self._orig_line is None:\n ...
[ "0.68525314", "0.6473832", "0.64653385", "0.64345104", "0.64087176", "0.6327431", "0.6293631", "0.6287279", "0.62672716", "0.6193143", "0.6137352", "0.61128193", "0.6102303", "0.60842335", "0.60765207", "0.6057564", "0.60540533", "0.60380507", "0.6030797", "0.60029155", "0.59...
0.85526377
0
Function to get the direction of the line. Returns
def get_direction(self): return self.direction
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_direction(self):\n return self.actual_coordinates[2]", "def get_direction(self):\r\n return self.__direction", "def direction(self):\n return atan2d(self.y, self.x)", "def getDirection(self):\n return self.ray.direction", "def direction(self):\r\n return 180 - ata...
[ "0.7764746", "0.74921775", "0.74461246", "0.7236827", "0.7222495", "0.7183815", "0.7064334", "0.7050146", "0.7007524", "0.69288164", "0.69204354", "0.69024444", "0.6901476", "0.6863641", "0.6818004", "0.67975605", "0.67823666", "0.6723684", "0.6717148", "0.67071515", "0.66958...
0.7374277
3
Get the line point closest to the origin. Returns
def get_origin(self): return self.zero
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def closest(self, x):\n # http://www.ahinson.com/algorithms_general/Sections/Geometry/PluckerLine.pdf\n # has different equation for moment, the negative\n\n x = arg.getvector(x, 3)\n\n lam = np.dot(x - self.pp, self.uw)\n p = self.point(lam) # is the closest point on the line\n...
[ "0.752301", "0.741795", "0.73585206", "0.7312732", "0.7232914", "0.71674716", "0.71045464", "0.69818723", "0.6970222", "0.69567466", "0.6912792", "0.6912227", "0.68720096", "0.67963266", "0.67862755", "0.6759423", "0.67402595", "0.6738672", "0.67113775", "0.67095816", "0.6697...
0.0
-1
Function to get the abscissa of a point with respect to a line. The abscissa is 0 if the projection of the point and the projection of the frame origin on the line are the same point.
def get_abscissa(self, p): return np.dot(p - self.zero, self.direction)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_line_to(self, point):\n\n b = ((self.x - point.x)*point.y - (self.y - point.y)*point.x)/(self.x - point.x)\n\n a = (self.y - point.y)/(self.x - point.x)\n\n return a, b", "def _dist_point2line(self, point: ndarray,\n line: Tuple[ndarray, ndarray]) -> ndarray:\...
[ "0.659462", "0.6087625", "0.6012542", "0.59856695", "0.58890575", "0.58882195", "0.5846869", "0.5727574", "0.57215995", "0.57181567", "0.57152516", "0.56363255", "0.5614506", "0.5601204", "0.55724233", "0.55630857", "0.55362034", "0.5515001", "0.5511656", "0.55000144", "0.548...
0.6117362
1
Function to get one point from the line.
def point_at(self, abscissa): return self.zero + abscissa * self.direction
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pick_point_not_on_line(line: Line):\n return line.point1 + line.get_perpendicular_at_point(line.point1).get_direction_vector()", "def get_line_to(self, point):\n\n b = ((self.x - point.x)*point.y - (self.y - point.y)*point.x)/(self.x - point.x)\n\n a = (self.y - point.y)/(self.x - point....
[ "0.7592827", "0.7068464", "0.6940365", "0.6910205", "0.6897533", "0.68894476", "0.6816368", "0.6789263", "0.67315537", "0.6678987", "0.66766155", "0.66728306", "0.66517955", "0.66410375", "0.663569", "0.6616116", "0.6613046", "0.65880394", "0.6556479", "0.6535376", "0.6529306...
0.0
-1
Function to check if the instance contains a point.
def contains(self, p): return self.distance(p=p) < self.tolerance
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __contains__(self, point: Point[Scalar]) -> bool:\n return point in self._points_set", "def __contains__(self, point: Point2D) -> bool:\n raise NotImplementedError", "def contains_point(self, point) -> bool:\n return (self.pos.x <= point[0] <= self.pos.x + self.size.x and\n ...
[ "0.80940896", "0.79766035", "0.7874318", "0.7752589", "0.77207327", "0.76728505", "0.7655251", "0.7603095", "0.7503402", "0.7494675", "0.7432554", "0.740622", "0.74035716", "0.73980653", "0.73448753", "0.72807014", "0.7261856", "0.7195358", "0.7172193", "0.7149684", "0.712169...
0.0
-1
Function to compute the distance between the instance and a point or the shortest distance between the instance and another line.
def distance(self, p=None, l=None): if l is None: d = p - self.zero n = np.zeros(3) # try: # n = d - np.dot(d, self.direction) * self.direction # except RuntimeWarning: # print(d, self.direction) # return norm(n) with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") n = d - np.dot(d, self.direction) * self.direction # print(n, norm(n)) if len(w) > 0 and issubclass(w[-1].category, RuntimeWarning): # Todo: check w/ Ram if this is what he meant to do when catch a warning: n = np.zeros(3) # n = np.zeros(3) # print(d, self.direction) pass return norm(n) else: normal = np.cross(self.direction, l.direction) n = norm(normal) if n < sys.float_info.min: # Lines are parallel. return self.distance(p=l.zero) offset = np.dot(l.zero - self.zero, normal) / n return np.abs(offset)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _distance(point, line_point1, line_point2):\n vec1 = line_point1 - point\n vec2 = line_point2 - point\n distance = np.abs(np.cross(vec1,vec2)) / np.linalg.norm(line_point1-line_point2)\n return distance", "def _distance_to_line(begin, end, point):\n return _vec_...
[ "0.7641407", "0.7141231", "0.70598394", "0.7000537", "0.6959461", "0.69434446", "0.6942349", "0.68482417", "0.6793337", "0.6758447", "0.67557317", "0.67258215", "0.6696894", "0.6693597", "0.6688431", "0.66852915", "0.6680149", "0.6679827", "0.6665373", "0.6638376", "0.6632367...
0.63587475
62
Function to compute the distance squared between the instance and a point.
def distance_sq(self, p): d = p - self.zero n = d - np.dot(d, self.direction) * self.direction return n[0] ** 2 + n[1] ** 2 + n[2] ** 2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def squared_distance(self, point: List[int]) -> int:\n return point[0] ** 2 + point[1] ** 2", "def squaredDistanceTo(self,other):\n if not isinstance(other,Point):\n return \n return (self.longitude - other.getLongitude())**2 +(self.latitude - other.getLatitude())**2", "def eucl...
[ "0.78861135", "0.7388568", "0.7332369", "0.7102426", "0.7052089", "0.70430666", "0.703139", "0.6993221", "0.69181925", "0.6889745", "0.6863204", "0.6794171", "0.6785468", "0.6758498", "0.67438406", "0.6737052", "0.67257434", "0.6707908", "0.6706913", "0.67060155", "0.67053574...
0.6738073
15
Function to the compute the point of the instance closest to another line.
def closest_point(self, l): cos = np.dot(self.direction, l.direction) n = 1 - cos ** 2 if n < sys.float_info.epsilon: # Lines are parallel. return self.zero d0 = l.zero - self.zero a = np.dot(d0, self.direction) b = np.dot(d0, l.direction) return self.zero + self.direction * ( a - b * cos) / n
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def closest_point_on_line(point, line):\n a, b = line\n ab = subtract_vectors(b, a)\n ap = subtract_vectors(point, a)\n c = vector_component(ap, ab)\n return add_vectors(a, c)", "def closest(self, x):\n # http://www.ahinson.com/algorithms_general/Sections/Geometry/PluckerLine.pdf\n #...
[ "0.79727983", "0.7753009", "0.7605306", "0.7497314", "0.7443135", "0.7417121", "0.7388166", "0.7367654", "0.71200454", "0.71104366", "0.7108977", "0.7068614", "0.7057041", "0.7001261", "0.6992348", "0.6936836", "0.6908155", "0.6904385", "0.6875017", "0.6862292", "0.6801013", ...
0.7502959
3
Function to compute the intersection point of the instance and another line.
def intersection(self, l): closest = self.closest_point(l) return closest if l.contains(closest) else None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _lines_intersection(self, other):\n\n the_slope, the_y_intercept = False, False\n\n # parallel?\n if self.slope == other.slope:\n return (\n self.y_intercept == other.y_intercept and\n self.x_value == other.x_value\n )\n\n if self.is_vertical():\n ...
[ "0.7900334", "0.78217113", "0.7766068", "0.7715372", "0.76640767", "0.7580761", "0.7566446", "0.7503989", "0.7500533", "0.7499418", "0.74659604", "0.7449178", "0.74213684", "0.7360603", "0.734246", "0.7337199", "0.7291764", "0.7291017", "0.71756595", "0.7140106", "0.7113183",...
0.0
-1
Call the Translation API hosted on the micropayments server.
def cli(text): #click.echo("Welcome to the Instant Translation Command Line Tool.\n") sel_url = server_url+'translate?text={0}&payout_address={1}' response = requests.get(url=sel_url.format(text, wallet.get_payout_address())) #click.echo("The following is the translation of the text you input.\n") click.echo(response.text)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def machine_translation(request):\n log.debug(\"Get translation from machine translation service.\")\n\n try:\n text = request.GET['text']\n locale = request.GET['locale']\n check = request.GET['check']\n except MultiValueDictKeyError as e:\n log.error(str(e))\n return H...
[ "0.704143", "0.69701964", "0.6816958", "0.66153824", "0.642939", "0.63775456", "0.62047935", "0.61574394", "0.6141896", "0.61338365", "0.60861075", "0.6081854", "0.6030524", "0.5947659", "0.5792178", "0.5742774", "0.57173043", "0.56933045", "0.56787753", "0.56550264", "0.5653...
0.6338963
6
Makes a new account and adds it into the database.
def create_account(): if not request.json or not 'name' in request.json: abort(400) account = { 'id': accounts[-1]['id'] + 1, #last id + 1 'name': request.json['name'], 'surname': request.json['surname'], 'product': request.json.get('product', ""), 'balance': request.json.get('balance', 0.00) } accounts.append(account) return json.dumps({'New Account': account}, ensure_ascii=False), 201, {'Content-Type': 'text/css; charset=utf-8'}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_user(self) -> None:\n # update when the account was created\n self.account_created = datetime.now().date()\n self.insert_to_db()\n log(f\"An account for User:{self.id} has been created.\")", "def create(self, account):\n model = models.load('Account', account)\n\n ...
[ "0.8021572", "0.750744", "0.74803704", "0.7311251", "0.72799855", "0.724296", "0.72236335", "0.71949494", "0.7147477", "0.7138259", "0.7131161", "0.7060654", "0.704185", "0.6993125", "0.6962196", "0.6949189", "0.6949064", "0.6937117", "0.6913708", "0.68980956", "0.6873912", ...
0.7375597
3
Makes deposit/withdrawal from an account and updates balance.
def make_transaction(): account_id = request.json['account_id'] aux_account = [account for account in accounts if account['id'] == account_id] if len(aux_account) == 0: abort(404) account_balance = Decimal(aux_account[0].get('balance')).quantize(Decimal('0.00')) transaction = request.json['transaction'] transaction_amount = Decimal(abs(request.json['amount'])).quantize(Decimal('0.00')) if not request.json: abort(400) if transaction not in ['withdrawal', 'deposit']: abort(400, f'Invalid transaction name: {transaction}') if transaction == 'withdrawal': transaction_amount = transaction_amount*-1 # the user can't withdraw more than the account has validation_sum = (account_balance + transaction_amount).quantize(Decimal('.01'), rounding=ROUND_DOWN) if validation_sum >= 0: for real_account in accounts: if real_account.get('id') == account_id: real_account['balance'] = round(float(validation_sum),2) else: abort(400, {'error':'Not enough funds for this transaction'}) return json.dumps({f'{transaction.capitalize()} Done. New balance': str(validation_sum)}, ensure_ascii=False), 200
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def deposit(account, amount):\n pass", "def deposit(self, amount):\n self.balance += amount", "def deposit(self, amount):\n self.balance += amount", "def deposit(self, deposit_money):\r\n self.balance += deposit_money", "def deposit(self, amount):\n self.balance += amount\n ...
[ "0.7868934", "0.7839314", "0.7839314", "0.7767801", "0.7667896", "0.75666636", "0.75089145", "0.75089145", "0.75089145", "0.74225825", "0.7420341", "0.741208", "0.7388114", "0.7388107", "0.73456854", "0.72894204", "0.7286367", "0.72752404", "0.7254404", "0.72427124", "0.72236...
0.6433212
81
Gets the details from an account.
def get_account(): account_id = request.json['id'] account = [account for account in accounts if account['id'] == account_id] if len(account) == 0: abort(404, 'Account not found') return json.dumps(account[0], ensure_ascii=False), 200, {'Content-Type': 'text/css; charset=utf-8'}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_account_details(self):\n pass", "def get_account_info(self):\n resp = requests.get(\n self.URL + 'info/',\n headers={'Authorization': 'Token ' + self.api_key}\n )\n\n return self.__handle_response(resp)", "def get_account_details(account_id, writer, key...
[ "0.8391992", "0.7705361", "0.76916474", "0.76766896", "0.7665401", "0.7580927", "0.7388152", "0.7283165", "0.6980997", "0.6968043", "0.6938249", "0.6916687", "0.6901691", "0.6892927", "0.6841231", "0.6769148", "0.6728201", "0.67043024", "0.6670262", "0.6635612", "0.6632791", ...
0.6153258
42
Checks the availability of the service.
def health_check(): now = datetime.datetime.now() return make_response(jsonify({'Alive': f'{now.strftime("%Y-%m-%d %H:%M")}'}), 200)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_availability(self):\n pass", "def print_service_available():\n if WithingsDataManager.service_available is not True:\n _LOGGER.info(\"Looks like the service is available again\")\n WithingsDataManager.service_available = True\n return True", "def is_avai...
[ "0.7628735", "0.74451256", "0.7004689", "0.6775977", "0.67273784", "0.66786855", "0.6657399", "0.65845925", "0.6574978", "0.65488654", "0.6541251", "0.6489893", "0.6482576", "0.64753973", "0.63969254", "0.63804036", "0.6367508", "0.6347607", "0.6273594", "0.62443465", "0.6236...
0.0
-1
Handles errors from the requests gotten from clients
def not_found(error): return make_response(jsonify({'error': 'Resource not found'}), 404)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handle_error(self, request_handler, client_address):\n logger.debug('handle_error(%s:%s)' % client_address)", "def handle_error(self, request, client_address):\n\t\tprint '-'*40\n\t\tprint 'Exception happened during processing of request from',\n\t\tprint client_address\n\t\timport traceback\n\t\ttrac...
[ "0.71784735", "0.71308863", "0.71102184", "0.70657563", "0.7006739", "0.6947597", "0.68516433", "0.6658565", "0.6613221", "0.65786", "0.6538273", "0.6400244", "0.63673776", "0.6355248", "0.63404506", "0.63398343", "0.63361794", "0.6322117", "0.6317077", "0.63164055", "0.63140...
0.0
-1
Upload File on Streamlit Code
def run(self): st.title('Acne Classifier') st.markdown(STYLE, unsafe_allow_html=True) file = st.file_uploader("Upload file", type=self.fileTypes) show_file = st.empty() if not file: show_file.info("Please upload a file of type: " + ", ".join(["png", "jpg"])) return file_bytes = np.asarray(bytearray(file.read()), dtype=np.uint8) opencv_image = cv2.imdecode(file_bytes, 1) cv2.imwrite('out.jpg', opencv_image) df = get_score() df2 = df.set_index('Issue') st.dataframe(df2) st.bar_chart(df2) if isinstance(file, BytesIO): show_file.image(file) else: data = pd.read_csv(file) st.dataframe(data.head(10)) file.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def upload():\n\treturn render_template(\"upload.html\", title=\"Upload a file\")", "def upload_file(self, file_path, file_name, output_path):", "def upload():\n\n file = request.files['query']\n filepath = upload_filepath(secure_filename(file.filename))\n file.save(filepath)\n classification = cla...
[ "0.6423938", "0.63981605", "0.63896406", "0.6386179", "0.6256276", "0.62473285", "0.62320954", "0.62008077", "0.6166157", "0.61652756", "0.6073021", "0.5995549", "0.59897304", "0.5989222", "0.5944204", "0.59314686", "0.5905269", "0.5904682", "0.5895401", "0.5894111", "0.58836...
0.0
-1
Denormalizes image tensors using mean and std
def denormalize(tensors): if len(tensors.shape) < 4: for c in range(3): tensors[c, ...].mul_(std[c]).add_(mean[c]) else: for c in range(3): tensors[:, c].mul_(std[c]).add_(mean[c]) return torch.clamp(tensors, 0, 255)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def un_normalize(tensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):\n mean = torch.FloatTensor(mean).view(1,3,1,1)\n std = torch.FloatTensor(std).view(1,3,1,1)\n \n image = tensor.cpu().detach()\n image = image*std+mean\n image = image.numpy()\n \n image = np.transpose(image, (...
[ "0.78944635", "0.7882652", "0.7882652", "0.78073585", "0.7707587", "0.75766003", "0.75766003", "0.75701815", "0.7559962", "0.75194675", "0.75118655", "0.74785763", "0.73548406", "0.7345986", "0.73086804", "0.72494674", "0.72197634", "0.71848446", "0.7110974", "0.7100263", "0....
0.765841
5
Get the status code as per ttype and it's status_val
def get_status_code(self, ttype, status_val) -> str: # get the status code from __status_code or __default_code pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def status_code(self):\n return int(self.status.split()[1])", "def get_status_code(status):\n return dict(const.STATUS_CODES).get(status)", "def status_code(self):\r\n return int(self._status[:3])", "def status_code(self):\n return int(self._status[:3])", "def _parse_status(self...
[ "0.7202656", "0.71696675", "0.7097821", "0.6938727", "0.68742913", "0.68445003", "0.68133837", "0.6747887", "0.67144114", "0.6705535", "0.662726", "0.6622442", "0.6621217", "0.66081154", "0.6606708", "0.6606708", "0.6598715", "0.65756345", "0.65702355", "0.65538526", "0.65501...
0.86103326
0
To check if payload to be processed with this lambda
def apply_filter(self, payload: dict, ainfos) -> (dict, dict): # check if needs to process by this lambda pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def verify_payload():\n return True", "def process(self, payload, status_code=0):", "def has_payload(self):\n\n if self._payload:\n return True\n return False", "def __should_payload_execute(self, queue_item):\n\n soup = queue_item.get_soup_response()\n\n ng_app_...
[ "0.6974256", "0.6329951", "0.6317524", "0.5889682", "0.58806306", "0.5717963", "0.57109547", "0.56970483", "0.56970483", "0.56906414", "0.566029", "0.55937403", "0.5567957", "0.5565435", "0.5472518", "0.5453765", "0.5410358", "0.54089427", "0.53794", "0.5371008", "0.53691435"...
0.66218215
1
Process Kinesis Record and save to Redis Cache
def enrich_payload(self, payload) -> None: filtered_payloads = self.apply_filter(payload) enriched = self.enrich(filtered_payloads) return enriched
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handler(kinesis_records, context):\n data = kinesis_records[0].parse()\n detail = data.get('detail')\n return publish({\n \"eventSource\": data['source'],\n \"awsRegion\": data['region'],\n \"eventTime\": data['time'],\n \"eventName\": detail['eventName'],\n \"userId...
[ "0.60701543", "0.60549337", "0.58346707", "0.58061445", "0.57601625", "0.56928015", "0.5668168", "0.56287974", "0.5627504", "0.55000585", "0.54971075", "0.545186", "0.5447746", "0.5404357", "0.5392328", "0.5323944", "0.5304658", "0.52952385", "0.52630335", "0.52459717", "0.52...
0.0
-1
Use ansi code on 'string' if the output is the terminal of a not Windows platform
def isSpecial(ansiCode,string): if IS_TERMINAL and not IS_WIN32: return ansiCode+string+ANSI_END else: return string
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def b(string):\n return \"\\033[94m{0}\\033[0m\".format(string)", "def ansi(color, text):\r\n code = COLOR_CODES[color]\r\n return '\\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)", "def ansi_escape(text: object) -> str:\n return str(text).replace(\"\\x1b\", \"?\").replace(\"\\b\", \"?\")", ...
[ "0.698737", "0.6955122", "0.68967116", "0.6775408", "0.67163545", "0.6666538", "0.6612062", "0.6594532", "0.6576787", "0.6540611", "0.6525283", "0.6465225", "0.6419213", "0.6390745", "0.6369478", "0.63463056", "0.6337062", "0.6330112", "0.6313778", "0.6313092", "0.6297528", ...
0.771174
0
Sort list of TKey by their names ignoring the case
def keyListSort(keyList): keyList.sort(key=lambda y: y.GetName().lower())
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sortCaseInsensitive(*args, **kwargs)->List[AnyStr]:\n pass", "def sort_by_name(list_to_sort):\n return sorted(\n list_to_sort,\n key=lambda k: k['Name'].lower()\n )", "def natsort_icase(lst: List[str]) -> None:\n lst.sort(key=natsort_key_icase)", "def human_sort(l):\n l.sort(...
[ "0.7360461", "0.7314273", "0.6833507", "0.67649287", "0.66534966", "0.6629779", "0.6619612", "0.6566453", "0.65517783", "0.6549519", "0.6549519", "0.65458226", "0.65365845", "0.65276384", "0.6501143", "0.64999694", "0.64592296", "0.6409549", "0.6385534", "0.6382833", "0.63771...
0.818581
0
Sort list of tuple by their first elements ignoring the case
def tupleListSort(tupleList): tupleList.sort(key=lambda y: y[0].lower())
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _mySort(self, alist):\n return sorted(alist, key=lambda x: (x[0].isdigit(), x.lower()))", "def sort_list_of_tuples(list):\n list.sort(key=lambda x: x[0])\n return list", "def sortCaseInsensitive(*args, **kwargs)->List[AnyStr]:\n pass", "def natsort_case_insensitive(seq):\r\n return nat...
[ "0.70666724", "0.6958094", "0.6883425", "0.68414825", "0.6625755", "0.65509486", "0.64947134", "0.64417565", "0.6294914", "0.62795585", "0.6264345", "0.6251216", "0.6234281", "0.62279594", "0.62186223", "0.62157", "0.6190618", "0.6180634", "0.6172756", "0.61627626", "0.615647...
0.8253932
0
Use sys.stdout.write to write the string with an indentation equal to indent and specifying the end character
def write(string,indent=0,end=""): sys.stdout.write(" "*indent+string+end)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def indentOut_ (stream, indent) :\r\n if indent == 0 :\r\n return\r\n else :\r\n stream.write(\" \"*indent)", "def out_indent(indent, *args):\n s = \"\"\n s += indent * \" \"\n s += \" \".join(args)\n return s", "def try_print_indent(self):\n if self.lasttoken[0] != lex.T...
[ "0.7758625", "0.6414926", "0.6342674", "0.6169035", "0.6082922", "0.59543496", "0.5942104", "0.5933664", "0.58904225", "0.5866938", "0.5845034", "0.5830857", "0.5830536", "0.5825642", "0.5822062", "0.58123285", "0.58008015", "0.5715586", "0.5666716", "0.5651807", "0.56485546"...
0.8376877
0
Print recursively tree informations
def recursifTreePrinter(tree,indent): listOfBranches = tree.GetListOfBranches() if len(listOfBranches) > 0: # Width informations maxCharName = max([len(branch.GetName()) \ for branch in listOfBranches]) maxCharTitle = max([len(branch.GetTitle()) \ for branch in listOfBranches]) dic = { \ "nameWidth":maxCharName+2, \ "titleWidth":maxCharTitle+4, \ "memoryWidth":1} for branch in listOfBranches: # Print loop rec = \ [branch.GetName(), \ "\""+branch.GetTitle()+"\"", \ str(branch.GetTotBytes())] write(TREE_TEMPLATE.format(*rec,**dic),indent,end="\n") recursifTreePrinter(branch,indent+2)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def print_tree(self):\n\t\tprint(self.__print_tree('', True, ''))", "def print_tree(self):\n\t\tself.root.print_recursive(0)", "def printTree(self):\n print(printTreeF(self, 0, self))", "def print_tree(node):\n print tree(node)", "def print_tree(self):\n return \"\"", "def print_tree(sel...
[ "0.8600898", "0.8487803", "0.8312677", "0.8166421", "0.80248964", "0.8010252", "0.7947379", "0.7931171", "0.7874574", "0.78502697", "0.7842588", "0.7769115", "0.7767501", "0.7752166", "0.77449286", "0.7713288", "0.77115613", "0.7703568", "0.7699183", "0.76673025", "0.76467204...
0.7243111
39
Get time in the proper shape
def prepareTime(time): time = str(time) time = '000000'+time time = time[len(time)-6:] return time
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def time(self):\n return self.time_array", "def get_time(self) -> float:\n raise NotImplementedError()", "def get_time(self):\n start=''\n end=''\n time=''\n times=self.times\n print(times[self.istep])\n if self.istep > 0:\n start=ncEarth.begin...
[ "0.7274171", "0.70513386", "0.7026728", "0.69944495", "0.68678916", "0.68556535", "0.68395287", "0.68395287", "0.6821601", "0.679285", "0.67860985", "0.6783213", "0.6751718", "0.6702506", "0.66815585", "0.66815585", "0.66815585", "0.66792035", "0.6662519", "0.66364765", "0.66...
0.0
-1
Print a list of Tkey in columns
def roolsPrintLongLs(keyList,optDict,indent): if len(keyList) > 0: # Width informations maxCharClass = max([len(key.GetClassName()) for key in keyList]) maxCharTime = 12 maxCharName = max([len(key.GetName()) for key in keyList]) dic = { \ "classWidth":maxCharClass+2, \ "timeWidth":maxCharTime+2, \ "nameWidth":maxCharName+2, \ "titleWidth":1} date = ROOT.Long(0) for key in keyList: time = ROOT.Long(0) key.GetDatime().GetDateTime(key.GetDatime().Get(),date,time) time = prepareTime(time) rec = \ [key.GetClassName(), \ MONTH[int(str(date)[4:6])]+" " +str(date)[6:]+ \ " "+time[:2]+":"+time[2:4], \ key.GetName(), \ "\""+key.GetTitle()+"\""] write(LONG_TEMPLATE.format(*rec,**dic),indent,end="\n") if optDict['tree'] and isTreeKey(key): tree = key.ReadObj() recursifTreePrinter(tree,indent+2)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def print_table(data):\n for key in sorted(data):\n print \"%s: %s\" % (key.rjust(16), data[key])", "def show_table(self, keys=None, sort_keys_function=None):\n rows = []\n output_keys = keys or self.keys\n\n for item in self.__get_items(sort_keys_function):\n ro...
[ "0.69297874", "0.6871086", "0.6832247", "0.655662", "0.64423645", "0.63084143", "0.6236635", "0.6138035", "0.60768145", "0.6069733", "0.60688424", "0.60679513", "0.6044288", "0.60366815", "0.60195136", "0.59938", "0.5990676", "0.5981191", "0.59755695", "0.5975386", "0.5961205...
0.0
-1
getTerminalSize() get width and height of console works on linux,os x,windows,cygwin(windows)
def getTerminalSize(): current_os = platform.system() tuple_xy = None if current_os == 'Windows': tuple_xy = _get_terminal_size_windows() if tuple_xy is None: tuple_xy = _get_terminal_size_tput() # needed for window's python in cygwin's xterm! if current_os in ['Linux', 'Darwin'] or current_os.startswith('CYGWIN'): tuple_xy = _get_terminal_size_linux() if tuple_xy is None: #print "default" #_get_terminal_size_windows() or _get_terminal_size_tput don't work tuple_xy = (80, 25) # default value return tuple_xy
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_terminal_size_windows():\r\n\r\n\r\n #from https://gist.github.com/jtriley/1108174, thank you very much for this hard to produce code!\r\n\r\n # stdin handle is -10\r\n # stdout handle is -11\r\n # stderr handle is -12\r\n h = windll.kernel32.GetStdHandle(-12)\r\n csbi = create_string_bu...
[ "0.8626077", "0.8466061", "0.83579844", "0.82661015", "0.8189961", "0.8158154", "0.8115553", "0.8110067", "0.8009353", "0.79788095", "0.7913624", "0.78884804", "0.787112", "0.78315413", "0.7774899", "0.77129865", "0.7648327", "0.7609278", "0.760888", "0.7603599", "0.7578715",...
0.7640822
17
Print list of strings in columns blue for directories green for trees
def roolsPrintSimpleLs(keyList,indent): # This code is adaptated from the pprint_list function here : # http://stackoverflow.com/questions/25026556/output-list-like-ls # Thanks hawkjo !! if len(keyList) == 0: return (term_width, term_height) = getTerminalSize() term_width = term_width - indent min_chars_between = 2 min_element_width = min( len(key.GetName()) for key in keyList ) \ + min_chars_between max_element_width = max( len(key.GetName()) for key in keyList ) \ + min_chars_between if max_element_width >= term_width: ncol,col_widths = 1,[1] else: # Start with max possible number of columns and reduce until it fits ncol = min( len(keyList), term_width / min_element_width ) while True: col_widths = \ [ max( len(key.GetName()) + min_chars_between \ for j, key in enumerate(keyList) if j % ncol == i ) \ for i in range(ncol) ] if sum( col_widths ) <= term_width: break else: ncol -= 1 for i, key in enumerate(keyList): if i%ncol == 0: write("",indent) # indentation # Don't add spaces after the last element of the line or of the list if (i+1)%ncol != 0 and i != len(keyList)-1: if not IS_TERMINAL: write( \ key.GetName().ljust(col_widths[i%ncol])) elif isDirectoryKey(keyList[i]): write( \ isSpecial(ANSI_BLUE,key.GetName()).ljust( \ col_widths[i%ncol] + ANSI_BLUE_LENGTH)) elif isTreeKey(keyList[i]): write( \ isSpecial(ANSI_GREEN,key.GetName()).ljust( \ col_widths[i%ncol] + ANSI_GREEN_LENGTH)) else: write(key.GetName().ljust(col_widths[i%ncol])) else: # No spaces after the last element of the line or of the list if not IS_TERMINAL: write(key.GetName()) elif isDirectoryKey(keyList[i]): write(isSpecial(ANSI_BLUE, key.GetName())) elif isTreeKey(keyList[i]): write(isSpecial(ANSI_GREEN, key.GetName())) else: write(key.GetName()) write('\n')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show_directory_table(self):\n for row in range(self.directory_table.shape[0]):\n for column in range(self.directory_table.shape[1]):\n if column == self.directory_table.shape[1] - 1:\n print(self.directory_table[row][column])\n else:\n ...
[ "0.68927115", "0.62558967", "0.6205917", "0.611956", "0.5990437", "0.59898376", "0.59636194", "0.5947244", "0.5935697", "0.5933059", "0.59189725", "0.58366364", "0.58359617", "0.58307904", "0.5817027", "0.58034277", "0.579429", "0.577492", "0.5759573", "0.5752997", "0.5740480...
0.55308056
36
Print informations given by keyList with a rools style choosen with optDict
def roolsPrint(keyList,optDict,indent=0): if optDict['long'] or optDict['tree']: \ roolsPrintLongLs(keyList,optDict,indent) else: roolsPrintSimpleLs(keyList,indent)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def printDict(myDict):\n for key in myDict:\n print(f\"Version: --> {myDict[key]['version']} \")\n print(f\"Accuracy: --> {myDict[key]['accuracy']}\")\n print(f\"Time --> {myDict[key]['time_per_target']}\")\n print(f\"Penalty --> {myDict[key]['target_w_penalt...
[ "0.6518504", "0.6352941", "0.63204557", "0.6319985", "0.62665594", "0.61978984", "0.6115929", "0.6110398", "0.60612506", "0.59930515", "0.5966976", "0.59666437", "0.59666437", "0.59537727", "0.5947354", "0.59427744", "0.5914536", "0.5914091", "0.582117", "0.5819495", "0.58194...
0.7562387
0
Call back function which checks if two rectangles have collided with each other
def collide_hit_rect(first, second): return first.hit_rect.colliderect(second.hit_rect) or first.hit_rect.colliderect(second.hit_rect)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_overlapping(self, region):\n if self.x2 < region.x1:\n return False # this box is left the other\n if self.x1 > region.x2:\n return False # this box is right the other\n if self.y2 < region.y1:\n return False # this box is above the other\n if ...
[ "0.703403", "0.70215464", "0.7011669", "0.69918287", "0.69465554", "0.6939659", "0.6890335", "0.6829306", "0.68109834", "0.6809146", "0.679998", "0.67945856", "0.6788503", "0.67841524", "0.66956073", "0.66782784", "0.6669898", "0.6662063", "0.6662063", "0.66499317", "0.663539...
0.64797306
39
Checks where the sprite has collided with an obstacle direction is needed to allow a sprite that collides horizontally to continue moving vertically if its movement was in a diagonal. Same goes for blocked vertical movement and continued horizontal movement.
def collide_with_obstacles(sprite, group, direction): collided = False if direction == 'x': collided = True hits = pg.sprite.spritecollide(sprite, group, False, collide_hit_rect) if hits: # If the sprite is moving right, stop it and # set its right face on the left side of the object it collided with. if hits[0].rect.centerx > sprite.hit_rect.centerx: sprite.pos.x = hits[0].rect.left - sprite.hit_rect.width / 2 # If the sprite is moving right, stop it and # set its left face on the left side of the object it collided with. if hits[0].rect.centerx < sprite.hit_rect.centerx: sprite.pos.x = hits[0].rect.right + sprite.hit_rect.width / 2 # Completely stop the sprite sprite.vel.x = -sprite.vel.x # Update the sprite's center to the new position sprite.hit_rect.centerx = sprite.pos.x if direction == 'y': collided = True hits = pg.sprite.spritecollide(sprite, group, False, collide_hit_rect) if hits: # If the sprite is moving upwards, then # set its top to the bottom of the sprite it collided with. if hits[0].rect.centery < sprite.hit_rect.centery: sprite.pos.y = hits[0].rect.bottom + sprite.hit_rect.height / 2 # If the sprite is moving downwards, then # set its bottom to the top of the sprite it collided with. if hits[0].rect.centery > sprite.hit_rect.centery: sprite.pos.y = hits[0].rect.top - sprite.hit_rect.height / 2 # Completely stop the sprite sprite.vel.y = -sprite.vel.y sprite.hit_rect.centery = sprite.pos.y return collided
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_collisions(self, offset, index, obstacles):\n unaltered = True\n self.rect.move_ip(offset)\n while pygame.sprite.spritecollideany(self, obstacles):\n\n # First of all, check if it is a motile transparent block.\n # if so, do nothin\n col_spr = pygame...
[ "0.67670953", "0.66960996", "0.663591", "0.6418021", "0.6344243", "0.63345575", "0.6334223", "0.6327699", "0.6312439", "0.63031816", "0.62835157", "0.6234458", "0.6216627", "0.6159888", "0.6156384", "0.61506426", "0.6149324", "0.61447644", "0.61446947", "0.6136143", "0.608260...
0.655872
3
Get a Producer queue instance
def getProducer(): # get the config and a producer config = ecommerce.config.getConfig() return ecommerce.queue.queue(config, queuePrefix)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_queue():\n\n return multiprocessing.Queue()", "def get(queue_name: str, **kwargs) -> Queue:\n return Queue(queue_name, **kwargs)", "def _get_queue(self):\n return self.__queue", "def _get_queue(self):\n return self.__queue", "def _get_queue(self):\n return self.__queue", "def _...
[ "0.7450264", "0.7052122", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69740534", "0.69648343", "0.69545984", "0.6784196", ...
0.8324251
0
Get the list of all entities of a given type from DB
def getEntityIds(type, subtype = None): # get a cursor conn = ecommerce.db.getConnection() cursor = conn.cursor() # decide the query to execute if type not in entityQueries: return [ ] # execute the query qparams = (type, ) if subtype is not None: qparams = (type, subtype) cursor.execute(entityQueries[type], qparams) # fetch the ids elist = [ ] row = cursor.fetchone() while row is not None: elist.append(int(row[0])) row = cursor.fetchone() cursor.close() return elist
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def query_all(cls)->List:\n database.cursor.execute(\"SELECT * FROM {}\".format(cls.table_name))\n items = database.cursor.fetchall()\n return [cls.to_object(item) for item in items]", "def get_all(cls):\n return db_session.query(cls).order_by(cls.name).all()", "def get_entities(sel...
[ "0.7030536", "0.6770714", "0.66363615", "0.6616682", "0.6602713", "0.6575097", "0.64512324", "0.6423671", "0.64117724", "0.6411315", "0.63493234", "0.634775", "0.63454515", "0.6322174", "0.62615913", "0.6218871", "0.6200281", "0.61640894", "0.6134082", "0.613314", "0.6114528"...
0.6784044
1
Puts generate commands into the queue
def cmd_add(arguments): # build the list of entities entities = { type : [ ] for type in entityTypes } type = "" param = 1 # skip "add" command while param < len(arguments): # get an entity type and check it's valid fullType = arguments[param] type = fullType subtype = None if "/" in type: (type, waste, subtype) = fullType.partition("/") param += 1 if type not in entityTypes: print "ERROR: entity type [%s] is not valid" % type return -1 if subtype is not None and subtype not in subtypes[type]: print "ERROR: entity subtype [%s] for type [%s] is not valid" % (subtype, type) return -1 # build the list of values eList = [ ] if arguments[param] == "*": # if the entity has subtypes and we have no subtype, iterate if subtype is None and subtypes[type]: # iterate subtypes for subtype in subtypes[type]: # set the fullType fullType = type + "/" + subtype # get the list of (ALL) ids from the database eList = getEntityIds(type, subtype) param += 1 # attach the list to the type entities[fullType] = eList else: # no subtypes or subtype specified # get the list of (ALL) ids from the database eList = getEntityIds(type, subtype) param += 1 # attach the list to the type entities[fullType] = eList else: # process the params while param < len(arguments): try: eList.append(int(arguments[param])) param += 1 except ValueError: break # attach the list to the type entities[fullType] = eList # get a producer producer = getProducer() # start creating jobs jobCount = 0 for fullType in entities: # separate type/subtype type = fullType if "/" in type: (type, waste, subtype) = fullType.partition("/") # get the list elist = entities[fullType] # build jobs of up to 64 entries partialJobCount = generateJobs(producer, type, elist) # report if partialJobCount > 0: print "added %5d jobs for entity %s" % (partialJobCount, fullType) jobCount += partialJobCount # report the number of jobs created print "" print "Added a total of %5d jobs in queue" % jobCount print "" return 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate():\n PackCommandExecutor().pack()\n GenerateCommandExecutor().generate()", "def _manager_main(self, queue):\r\n for task in self._task_generator():\r\n queue.put(task)", "def enqueue(self, cmd) -> None:\n self.general_queue.append(cmd)", "def send_command_queue(com...
[ "0.65800864", "0.6378465", "0.61124223", "0.60805756", "0.60594606", "0.60329777", "0.5986247", "0.5985811", "0.58339554", "0.58075696", "0.5778677", "0.5776468", "0.5760314", "0.57391536", "0.57391536", "0.5685093", "0.56670094", "0.56434864", "0.5631529", "0.56295687", "0.5...
0.0
-1
Get the LastUpdateDate for this type of entity
def max_entity_date(entity_type): # assume empty date max_date = None try: # get a cursor conn = ecommerce.db.getConnection() cursor = conn.cursor() # execute the query cursor.execute(""" SELECT TO_CHAR(LastUpdateDate, 'YYYY-MM-DD HH24:MI:SS') FROM Stage0_DeltaControl WHERE EntityType = ? """, (entity_type, ) ) # fetch the max date row = cursor.fetchone() if row is not None: max_date = row[0] cursor.close() except: pass return max_date
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def dt_last_update(self):\n return self.last_update", "def get_last_updated_at(self):\n return self.last_updated", "def get_last_update_time(self):\n return self.last_update_time", "def last_update_datetime(self):\n return datetime.strptime(self.last_update, \"%Y-%m-%d %H:%M:%S.%f...
[ "0.7807228", "0.7612656", "0.75777316", "0.74499947", "0.74499947", "0.7426561", "0.73883593", "0.73883593", "0.721249", "0.721249", "0.7182299", "0.7182299", "0.71680653", "0.71449316", "0.7084291", "0.70218515", "0.69548345", "0.6950892", "0.6945901", "0.686151", "0.6858256...
0.0
-1
Get the list of modified entities before a specified date
def list_modified_entities(entity_type, max_date): # get a cursor conn = ecommerce.db.getConnection() cursor = conn.cursor() # execute the query cursor.execute(""" SELECT EntityId FROM Stage0_Delta WHERE EntityType = ? AND FlagUpdated = 1 AND LastUpdate <= TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS') """, (entity_type, max_date) ) # fetch the ids elist = [ ] row = cursor.fetchone() while row is not None: elist.append(int(row[0])) row = cursor.fetchone() cursor.close() return elist
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def created_before(self, date: datetime):\n return self.created_search(date, search_type=\"before\")", "def is_before(self,other_date):", "def getListModifiedDates(self):\n return _libsbml.ModelHistory_getListModifiedDates(self)", "def get_records_created_before(self, when):\n return self....
[ "0.6760683", "0.59212226", "0.58793044", "0.58698404", "0.573927", "0.5540924", "0.5527508", "0.5492065", "0.5454459", "0.5417637", "0.5409974", "0.53736883", "0.5361394", "0.5243023", "0.52254313", "0.5220781", "0.5217296", "0.5216376", "0.51910895", "0.51544005", "0.5142516...
0.5889012
2
Mark the entities modified before a specific date as processed
def mark_processed_entities(entity_type, max_date): try: # get a connection and cursor conn = ecommerce.db.getConnection() cursor = conn.cursor() # execute the query cursor.execute(""" UPDATE Stage0_Delta SET FlagUpdated = 0 WHERE EntityType = ? AND FlagUpdated = 1 AND LastUpdate <= TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS') """, (entity_type, max_date) ) # commit changes conn.commit() except: conn.rollback() pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def visitBefore(self, date):\n raise NotImplementedError()", "def is_before(self,other_date):", "def modified(self):\r\n\t\treturn self.last_modified > self.last_processed", "def modified(self):\n\t\treturn self.last_modified > self.last_processed", "def _update_modified_since(self, timestamp):\n ...
[ "0.6026466", "0.60223776", "0.6005824", "0.58785576", "0.5820918", "0.5775946", "0.5775946", "0.57705164", "0.56849986", "0.5605239", "0.5544186", "0.55204594", "0.54331017", "0.54331017", "0.54331017", "0.54331017", "0.54331017", "0.54331017", "0.54331017", "0.5399244", "0.5...
0.6365167
0
Process the Stage0_Delta table and create queue commands to process each record that has FlagUpdated = 1
def cmd_delta(arguments): cmd_delta.entities = [ # each entry is a 2-uple, stating the EntityType and # wheter if queue jobs must be generated or not ( "CONT", False ), ( "IMPR", False ), ( "_DSP", False ), ( "SUBJ", True ), ( "PROD", True ), ( "PAGE", True ) ] # iterate each entity type for e in range(len(cmd_delta.entities)): # get handy values entity_type = cmd_delta.entities[e][0] generate = cmd_delta.entities[e][1] print "Processing Entity %s" % (entity_type), logger.info("Processing Entity %s" % (entity_type)) # get the max date max_date = max_entity_date(entity_type) if max_date is not None: # get the list of modified entities (if we need to generate) entities = [ ] if generate: # get the list of entities entities = list_modified_entities(entity_type, max_date) # generate queue jobs producer = getProducer() partialJobCount = generateJobs(producer, entity_type, entities) # mark entities as processed if max_date is not None: mark_processed_entities(entity_type, max_date) print "- DONE (%d entities)" % len(entities) logger.info("Processed Entity %s OK (%d entities)" % (entity_type, len(entities))) else: print "- ERROR" logger.info("Processed Entity %s with ERROR" % (entity_type)) return 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def queueUpdate(self):\n packts = 1\n self.ueLst = list(self.ues.keys())\n self.resAlloc(self.nrbUEmax)\n sym = 0\n if self.nrbUEmax == 0:\n self.sm_lim = 0\n else:\n if self.mimomd == 'MU':\n self.sm_lim = self.symMax*self.nlayers\n ...
[ "0.57603353", "0.5615798", "0.5543773", "0.5470545", "0.5338651", "0.52531934", "0.5228426", "0.5206048", "0.5201316", "0.51806426", "0.51614136", "0.51220685", "0.50776464", "0.50263834", "0.4995501", "0.49954292", "0.4989829", "0.49809688", "0.4969443", "0.4967038", "0.4962...
0.5197049
9
List the job queue
def cmd_list(arguments): # get a producer producer = getProducer() # get the list of pending jobs jobs = producer.list() # print que list size and the entries print "Number of jobs: %d" % len(jobs) for j in range(len(jobs)): print " job %06d - %s" % (j, jobs[j]) return 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ls(self):\n server = jenkins_server.get_jenkins_server()\n queue = server.get_queue_info()\n print('任务ID\\t%s\\t原因' % '任务链接'.ljust(50))\n for q in queue:\n print('%d\\t%s\\t%s' % (q['id'], q['task']['url'].ljust(50), q['why']))", "def list_jobs():\n\n name_to_job_det...
[ "0.7661594", "0.7647107", "0.762154", "0.75825155", "0.74639344", "0.7404997", "0.71474695", "0.7096951", "0.7051303", "0.69853973", "0.69715", "0.69715", "0.69136894", "0.68906635", "0.6835532", "0.683014", "0.6773141", "0.6738064", "0.6734032", "0.6690407", "0.6667332", "...
0.7498685
4
List the job queue
def cmd_sitemap(arguments): # create a sitemap job job = jobs.encode(jobs.sitemap()) # get a producer producer = getProducer() # get an item, set content and make it ready item = producer.item() item.content = job producer.ready(item) print "Sitemap command put in queue" return 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ls(self):\n server = jenkins_server.get_jenkins_server()\n queue = server.get_queue_info()\n print('任务ID\\t%s\\t原因' % '任务链接'.ljust(50))\n for q in queue:\n print('%d\\t%s\\t%s' % (q['id'], q['task']['url'].ljust(50), q['why']))", "def list_jobs():\n\n name_to_job_det...
[ "0.7661594", "0.7647107", "0.762154", "0.75825155", "0.7498685", "0.74639344", "0.7404997", "0.71474695", "0.7096951", "0.7051303", "0.69853973", "0.69715", "0.69715", "0.69136894", "0.68906635", "0.6835532", "0.683014", "0.6773141", "0.6738064", "0.6734032", "0.6690407", "...
0.0
-1
A generator that can be used to iterate over all of the message handlers that belong to this instance.
def iter_message_handlers(self): for name in dir(self): attr = getattr(self, name) if isinstance(attr, MessageHandler): yield attr
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_message_handlers(self):\n\t\treturn self.message_handlers", "def get_handlers(self):\n\n # Get handlers \n logger.debug(\"%s: Returned %d handlers.\" % \\\n (self.__class__.__name__, len(self._handlers)))\n return self._handlers[:]", "def __iter__(self):\n ...
[ "0.75313586", "0.7092574", "0.689368", "0.6885732", "0.6611093", "0.64954853", "0.6490498", "0.6438109", "0.6379151", "0.6324771", "0.6322066", "0.62982225", "0.62764996", "0.6234379", "0.6224543", "0.62200075", "0.61538786", "0.60254633", "0.6023188", "0.60213643", "0.594284...
0.86009705
0
Adds the given service's message handlers to our managed message handlers.
def register_service(self, service): for message_handler in service.iter_message_handlers(): self.message_handlers[message_handler.name] = message_handler
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def connect(self, service, handler):\n self.partyline.setdefault(service, []).append(handler)", "def register_websock_handlers(self, service, new_client, new_message, close_client):\n if service in self.websock_handlers:\n L.error(\"Error: service:\" + service + \" is already registered\...
[ "0.6415957", "0.63830936", "0.60461724", "0.6046069", "0.6006367", "0.58971536", "0.5866512", "0.5834788", "0.5806009", "0.5753481", "0.5696065", "0.5631438", "0.56120425", "0.5598932", "0.55874574", "0.55768156", "0.55757207", "0.55562836", "0.5551294", "0.5539715", "0.55364...
0.8374331
0
Invokes the correct message handler for the given message.
def handle_message(self, sender, message): self.logger.debug('handle_message(%r, %r)', sender, message.handler) message_handler = self.message_handlers.get(message.handler) if message_handler is None: self.logger.warning("sender=%r, No handler found: '%s'", sender, message.handler) return message_handler(sender, message)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handle_message(self, message):\n\n\t\tself.log.debug(\"%s handle_message %s\", self.name, message)\n\n\t\tif message[\"Type\"] == \"command\":\n\t\t\ttry:\n\t\t\t\tcommand_callable = \"command_%s\" % message[\"Message\"][\"command\"]\n\t\t\t\tif hasattr(self, command_callable) and callable(getattr(self, comman...
[ "0.7761963", "0.72658277", "0.7105738", "0.7102408", "0.7060995", "0.7036604", "0.70310044", "0.7029397", "0.699162", "0.69913566", "0.698211", "0.6949379", "0.69273627", "0.6888938", "0.68215775", "0.6818507", "0.67997396", "0.6774335", "0.67683744", "0.6749502", "0.6715756"...
0.73108006
1
Do not return anything, modify matrix inplace instead.
def setZeroes(self, matrix): for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] == 0 and (i, j) not in self.visited: for neighbor in self.setter(matrix, i, j): matrix[neighbor[0]][neighbor[1]] = 0 self.visited.add((neighbor[0], neighbor[1])) print(matrix)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __update_matrix(self, old_matrix_view):\n # if we've cleaned dirt - we will see it on our next move, so we substitute only unseen cells\n # which are marked with \"o\"\n new_matrix_view = []\n for row in range(self.matrix_rows):\n new_matrix_view.append([char for char in ...
[ "0.7066283", "0.6845453", "0.6360038", "0.62143975", "0.6191982", "0.61279464", "0.6040232", "0.59938055", "0.5967881", "0.59397227", "0.59288263", "0.5918774", "0.58981085", "0.5853208", "0.58428276", "0.58091146", "0.57997805", "0.5791091", "0.57368064", "0.57231134", "0.57...
0.0
-1
This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`.
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def plot_confusion_matrix(cm, classes=[0,1], normalize=False, title='Confusion matrix', print_matrix=False):\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n...
[ "0.8194862", "0.80949175", "0.8029915", "0.8019153", "0.79941195", "0.7991258", "0.7980955", "0.7976606", "0.79610753", "0.79590565", "0.79378676", "0.7934962", "0.7934504", "0.79313844", "0.7926313", "0.7924577", "0.79241234", "0.7923211", "0.7923023", "0.7921931", "0.791787...
0.0
-1
Export ECU data to excel format
def extract_ecu(self, vin_list=None): corvets = Corvet.objects.filter(vin__in=vin_list) self.header, self.fields = self.get_header_fields(CORVET_DICT.get("extract_ecu", [])) values_list = corvets.values_list(*self.fields).distinct() return values_list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_excel(self, filename):\n self.data.to_excel(filename)", "def export_excel(self, filename):\n # convert table to array of rows\n rows = [self.headings]\n for y in range(self.rowcount):\n row = []\n for h in self.headings:\n row.append(self.ta...
[ "0.6653394", "0.6451767", "0.643158", "0.63429654", "0.6334339", "0.6333897", "0.6286794", "0.62807244", "0.6235302", "0.62333274", "0.6191427", "0.6170842", "0.60931844", "0.60574377", "0.605236", "0.6052189", "0.6044034", "0.60123223", "0.6012149", "0.6002858", "0.5997272",...
0.0
-1
Export CORVET data to excel format
def extract_corvet(self, *args, **kwargs): self._product_filter(**kwargs) self._vehicle_filter(**kwargs) self._select_columns(**kwargs) queryset = self.queryset.annotate( date_debut_garantie=Cast(TruncSecond('donnee_date_debut_garantie', DateTimeField()), CharField())) if kwargs.get('tag', None): queryset = queryset.filter(opts__tag=kwargs.get('tag')) if kwargs.get('vins', None): vin_list = kwargs.get('vins').split('\r\n') queryset = queryset.filter(vin__in=vin_list) if kwargs.get('xelon_model', None): queryset = queryset.select_related().filter(xelon__modele_produit__startswith=kwargs.get('xelon_model')) if kwargs.get('xelon_vehicle', None): queryset = queryset.select_related().filter(xelon__modele_vehicule__startswith=kwargs.get('xelon_vehicle')) if kwargs.get('start_date', None): queryset = queryset.filter(donnee_date_debut_garantie__gte=kwargs.get('start_date')) if kwargs.get('end_date', None): queryset = queryset.filter(donnee_date_debut_garantie__lte=kwargs.get('end_date')) values_list = queryset.values_list(*self.fields).distinct() return values_list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_excel(self, filename):\n self.data.to_excel(filename)", "def export_to_file(final_data_fetch):\r\n\r\n # Column names for data\r\n header_fields = ['Course', 'University', 'GPA', 'GRE', 'TOEFL', 'Work Experience', 'UG Course', 'UG College','Admit Status']\r\n with xlsxwriter.Workbook('yock...
[ "0.6996788", "0.6588683", "0.65867573", "0.6548197", "0.6542862", "0.6455031", "0.63961285", "0.6389617", "0.632453", "0.6319494", "0.628004", "0.62699443", "0.6260905", "0.6237417", "0.62198824", "0.62193406", "0.6173042", "0.6167193", "0.61626554", "0.6151517", "0.61514807"...
0.0
-1
Get a yacs CfgNode object with default values for my_project.
def get_cfg_defaults(): # Return a clone so that the defaults will not be altered # This is for the "local variable" use pattern return _C.clone()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_default_config(project):\n return {\n \"breathe_projects\": {\n project: \"./_doxygen/xml\"\n },\n \"breathe_default_project\": project,\n \"exhale_args\": {\n # required arguments\n \"containmentFolder\": \"./api\",\n \"rootFileNa...
[ "0.6206752", "0.60061955", "0.59438497", "0.5857599", "0.5857599", "0.58438694", "0.5837966", "0.58032465", "0.5682998", "0.5640771", "0.55415815", "0.5538713", "0.5535621", "0.5531356", "0.5446284", "0.54307395", "0.5405538", "0.5367158", "0.535104", "0.5333277", "0.5309475"...
0.5848163
6
Convert a time.struct_time as returned by feedparser into a
def _convert_struct_time_to_dt(stime): return date.fromtimestamp(mktime(stime))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def time_struct_to_datetime(struct_time_object):\n return datetime.datetime(*struct_time_object[:6])", "def _convert_struct_time_to_dt(stime):\n\n dt = datetime.datetime.fromtimestamp(mktime(stime))\n\n return dt.date()", "def unmarshall_time(tyme):\r\n return datetime.datetime(day=tyme['day'],\r\n...
[ "0.7229315", "0.67260563", "0.6565747", "0.6513471", "0.63544554", "0.6352278", "0.63428724", "0.62921166", "0.6273469", "0.6266583", "0.62201977", "0.62145513", "0.6209023", "0.61696506", "0.6159586", "0.61529684", "0.61013764", "0.608812", "0.59947324", "0.5987127", "0.5983...
0.7049241
1
Use feedparser to parse PyBites RSS feed. Return a list of Entry namedtuples (date = date, drop time part)
def get_feed_entries(feed=FEED) -> list: f = feedparser.parse(feed) entry_list = [] for entry in f.entries: date = _convert_struct_time_to_dt(entry["published_parsed"]) title = entry["title"] link = entry["link"] tags = [tag["term"].lower() for tag in entry["tags"]] entry_list.append(Entry(date=date, title=title, link=link, tags=tags)) return entry_list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_feed_entries(feed=FEED):\n d = feedparser.parse(feed)\n entries = d.entries\n \n all_entries =[]\n for entry in entries:\n title = entry.title\n link = entry.link\n date = entry.published_parsed\n tags = entry.tags\n tags = [t.get('term').lower() for t in t...
[ "0.7831155", "0.729255", "0.7232448", "0.67960274", "0.674423", "0.6664003", "0.66603625", "0.6557846", "0.6554401", "0.65351653", "0.65075", "0.64848477", "0.647246", "0.6385361", "0.63827616", "0.63343084", "0.6323492", "0.6318049", "0.6304754", "0.6304091", "0.62566954", ...
0.7714306
1
Check if search matches any tags as stored in the Entry namedtuple (case insensitive, only whole, not partial string matches).
def filter_entries_by_tag(search, entry) -> bool: tags = entry.tags search_words = search.strip().translate(str.maketrans("&|", " ")).split() if "&" in search: search_type = "AND" else: search_type = "OR" for word in search_words: if word.lower() in tags: if search_type == "OR": return True elif search_type == "AND": return False if search_type == "OR": return False else: return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def filter_entries_by_tag(search, entry):\n \n entry_tags = entry.tags\n if '&' in search:\n splits = search.split('&')\n\n return all(split.lower() in entry_tags for split in splits)\n elif '|' in search:\n splits = search.split('|')\n return any(split.lower() in entry_...
[ "0.7962715", "0.72779536", "0.6499833", "0.62624013", "0.62382317", "0.6214999", "0.6140391", "0.6119588", "0.6078616", "0.60098", "0.59635174", "0.5918138", "0.5911922", "0.58637714", "0.5848267", "0.5831237", "0.5806548", "0.5795138", "0.57761455", "0.57537323", "0.57031983...
0.75187373
1
Entry point to the program 1. Call get_feed_entries and store them in entries 2. Initiate an infinite loop
def main(): entries = get_feed_entries() while True: response = input("What you you like to search for? ") if not response: print("Please provide a search term") continue if response.lower() == "q": print("Bye") break matches = [ entry for entry in list( filter(lambda x: filter_entries_by_tag(response.lower(), x), entries) ) ] if matches: for entry in sorted(matches, key=lambda x: x.date): print(entry.title) print(f"{len(matches)} {'entry' if len(matches) == 1 else 'entries'} matched")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_feed_entries_task():\n get_feed_entries()\n logger.info(\"Entries for Feed\")", "def main():\n feed_db, entry_db = openDBs(FEED_DB_FN, ENTRY_DB_FN)\n\n feeds = [ x.strip() for x in open(FEEDS_FN, \"r\").readlines() ]\n \n entries = getNewFeedEntries(feeds, feed_db, entry_db)\n \n ...
[ "0.67926604", "0.6669436", "0.66450924", "0.66018087", "0.63761574", "0.63712484", "0.63650745", "0.6307002", "0.62871724", "0.61856663", "0.6142305", "0.6107129", "0.61045074", "0.61003304", "0.60493374", "0.6042528", "0.6004268", "0.59982747", "0.59332794", "0.59283483", "0...
0.65567255
4
Gather the top 10 words by highest (descending) likelihoods for each class
def top10_likelihoods(likelihoods, vocab, classes): resultDict = {} for cls in classes: results = [] for word in vocab: results.append((word, likelihoods[cls][word])) resultDict[cls] = results # Sort and return top 10 for each class for key in resultDict: results = resultDict[key] resultDict[key] = map(lambda x: x[0], sorted(results, key=lambda x: x[1], reverse=True))[:10] return resultDict
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def top10_odds_ratio(likelihoods, vocab, classes):\r\n results = []\r\n for word in vocab:\r\n highestOddsRatio = None\r\n for c1 in classes:\r\n for c2 in classes:\r\n # Skip self TODO: Is this right?\r\n # if c1 == c2:\r\n # continue...
[ "0.7205802", "0.70088744", "0.6974292", "0.6939049", "0.68271315", "0.67730814", "0.6618862", "0.66091466", "0.64232916", "0.6413391", "0.639833", "0.63636", "0.6353295", "0.63519716", "0.6349507", "0.63440084", "0.6335887", "0.63027114", "0.6243625", "0.623767", "0.6233897",...
0.7892108
0
Gather the top 10 words by highest (descending) odds ratios
def top10_odds_ratio(likelihoods, vocab, classes): results = [] for word in vocab: highestOddsRatio = None for c1 in classes: for c2 in classes: # Skip self TODO: Is this right? # if c1 == c2: # continue oddsRatio = odds_ratio(likelihoods, c1, c2, word) if oddsRatio > highestOddsRatio or highestOddsRatio == None: highestOddsRatio = oddsRatio results.append((word, highestOddsRatio)) # Sort and return top 10 return map(lambda x: x[0], sorted(results, key=lambda x: x[1], reverse=True))[:10]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def display_top_n_words(total_count__of_words, n): # Considering n=10 here as specified in the requirements\n return sorted(total_count__of_words.items(), key=lambda i: i[1], reverse=True)[:n]", "def get_top_words(self, label, n):\n score_list = []\n if('sod' in label):\n for term i...
[ "0.7232739", "0.6893036", "0.67285866", "0.6680685", "0.66617835", "0.66482335", "0.6614465", "0.6595784", "0.6562109", "0.645501", "0.64387554", "0.6425363", "0.63707566", "0.6370042", "0.6349563", "0.6348198", "0.6341136", "0.6331591", "0.63161516", "0.6312066", "0.6284538"...
0.7499493
0
Calculate the accuracy of our predicated vs. actual
def evaluate(predicted, actual): assert(len(predicted) == len(actual)) total = len(actual) correct = len([x for x in range(total) if predicted[x] == actual[x]]) return (float(correct) / float(total)) * 100.0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accuracy(self):\n total_predictions = self.tp + self.fp + self.tn + self.fn;\n return float(self.tp + self.tn) / total_predictions if total_predictions != 0 else 1", "def get_accuracy(self) -> float:\n self.network.load_data()\n self.network.train()\n\n n = len(self.network...
[ "0.83784646", "0.82262033", "0.822042", "0.8146395", "0.8089007", "0.8089007", "0.80558175", "0.8008387", "0.80057275", "0.79616034", "0.79590094", "0.79344165", "0.7930567", "0.78854644", "0.78593326", "0.7858755", "0.7850988", "0.7762686", "0.7759415", "0.7753433", "0.77095...
0.0
-1
Classify data based on bernoulli model
def classify(priors, likelihoods, testData, classes): results = [] for document in testData: bestClass = None bestProb = None currentProb = 0.0 for cls in classes: prior = priors[cls] currentProb = log(prior) lhoods = likelihoods[cls] for (word, count) in document: if word in lhoods: currentProb += log(lhoods[word]) else: currentProb += log(lhoods[None]) if currentProb > bestProb or bestClass == None: bestProb = currentProb bestClass = cls results.append(bestClass) return results
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_Bernoulli_NB_estimators():", "def fit_and_predict_BernoulliNB(X_train, Y_train, X_test):\n\n # Import the package\n from sklearn.naive_bayes import BernoulliNB \n\n ### YOUR SOLUTION STARTS HERE### \n #referenced to sklearn documentation \n # fit the model... \n clf = BernoulliNB(bi...
[ "0.6858228", "0.68162215", "0.6734391", "0.6612314", "0.65618414", "0.64322984", "0.64175165", "0.64140654", "0.6396146", "0.63302946", "0.6329519", "0.62704647", "0.62355125", "0.6218283", "0.6174795", "0.6173328", "0.6168497", "0.61587894", "0.61451745", "0.61435205", "0.61...
0.0
-1
Estimate the priors for a class
def calculate_priors(trainingLabels): sum = 0 priors = {} totalSamples = len(trainingLabels) classes = set(trainingLabels) for cls in classes: numCls = len(filter(lambda x: x == cls, trainingLabels)) sum += numCls priors[cls] = float(numCls) / float(totalSamples) # Sanity check: valid partitioning assert(sum == totalSamples) return priors
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def classProbs(observation, tree, classes):\n res = classify(observation, tree) #res = results\n total = sum(res.values())\n probs = []\n for c in classes:\n if c in res.keys():\n probs.append(float(res[c])/total)\n else:\n probs.append(0)\n return probs", "def ...
[ "0.66456854", "0.6316928", "0.6273953", "0.60905004", "0.6055876", "0.60154176", "0.5993265", "0.59645927", "0.59377426", "0.5896327", "0.58948433", "0.58720356", "0.58248436", "0.5820803", "0.58123535", "0.5798083", "0.57771003", "0.5732761", "0.5723448", "0.57202864", "0.57...
0.699718
0
Calculate the likelihoods for multinomial
def calculate_likelihoods_multinomial(data, labels, vocab): likelihoods = {} counts = {} words = {} classes = set(labels) vocabLen = len(vocab) for cls in classes: # Initialize counts[cls] = {} words[cls] = 0 # Perform counts line = 0 for doc in data: cls = labels[line] wordCounts = counts[cls] for (word, count) in doc: if word not in wordCounts: wordCounts[word] = 0 wordCounts[word] += count words[cls] += count line += 1 # Compute likliehoods for cls in counts: wordCounts = counts[cls] likelihoods[cls] = {} wordsInClass = words[cls] for word in wordCounts: likelihoods[cls][word] = laplace_smooth(wordCounts[word], wordsInClass, vocabLen) # Add all training words: for word in vocab: if word not in likelihoods[cls]: likelihoods[cls][word] = laplace_smooth(0, wordsInClass, vocabLen) # Special laplace smoothing for words not found in training data likelihoods[cls][None] = laplace_smooth(0, wordsInClass, vocabLen) return likelihoods
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def multinomial_likelihood(m_true, alpha, alpha0, m_probs):\n\n ll = tf.reduce_sum(input_tensor=m_true * (tf.math.log(alpha0) - tf.math.log(alpha)), axis=1, keepdims=True)\n ll = tf.reduce_mean(input_tensor=ll)\n return ll", "def multinomial_nll(true_counts, logits):\n counts_per_example = tf.reduce_...
[ "0.7405791", "0.71270245", "0.6805791", "0.67948574", "0.6551636", "0.6476551", "0.64614797", "0.6425553", "0.6342785", "0.63420993", "0.6332708", "0.633066", "0.6330074", "0.6298897", "0.62908417", "0.62799925", "0.62471", "0.62063324", "0.61783415", "0.6177655", "0.61492676...
0.7152682
1