query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Gets the full name of sender. Uses a get request. | def get_full_name(sender, token):
url = "https://graph.facebook.com/v2.6/" + sender + "?fields=first_name,last_name&access_token=" + token
headers = {'content-type': 'application/json'}
response = requests.get(url, headers=headers)
data = json.loads(response.content)
return ''.join(data['first_name'... | [
"def sender_name(self):\n return self._sender_name",
"def get_sender_username(self, mess): \n type = mess.getType()\n jid = mess.getFrom()\n if type == \"groupchat\":\n username = jid.getResource()\n elif type == \"chat\":\n username = jid.getNode()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if noninteractive is truthy, always return default. intended primarily as a wrapper to preempt attempts to prompt user input. | def catch_interaction(
noninteractive: Any, func: Callable, *args, _default: Any = "", **kwargs
):
if noninteractive:
return _default
return func(*args, **kwargs) | [
"def _return_default(self, prompt, default, cli_flag, force_interactive):\n # assert_valid_call(prompt, default, cli_flag, force_interactive)\n if self._can_interact(force_interactive):\n return False\n elif default is None:\n msg = \"Unable to get an answer for the questi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
iterable > function returns function that checks if its single argument contains all (or by changing oper, perhaps any) items | def are_in(items: Collection, oper: Callable = and_) -> Callable:
def in_it(container: Collection) -> bool:
inclusion = partial(contains, container)
return reduce(oper, map(inclusion, items))
return in_it | [
"def are_in(\n items: Iterable, oper: Callable = and_\n) -> Callable[[Sequence], bool]:\n\n def in_it(container: Iterable) -> bool:\n inclusion = partial(contains, container)\n return reduce(oper, map(inclusion, items))\n\n return in_it",
"def AllInSet(operator):\n return lambda elem, va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
'greedy map' function. map `func` across `iterables` using `mapper` and evaluate with `evaluator`. because we splat the variadic `iterables` argument into `mapper`, behavior is roughly equivalent to `itertools.starmap` if you pass more than one iterable. for cases in which you need a terse or configurable way to map an... | def gmap(
func: Callable,
*iterables: Iterable,
mapper: Callable[[Callable, tuple[Iterable]], Iterable] = map,
evaluator: Callable[[Iterable], Any] = tuple
):
return evaluator(mapper(func, *iterables)) | [
"def map(function, iterable0, *iterables):\n return stdlib_map(function, iterable0, *iterables)",
"def starmap(func, iterable):\n return Iter(itertools.starmap(func, iterable))",
"def eager_map(func, iterable):\n for _ in map(func, iterable):\n continue",
"def map(function, iterable):\n\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the boolean version of a number | def CBool(num):
n = float(num)
if n:
return 1
else:
return 0 | [
"def numberp(v):\r\n return (not(isinstance(v, bool)) and\r\n (isinstance(v, int) or isinstance(v, float)))",
"def test04_boolean_operator(self):\n\n import _cppyy\n number = _cppyy.gbl.number\n\n n = number(20)\n assert n\n\n n = number(0)\n assert not n",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Choose from a list of options If the index is out of range then we return None. The list is indexed from 1. | def Choose(index, *args):
if index <= 0:
return None
try:
return args[index - 1]
except IndexError:
return None | [
"def _choose_one(options, what='one'):\n chosen = None\n if not options:\n return\n elif len(options) == 1:\n chosen = 0\n else:\n print 'Choose %s:' % what\n for number, line in enumerate(options):\n print '%d. %s' % (number + 1, line)\n while chosen is Non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to create an OLE object This only works on windows! | def CreateObject(classname, ipaddress=None):
if not win32com:
raise ImportError('Not on Windows - cannot create COM object')
if ipaddress:
raise VB2PYNotSupported("DCOM not supported")
return win32com.client.Dispatch(classname) | [
"def __init__(self, name):\n super().__init__()\n try:\n import win32com.client\n self.connection = win32com.client.Dispatch(name)\n except ModuleNotFoundError:\n print(\"'win32com' package is missing. Can't use ActiveX LabControl.\")",
"def _winoffice(self):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the String associated with an operating system environment variable envstring Optional. String expression containing the name of an environment variable. number Optional. Numeric expression corresponding to the numeric order of the environment string in the environmentstring table. The number argument can be any... | def Environ(envstring):
try:
envint = int(envstring)
except ValueError:
return os.environ.get(envstring, "")
# Is an integer - need to get the envint'th value
try:
return "%s=%s" % (list(os.environ.keys())[envint], list(os.environ.values())[envint])
except IndexError:
... | [
"def getenv_string(setting, default=''):\n return os.environ.get(setting, default)",
"def env_string(env_vars):\n env_str = \"\"\n for env_var in env_vars:\n value = env_vars[env_var]\n env_str += f\" -e {env_var}='{value}' \"\n return env_str",
"def ENV_STR(name, default=None):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if we reached the end of file for the particular channel | def EOF(channel):
return VBFiles.EOF(channel) | [
"def at_eof(self):\n return self.tell() >= len(self)",
"def eof_check(self) -> bool:\n eof = False\n curr_pos = self.fileobject.tell()\n # print(curr_pos, self.st_size)\n chunk = self.fileobject.read(25)\n if chunk == '':\n # Is there something on the back burn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the length of a given file | def FileLen(filename):
return os.stat(str(filename))[6] | [
"def get_len(filename):\n return os.stat(filename).st_size",
"def file_size(filename):\n return stat(filename).st_size",
"def file_size():\n return os.path.getsize(FILE_NAME)",
"def file_size(root, file):\n return getsize(join(root,file))",
"def get_file_size(input_file):\n old_file_position = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a zerobased array containing subset of a string array based on a specified filter criteria | def Filter(sourcesarray, match, include=1):
if include:
return Array(*[item for item in sourcesarray if item.find(match) > -1])
else:
return Array(*[item for item in sourcesarray if item.find(match) == -1]) | [
"def _get_string_subset(\n data, starts_with=None, ends_with=None, exact_word=None, regex=None\n):\n data = utils.toarray(data)\n mask = _get_string_subset_mask(\n data,\n starts_with=starts_with,\n ends_with=ends_with,\n exact_word=exact_word,\n regex=regex,\n )\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if an object is an array | def IsArray(obj):
return isinstance(obj, (list, tuple)) | [
"def _is_array(obj):\r\n return isinstance(obj, np.ndarray)",
"def is_arraylike(obj):\n if isinstance(obj, list):\n return True\n elif isinstance(obj, np.ndarray):\n return True\n elif isinstance(obj, pd.Series):\n return True\n elif isinstance(obj, pd.DataFrame):\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the left most characters in the text | def Left(text, number):
return text[:number] | [
"def characters_left(self):\r\n return self.max_chars - len(self.variable.get())",
"def _take_left_n_chars(self, txt, i):\n\t\tassert 0 <= i <= len(txt)\n\n\t\tchars = []\n\t\tk = i\n\t\twhile len(chars) < self._n_chars_left and k >= 0:\n\t\t\tc = txt[k]\n\t\t\tif c not in self._separators:\n\t\t\t\tchars.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if the text matches the pattern The pattern is a string containing wildcards = any string of characters ? = any one character Fortunately, the fnmatch library module does this for us! | def Like(text, pattern):
return fnmatch.fnmatch(text, pattern) | [
"def search(text=None, pattern=None):\n return True if pattern in text else False",
"def regex_match(text, pattern):\n try:\n pattern = re.compile(\n pattern,\n flags=re.IGNORECASE + re.UNICODE + re.MULTILINE,\n )\n except BaseException:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if X implies Y Performs a bitwise comparison of identically positioned bits and sets corresponding bit in the output. | def Imp(x, y):
ix, iy = int(x), int(y)
if not (ix or iy):
result = 1
else:
result = 0
while ix or iy:
# Shift result by one bit
result = result << 1
#
# Get the bits for comparison
x_bit1 = ix & 1
y_bit1 = iy & 1... | [
"def xor(x, y):\n return bool(x) != bool(y)",
"def equivalent(self, x, y):\n\t\treturn self.morphism(x) == self.morphism(y)",
"def equalp(self, y):\n return scbool(self == y)",
"def __and__(self, other):\n return BitBoard(self.num & other.num)",
"def _logical_equal(x, y):\n x_ = _static_va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load an image as a bitmap for display in a BitmapImage control | def LoadPicture(filename):
return Bitmap(filename) | [
"def load_image(in_image):\n img = Image.open(in_image)\n return img",
"def ImageFromBitmap(*args, **kwargs):\n val = _core_.new_ImageFromBitmap(*args, **kwargs)\n return val",
"def create_bitmap(self, image_data):\n stream = io.BytesIO(image_data)\n\n bitmap = None\n\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Do a VB LSet Left aligns a string within a string variable, or copies a variable of one userdefined type to another variable of a different userdefined type. LSet stringvar = string LSet replaces any leftover characters in stringvar with spaces. If string is longer than stringvar, LSet places only the leftmost characte... | def LSet(var, value):
return value[:len(var)] + " " * (len(var) - len(value)) | [
"def RSet(var, value):\n return \" \" * (len(var) - len(value)) + value[:len(var)]",
"def test_assignment_to_string(self):\n code = \"s = 'abc'\\ns[1] = 'd'\"\n good_code = \"s = 'abc'\\nl = list(s)\\nl[1] = 'd'\\ns = ''.join(l)\"\n sugg = 'convert to list to edit the list and use \"join()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a string in which a specified substring has been replaced with another substring a specified number of times The return value of the Replace function is a string, with substitutions made, that begins at the position specified by start and and concludes at the end of the expression string. It is not a copy of th... | def Replace(expression, find, replace, start=1, count=-1):
if find:
return expression[:start - 1] + expression[start - 1:].replace(find, replace, count)
else:
return expression | [
"def REPLACE(old_text, start_num, num_chars, new_text):\n if start_num < 1:\n raise ValueError(\"start_num invalid\")\n return old_text[:start_num - 1] + new_text + old_text[start_num - 1 + num_chars:]",
"def sub(self, replace, string, count=0):\n return self.re.sub(replace, string, count)",
"def resu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the right most characters in the text | def Right(text, number):
return text[-number:] | [
"def _take_right_n_chars(self, txt, i):\n\t\tassert 0 <= i <= len(txt)\n\n\t\tchars = []\n\t\tk = i\n\t\twhile len(chars) < self._n_chars_right and k < len(txt):\n\t\t\tc = txt[k]\n\t\t\tif c not in self._separators:\n\t\t\t\tchars.append(c)\n\t\t\tk += 1\n\t\ts = \"\".join(chars)\n\t\treturn s + OUT_OF_BOUNDS * (s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Do a VB RSet Right aligns a string within a string variable. RSet stringvar = string If stringvar is longer than string, RSet replaces any leftover characters in stringvar with spaces, back to its beginning. | def RSet(var, value):
return " " * (len(var) - len(value)) + value[:len(var)] | [
"def LSet(var, value):\n return value[:len(var)] + \" \" * (len(var) - len(value))",
"def write_right(self, string):\n self._start_line()\n pad = self.remaining - length(string)\n if pad < 0:\n self.newline()\n else:\n self._write(pad * \" \")\n self._wr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a setting in the central setting file | def DeleteSetting(appname, section, key):
settings = _OptionsDB(appname)
settings.delete(section, key) | [
"def delsetting(name):\r\n if '__delattr__' in settings.__class__.__dict__:\r\n delattr(settings, name)\r\n else:\r\n delattr(settings._wrapped, name)",
"def _delSetting(cls, setting):\r\n del cls.settings[setting.name]\r\n delattr(cls, setting._py_name)",
"def _delSetting(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split a string using the delimiter If the optional limit is present then this defines the number of items returned. The compare is used for different string comparison types in VB, but this is not implemented at the moment | def Split(text, delimiter=" ", limit=-1, compare=None):
if compare is not None:
raise VB2PYNotSupported("Compare options for Split are not currently supported")
#
if limit == 0:
return VBArray(0)
elif limit > 0:
return Array(*str(text).split(delimiter, limit - 1))
else:
... | [
"def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__\n return []",
"def split(self, string, maxsplit=MAX_INT, include_separators=False):\n return self._split(\n string, maxsplit=maxsplit, include_separators=include_separators\n )",
"def split_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Choose from a list of expression each with its own condition The arguments are presented as a sequence of condition, expression pairs and the first condition that returns a true causes its expression to be returned. If no conditions are true then the function returns None | def Switch(*args):
arg_list = list(args)
arg_list.reverse()
#
while arg_list:
cond, expr = arg_list.pop(), arg_list.pop()
if cond:
return expr
return None | [
"def find_if(cond,seq):\n for x in seq:\n if cond(x): return x\n return None",
"def argfind1(xs, cond):\n return next(i for (i, x) in enumerate(xs) if cond(x))",
"def or_list(conditionList):\n return functools.reduce(numpy.logical_or, conditionList)",
"def and_list(conditionList):\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the value of a string This function finds the longest leftmost number in the string and returns it. If there are no valid numbers then it returns 0. The method chosen here is very poor we just keep trying to convert the string to a float and just use the last successful as we increase the size of the string. A R... | def Val(text):
best = 0
for idx in range(len(text)):
try:
best = float(text[:idx + 1])
except ValueError:
pass
return best | [
"def find_float_in_string(value, limit=None, keep_right_zeros=True):\n if value:\n value = str(value).lower()\n\n try:\n value = value.replace(',', '.')\n number = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", value)[0]\n # number = re.findall(r\"\\d+\\.\\d+\", value)[0] #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return arguments passed in an event VB Control events have parameters passed in the call, eg MouseMove(Button, Shift, X, Y). In vb2py.PythonCard the event parameters are all passed as a single event object. We can easily unpack the attributes back to the values in the Event Handler but we also have to account for the f... | def vbGetEventArgs(names, arguments):
# arguments is the *args tuple
#
# Is there only one parameter
if len(arguments) == 1:
# Try to unpack names from this argument
try:
ret = []
for name in names:
if name.endswith("()"):
ret.a... | [
"def keyevent2tuple(event):\n return (event.type(), event.key(), event.modifiers(), event.text(),\n event.isAutoRepeat(), event.count())",
"def _convert_args(self, expr, args, kwargs):\n assert expr is not None\n\n if not kwargs:\n return args\n\n if kwargs and not is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the AddressOf a variable This does not work in Python and likely the code using it is going to need significant work so we just throw an error here. | def AddressOf(obj):
raise NotImplementedError('AddressOf does not work in Python and code will likely need refactoring') | [
"def addressof(obj):\n pass",
"def LocalAddress(self) -> _n_5_t_0:",
"def get_address_value(obj):\n no_dynamic = obj.GetDynamicValue(lldb.eNoDynamicValues)\n \"\"\":type: lldb.SBValue\"\"\"\n address = no_dynamic.GetAddress()\n \"\"\":type: lldb.SBAddress\"\"\"\n address_value = address.GetFil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Close any pipes we have to the process (both input and output) and wait for it to exit. If cancelled, kills the process and waits for it to finish exiting before propagating the cancellation. | async def aclose(self):
with _core.open_cancel_scope(shield=True):
if self.stdin is not None:
await self.stdin.aclose()
if self.stdout is not None:
await self.stdout.aclose()
if self.stderr is not None:
await self.stderr.aclose(... | [
"def close(self):\n self.ffmpeg_process.stdin.close()\n self.ffmpeg_process.wait()",
"def close(self):\n self.shell.stdin.close()\n self.shell.terminate()\n self.shell.wait(timeout=1.0)",
"def close_process(p):\n try:\n p.close()\n except AttributeError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch the permission for the specified team. | def get(self, namespace_name, repository_name, teamname):
logger.debug(
"Get repo: %s/%s permissions for team %s", namespace_name, repository_name, teamname
)
role = model.get_repo_role_for_team(teamname, namespace_name, repository_name)
return role.to_dict() | [
"def get_team_permissions(team_id, token):\n team = service.control.get_object(\n service='team',\n action='get_team',\n return_object='team',\n client_kwargs={'token': token},\n inflations={'disabled': True},\n fields={'only': ['permissions']},\n team_id=team_id,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the existing team permission. | def put(self, namespace_name, repository_name, teamname):
new_permission = request.get_json()
logger.debug("Setting permission to: %s for team %s", new_permission["role"], teamname)
try:
perm = model.set_repo_permission_for_team(
teamname, namespace_name, repository... | [
"def patch(self, team_id, project_id):\n try:\n role = request.get_json(force=True)[\"role\"]\n except DataError as e:\n current_app.logger.error(f\"Error validating request: {str(e)}\")\n return {\"Error\": str(e), \"SubCode\": \"InvalidData\"}, 400\n\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add event 'event', which is of type event to minheap of events assign an id to it return the assigned id | def addEvent(self, event):
event.__id=id
id+=1
self.addToHeap(event)
return event.__id | [
"def insert(self, event):\n with self._lock:\n self._events.update({self._id_count : event}) # id, event pair\n self._id_count += 1 # increasing ids",
"def add_event(self, event):\n if event.event_id not in self.event_cache:\n self.event_cache[event.event_id] = event... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given `src_lines`, a list of lines of a single record, this will instantiate and populate an object corresponding to the data. | def __init__(self, src_lines):
self.study_id = None
self.citation = None
self.abstract = None
self.authors = []
self.study_matrices = {}
self.history_date = None
self.history_time = None
self.history_person = None
self.history_event = None
... | [
"def __init__(self, lines):\n next(lines) # seek to second line / throw away the header\n csv_reader = csv.DictReader(lines, fieldnames=['name'], restkey='data')\n self.data = list(csv_reader)",
"def __init__(self, src, line=1):\n self.src = src\n self.line = line",
"def from... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a string representing the key sequence used to get the specified message using the given dictionary | def messagetokeystring(message, keydict):
return ''.join([' ' + str(keydict[char])
if i - 1 >= 0
and str(keydict[char])[0]
== str(keydict[message[i - 1]])[0]
else str(keydict[char])
for i, char in enumerate(mes... | [
"def msg_key_to_string(msg):\n return json.loads(msg.key().decode('utf-8'))",
"def get_msg_key(plaintext, key, x=0):\n key_b = str(key).encode()\n plaintext_b = plaintext.encode()\n msg_key_large = sha256(key_b + plaintext_b).hexdigest()\n return msg_key_large[16:48]",
"def _compute_state_key(mes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a dict mapping each alphabet letter to the corresponding T9 number sequence | def getT9dict():
T9dict = {}
all_letters = string.lowercase
T9dict.update(mapkeystoletter(2, all_letters[0:3]))
T9dict.update(mapkeystoletter(3, all_letters[3:6]))
T9dict.update(mapkeystoletter(4, all_letters[6:9]))
T9dict.update(mapkeystoletter(5, all_letters[9:12]))
T9dict.update(ma... | [
"def get_conversion():\n return {r:i for i,r in enumerate('23456789TJQKA', start=2)}",
"def make_gematria() -> Dict[int, str]:\n return {char: i for i, char in enumerate(string.ascii_lowercase[:27], 1)}",
"def gen_char_dict():\n alphabet = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a dict mapping each key appropriately to each letter such that each letter is mapped to a string containing the key n number of times, where n is the position of the letter in the given letters string | def mapkeystoletter(key, letters):
return dict((v, ''.join([str(key) for i in range(k)]))
for k, v in enumerate(letters, 1)) | [
"def mapping_letter(letters):\n my_list = list(map(lambda x: x.upper(), letters))\n return dict(zip(letters, my_list))",
"def get_letter_counts(str_):\n return dict(Counter(str_))",
"def count_letters(s):\n return dict(Counter(s))",
"def ex_2(input_string: str) -> dict:\n characters_in_string =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the equality dunder method is correct for Resources. | def test_eq(self):
r1 = Resources(4, 2, {"Hadamard": 1, "CNOT": 1}, {1: 1, 2: 1}, 2, Shots(100))
r2 = Resources(4, 2, {"Hadamard": 1, "CNOT": 1}, {1: 1, 2: 1}, 2, Shots(100))
r3 = Resources(4, 2, {"CNOT": 1, "Hadamard": 1}, {2: 1, 1: 1}, 2, Shots(100)) # all equal
r4 = Resources(1, 2, ... | [
"def testEquality(self):\n pass",
"def __eq__(self, other:object) -> bool:\n\t\treturn isinstance(other, Resource) and self.ri == other.ri",
"def assert_equal_resource(res1, res2):\n assert isinstance(res1, FakedBaseResource)\n assert isinstance(res2, FakedBaseResource)\n assert res1.uri == res2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a not type error is raised if the class is initialized without a `resources` method. | def test_raise_not_implemented_error(self):
class CustomOpNoResource(ResourcesOperation): # pylint: disable=too-few-public-methods
num_wires = 2
class CustomOPWithResources(ResourcesOperation): # pylint: disable=too-few-public-methods
num_wires = 2
def resources(... | [
"def test_person_cannot_be_instantiated():\n with pt.raises(TypeError):\n Person()",
"def test_invalid_resource_type():\n tmpfile = _setup_config_file(\"\"\"\n[resource/test]\ntype = invalid\nauth = none\ntransport = local\nmax_cores_per_job = 1\nmax_memory_per_core = 1\nmax_walltime = 8\nmax... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the count resources method. | def test_count_resources(ops_and_shots, expected_resources):
ops, shots = ops_and_shots
computed_resources = _count_resources(QuantumScript(ops=ops, shots=shots))
assert computed_resources == expected_resources | [
"def test_get_resource_license_resource_count_list(self):\n pass",
"def test_get_resource_license_resource_count_by_moid(self):\n pass",
"def test_count(self):\n self._test_count_func(count)",
"def test_download_count_per_resource(self):\n\n for path, count in [('test1', 1), ('test... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clamp value between mini and maxi | def clamp(value, mini, maxi):
if value < mini:
return mini
elif maxi < value:
return maxi
else:
return value | [
"def clamp(x, mini, maxi):\n\n if maxi < mini:\n return x\n if x < mini:\n return mini\n if x > maxi:\n return maxi\n return x",
"def clamp(n, min_, max_):\n return max(min(max_,n),min_)",
"def clamp(min_value, max_value, value):\n return max(min_value, min(value, max_valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show a saved search. | def show(ctx, saved_search_id):
r = SavedSearch(ctx.obj['TOKEN'], ctx.obj['DEBUG']).show(saved_search_id)
click.echo(json_dumps(r, ctx.obj['PRETTY'])) | [
"def show(state, search_id):\n response = state.sdk.securitydata.savedsearches.get_by_id(search_id)\n echo(pformat(response[\"searches\"]))",
"def save_search(self):\n\n # Retrieve query which generated this view\n query = self.app.searchHandler.lastQueryExecuted\n\n # Create list containing desire... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a saved search. | def create(ctx, payload):
payload = parse_payload(ctx, payload)
r = SavedSearch(ctx.obj['TOKEN'], ctx.obj['DEBUG']).create(payload)
click.echo(json_dumps(r, ctx.obj['PRETTY'])) | [
"def test_create_saved_search(self):\n pass",
"def save_search(self):\n\n # Retrieve query which generated this view\n query = self.app.searchHandler.lastQueryExecuted\n\n # Create list containing desired identifier (from text box), and the query\n subList = [self.app.searchForm.infoWindowWidge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update a saved search. | def update(ctx, saved_search_id, payload):
payload = parse_payload(ctx, payload)
r = SavedSearch(ctx.obj['TOKEN'], ctx.obj['DEBUG']).update(payload)
click.echo(json_dumps(r, ctx.obj['PRETTY'])) | [
"def updateSearch(self, authenticationToken, search):\r\n pass",
"def test_update_saved_search(self):\n pass",
"def save(self, *args, **kwargs):\n self._update_search_tokens()\n super().save(*args, **kwargs)",
"def __on_query_edited(self):\n self.__refresh_search_results()",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a saved search. | def delete(ctx, saved_search_id):
r = SavedSearch(ctx.obj['TOKEN'], ctx.obj['DEBUG']).delete(saved_search_id)
click.echo(json_dumps(r, ctx.obj['PRETTY'])) | [
"def test_delete_saved_search(self):\n pass",
"def deletionsearch(ctx, apikey=None, conf_file=None, save=None):\r\n logger.info(\"Calling deletionsearch().\")\r\n call_api_method(\"deletionsearch\", apikey, conf_file=conf_file, save=save)",
"def removeSavedSearch(self, searchName):\n data = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extend the size of an image by adding borders. The sides argument defaults to | def add_border(image: np.ndarray, width=2, value=0, sides='ltrb'):
result = image
sides = sides.upper()
if 'L' in sides: result = add_left(result, width, value)
if 'T' in sides: result = add_top(result, width, value)
if 'R' in sides: result = add_right(result, width, value)
if 'B' in sides: resu... | [
"def add_border(input_img):\n print('\\n Adding border')\n left = 50\n top = left\n right = left\n bottom = 500\n border = (left, top, right, bottom)\n bimg = ImageOps.expand(input_img, border=border, fill='White')\n print('\\n Border: Done')\n return bimg",
"def add_border(original_img... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Horizontally concatenate a list of images with a border. This is similar to numpy's hstack except that it adds a border around each image. The borders can be controlled with the optional border_width and border_value arguments. See also vstack. | def hstack(images, border_width=2, border_value=0):
if border_width == 0: return np.hstack(images)
T, V = border_width, border_value
result = []
for image in images[:-1]:
result.append(add_border(image, T, V, 'LTB'))
result.append(add_border(images[-1], T, V))
return np.hstack(result) | [
"def vstack(images, border_width=2, border_value=0):\n if border_width == 0: return np.vstack(images)\n T, V = border_width, border_value\n result = []\n for image in images[:-1]:\n result.append(add_border(image, T, V, 'LTR'))\n result.append(add_border(images[-1], T, V))\n return np.vstac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Vertically concatenate a list of images with a border. This is similar to numpy's vstack except that it adds a border around each image. The borders can be controlled with the optional border_width and border_value arguments. See also hstack. | def vstack(images, border_width=2, border_value=0):
if border_width == 0: return np.vstack(images)
T, V = border_width, border_value
result = []
for image in images[:-1]:
result.append(add_border(image, T, V, 'LTR'))
result.append(add_border(images[-1], T, V))
return np.vstack(result) | [
"def hstack(images, border_width=2, border_value=0):\n if border_width == 0: return np.hstack(images)\n T, V = border_width, border_value\n result = []\n for image in images[:-1]:\n result.append(add_border(image, T, V, 'LTB'))\n result.append(add_border(images[-1], T, V))\n return np.hstac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compose a source image with alpha onto a destination image. | def compose(dst: np.ndarray, src: np.ndarray) -> np.ndarray:
a, b = ensure_alpha(src), ensure_alpha(dst)
alpha = extract_alpha(a)
result = b * (1.0 - alpha) + a * alpha
if dst.shape[2] == 3:
return extract_rgb(result)
return result | [
"def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):\r\n\r\n if not isinstance(source, (list, tuple)):\r\n raise ValueError(\"Source must be a tuple\")\r\n if not isinstance(dest, (list, tuple)):\r\n raise ValueError(\"Destination must be a tuple\")\r\n if not len(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate bandpass filters with adjustable length for given frequency ranges. This function returns for the given frequency band ranges the filter coefficients with length "filter_len". Thus the filters can be sequentially used for band power estimation. | def calc_band_filters(f_ranges, sfreq, filter_length="1000ms", l_trans_bandwidth=4, h_trans_bandwidth=4):
filter_list = list()
for f_range in f_ranges:
h = mne.filter.create_filter(None, sfreq, l_freq=f_range[0], h_freq=f_range[1], fir_design='firwin',
l_trans_ban... | [
"def _create_bandpass_filter(freqs, min_freq, max_freq):\n if freqs is None or not isinstance(freqs, np.ndarray) or not len(freqs.shape) == 1:\n _logger.debug(\"Wrong frequencies value. Must be a one dimensional numpy array\")\n raise ValueError(\"The given frequencies are invalid\")\n if min_fr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the database of People objects as a specified data type | def load_database(database_type):
f = open("database.p", "rb")
database = pickle.load(f)
f.close()
if database_type is "dict":
return database
elif database_type is "list":
return database.values() | [
"def test_loaded_types(self):\n self.assertTrue(all([type(p) == Person for p in self.loaded_data]))",
"def populate_persondata():\n\n logging.basicConfig(level=logging.INFO)\n logger = logging.getLogger(__name__)\n\n database = SqliteDatabase('personjob.db')\n\n logger.info('Working with Person... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait for container to be healthy. | def test_wait_for_healthy(main_container):
# This could take a while
TIMEOUT = 180
for i in range(TIMEOUT):
inspect = main_container.inspect()
status = inspect["State"]["Health"]["Status"]
assert status != "unhealthy", "The container became unhealthy."
if status == "healthy":... | [
"def wait_for_container(self):\n i = 0\n while True:\n ip_address = self.btcd_container.attrs[\"NetworkSettings\"][\"IPAddress\"]\n if ip_address.startswith(\"172\"):\n self.rpcconn.ipaddress = ip_address\n break\n self.btcd_container.relo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait for containers to exit. | def test_wait_for_exits(main_container, version_container):
assert (
version_container.wait() == 0
), "Container service (version) did not exit cleanly" | [
"def _wait_until_machine_finish(self):\n self.image._wait_for_machine_finish(self.name)\n # kill main run process\n self.start_process.kill()\n # TODO: there are some backgroud processes, dbus async events or something similar, there is better to wait\n # to provide enough time to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify the container outputs the correct version to the logs. | def test_log_version(version_container):
version_container.wait() # make sure container exited if running test isolated
log_output = version_container.logs().decode("utf-8").strip()
pkg_vars = {}
with open(VERSION_FILE) as f:
exec(f.read(), pkg_vars) # nosec
project_version = pkg_vars["__v... | [
"def _check_version_print(self, output, version):\n self.assertIn(version['id'], output)\n self.assertIn(version['status'], output)\n self.assertIn(version['url'], output)",
"def test_version(self):\n assert dockerprettyps.__version__\n assert dockerprettyps.version()",
"def v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify the container version label is the correct version. | def test_container_version_label_matches(version_container):
pkg_vars = {}
with open(VERSION_FILE) as f:
exec(f.read(), pkg_vars) # nosec
project_version = pkg_vars["__version__"]
assert (
version_container.labels["org.opencontainers.image.version"] == project_version
), "Dockerfile... | [
"def version_match(self, container: Container) -> bool:\n if f'nvidia/bobber:{version}' not in container.image.tags:\n return False\n return True",
"def check_cluster_kubernetes_version(admin_mc):\n client = admin_mc.client\n cluster = client.by_id_cluster(\"local\")\n version = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the main splash page. | def test_splash_page(self):
response = self.testapp.get('/')
self.assertEqual(response.status_int, 200)
response.mustcontain(
'Bite-sized learning journeys',
'Browse the explorations gallery', '100% free!',
'Learn', 'About', 'Contact',
# No navbar ... | [
"def main():\r\n test = Splashscreen()\r\n test.main()",
"def test_main_app(self):\n resp = self.app.get('/')\n # ensure relevant pieces of UI are returned\n assert 'Foggy Fork' in resp.data\n assert 'A San Francisco Food Truck Map' in resp.data\n assert 'Where in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accepts list of nested dictionaries and produces a single dictionary containing mean values and estimated errors from these dictionaries. Errors are estimated as confidence intervals lengths. | def dict_recur_mean_err(dlist):
if isinstance(dlist[0], dict):
res_dict = {}
for k in dlist[0]:
n_dlist = [d[k] for d in dlist]
res_dict[k] = dict_recur_mean_err(n_dlist)
return res_dict
else:
n = len(dlist)
mean = float(sum(dlist)) / n
var... | [
"def average_dictlist(dict_list):\r\n avg=sum(dict_list)/len(dict_list)\r\n return avg",
"def mean_dict(dicts):\n keys = keyset(dicts, typed=True) # list of keys and types\n dicts = [normalize_keys(d, keys) for d in dicts] # make sure we have the same keys\n mean = {}\n for k,t in keys:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to connect reach from/to wastewater network elements | def connect_reach(self, reach_id, from_id=None, to_id=None):
data = {}
if from_id is not None:
data['rp_from_fk_wastewater_networkelement'] = from_id
if to_id is not None:
data['rp_to_fk_wastewater_networkelement'] = to_id
self.update('vw_qgep_reach', data, reach_... | [
"def _linkConnectEcoCell(self):",
"def navigate_to_network_then_to_interfaces(driver):\n driver.find_element_by_xpath('//mat-list-item[@ix-auto=\"option__Network\"]').click()\n wait_on_element(driver, 0.5, 30, '//mat-list-item[@ix-auto=\"option__Interfaces\"]')\n driver.find_element_by_xpath('//mat-list-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolve activelink values into x and y directions. Takes a set of values defined on active links, and returns those values | def resolve_values_on_active_links(grid, active_link_values):
link_lengths = grid.length_of_link[grid.active_links]
return (
np.multiply(
(
(
grid.node_x[grid._activelink_tonode]
- grid.node_x[grid._activelink_fromnode]
... | [
"def resolve_values_on_links(grid, link_values):\n return (\n np.multiply(\n (\n (\n grid.node_x[grid.node_at_link_head]\n - grid.node_x[grid.node_at_link_tail]\n )\n / grid.length_of_link\n ),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolve link values into x and y directions. Takes a set of values defined on active links, and returns those values | def resolve_values_on_links(grid, link_values):
return (
np.multiply(
(
(
grid.node_x[grid.node_at_link_head]
- grid.node_x[grid.node_at_link_tail]
)
/ grid.length_of_link
),
link_valu... | [
"def resolve_values_on_active_links(grid, active_link_values):\n link_lengths = grid.length_of_link[grid.active_links]\n return (\n np.multiply(\n (\n (\n grid.node_x[grid._activelink_tonode]\n - grid.node_x[grid._activelink_fromnode]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Temporary fix until master of pyzmq is released | def fix_zmq_exit():
import zmq
ctx = zmq.Context.instance()
ctx.term() | [
"def zmq_setup(self):\n pass",
"def zmq():\n with lcd('/tmp'):\n local('wget http://download.zeromq.org/zeromq-3.2.0-rc1.tar.gz;'\n 'tar xf zeromq-3.2.0-rc1.tar.gz')\n with lcd('zeromq-3.2.0'):\n local('chmod -R 777 .')\n local('./autogen.sh ; ./configure... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies filters and stores job postings in a database job_list a list of Job_Posting objects avoids saving duplicate job postings into the database by hashing job_description creates the database if it does not exist yet | def store_data(job_list):
if not job_list:
raise ValueError('Job list is empty. To proceed, it must contain at least one item.')
if not isfile('/data/visited_jobs.db'):
print('DB not found')
ds.create_db()
accepted, not_accepted = 0, 0
for job in job_list:
jo... | [
"def job_list(self, job_list):\n self._job_list = job_list",
"def updateJobDB(request,Q={}):\n\tuser = request.user\n\t# Get metadata\n\tresponse = agaveRequestMetadataList(user,Q=Q)\n\t# Add job if not in db\n\tfor metadata in response['result']:\n\t\tvalue = metadata['value']\n\t\tif 'jobName' in value a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets two positive integer numbers m and n (m > n). Returns True if they are coprime, otherwise, returns False. | def coprime(m,n):
# The function uses the Euclid's algorithm for finding the greatest common divisor. The algorithm is recursive.
# If the GCD is 1, when the numbers are coprime. If it is greater than 1, when the numbers aren't coprime.
if n == 0 and m > 1:
return False
elif n == 0 and m ==... | [
"def coprime(n, m):\n return gcd(n, m) == 1",
"def coprime(num1, num2):\n return gcd(num1, num2) == 1",
"def coprime(a: int, b: int):\n\n return euclid(a, b) == 1",
"def coprime(a:int, b:int):\n \n if euclid(a, b) == 1:\n return True\n else:\n return False",
"def coprime(a, b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a shift from a datetime. | def from_datetime(cls, position, datetime):
return cls(
position = position,
date = datetime.date(),
name = position.shiftForTime(datetime.time()),
) | [
"def create_realized_shift(self, date):\n newshift = copy.copy(self)\n newshift.date = date\n return newshift",
"def timeshift(self, shift='random'):\n\n if shift == 'random':\n one_month = pd.Timedelta('30 days').value\n two_years = pd.Timedelta('730 days').value... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
LSTM over tweet only | def get_model_tweetonly(batch_size, max_seq_length, input_size, hidden_size, target_size,
vocab_size, pretrain, tanhOrSoftmax, dropout):
# batch_size x max_seq_length
inputs = tf.placeholder(tf.int32, [batch_size, max_seq_length])
cont_train = True
if pretrain == "pre":
... | [
"def LSTM_train(X_train, Y_train, X_dev, Y_dev, R_train, R_dev, hyperparams):",
"def customLSTM(dim):\n regularizer = tf.keras.regularizers.l1_l2(l1=1e-4, l2=1e-3)\n cell = Mod_LSTMCELL(dim, dropout=0.5, kernel_regularizer=regularizer, recurrent_regularizer=regularizer)\n lstm = RNN(cell, return_sequence... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get teams owned by the account. | def get_teams(self, account_id):
endpoint = '/accounts/{}/teams'.format(account_id)
return self._api_call('get', endpoint) | [
"def get_teams(self):\n url = 'teams'\n result = self.get(url)\n return result.get('teams', result)",
"async def _fetch_user_teams(self, access_token, token_type):\n headers = self.build_userdata_request_headers(access_token, token_type)\n next_page = url_concat(\n \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get projects owned by the team. | def get_projects(self, team_id):
endpoint = '/teams/{}/projects'.format(team_id)
return self._api_call('get', endpoint) | [
"def get_user_projects(self):\n return self.projects.all()",
"def getProjects(self , teamindex = 0):\r\n if self.userdata == {}:\r\n self.reloadUserdata()\r\n projects = self.userdata['user']['teams'][teamindex]['projects']\r\n return projects",
"def getProjects(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an asset by id. | def get_asset(self, asset_id):
endpoint = '/assets/{}'.format(asset_id)
return self._api_call('get', endpoint) | [
"def get_asset(self, asset_id):\n text, code = ApiClient(self._config, 'assets/' + asset_id).get()\n return Asset.deserialize(text)",
"def get_asset(self, asset_id, asset_type):\n return self.asset(asset_id, asset_type=asset_type)",
"def find_asset_by_id(self, asset_id):\n return sup... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an asset's children. | def get_asset_children(self, asset_id):
endpoint = '/assets/{}/children'.format(asset_id)
return self._api_call('get', endpoint) | [
"def children(self) -> \"AssetList\":\n return self._cognite_client.assets.list(parent_ids=[self.id], limit=None)",
"def children(self):\n with qdb.sql_connection.TRN:\n sql = \"\"\"SELECT artifact_id\n FROM qiita.parent_artifact\n WHERE parent_id =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload an asset. The method will exit once the file is uploaded. | def upload(self, asset, file):
uploader = FrameioUploader(asset, file)
uploader.upload() | [
"def upload_asset(self, content_type, name, asset):\n headers = Release.CUSTOM_HEADERS.copy()\n headers.update({'Content-Type': content_type})\n url = self.upload_urlt.expand({'name': name})\n r = self._post(url, data=asset, json=False, headers=headers,\n verify=Fal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an asset's comments. | def get_comments(self, asset_id):
endpoint = '/assets/{}/comments'.format(asset_id)
return self._api_call('get', endpoint) | [
"def get_comments(self):\n\t\treturn self._client.get_comments(self)",
"def getComments(self):\n\n # Loop over the comment segments \n comments = []\n for com_seg in self.segments[SEG_NUMS[\"COM\"]]:\n comments.append(com_seg.getData())\n\n # Return None if no comment was found, or a list with co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the review links of a project | def get_review_links(self, project_id):
endpoint = '/projects/{}/review_links'.format(project_id)
return self._api_call('get', endpoint) | [
"def review_links():",
"def get_review_urls(self, pagenum):\n\t\t\n\t\tfor i in range(self.num_retrys):\n\t\t\tpage = requests.get(self.reviews_pageroot, \n\t\t\t\theaders = self.httpheaders, \n\t\t\t\tparams = dict(page = pagenum)\n\t\t\t)\n\t\t\ttime.sleep(self.timeout)\n\t\t\tif page.status_code == 200:\tbreak... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a review link. | def create_review_link(self, project_id, **kwargs):
endpoint = '/projects/{}/review_links'.format(project_id)
return self._api_call('post', endpoint, payload=kwargs) | [
"def review_link(self, review_link):\n\n self._review_link = review_link",
"def review_links():",
"def test_supplier_review_list_view_has_create_link(self):\n s1 = create_supplier(\"Supplier A\")\n response = self.client.get(reverse('reviews:supplier_reviews', kwargs={'slug': s1.slug}))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a single review link | def get_review_link(self, link_id, **kwargs):
endpoint = '/review_links/{}'.format(link_id)
return self._api_call('get', endpoint, payload=kwargs) | [
"def get_review_url(self):\n return self.review_url + self.slug",
"def review_links():",
"def _getReviewTitle(self):\n try:\n return re.search('reviewLink\">\"(.+?)\"</a>', self.reviewHTML).group(1)\n except:\n return ''",
"def get_content_object_url(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add or update assets for a review link. | def update_review_link_assets(self, link_id, **kwargs):
endpoint = '/review_links/{}/assets'.format(link_id)
return self._api_call('post', endpoint, payload=kwargs) | [
"def review_link(self, review_link):\n\n self._review_link = review_link",
"def review_links():",
"def update_link(self, link):",
"def update_asset(self, asset_node: \"Asset\"):\n pass",
"def add(self, link):\n # if path.exists(self.cachefile):\n with open(self.cachefile, 'a') as... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get items from a single review link. | def get_review_link_items(self, link_id):
endpoint = '/review_links/{}/items'.format(link_id)
return self._api_call('get', endpoint) | [
"def _parse_reviewers(self, content):\n soup = bs(content, ['fast', 'lxml'])\n table = soup.find('table', {'id': 'productReviews'})\n reviewers = [link['href'] for link in table.findAll('a')\\\n if link.contents == ['See all my reviews']]\n return reviewers",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an imaging server fqdn, get its ID; raises NotFound if not found. | def get_id(self, fqdn):
res = self.db.execute(sqlalchemy.select([ model.imaging_servers.c.id ],
whereclause=(model.imaging_servers.c.fqdn==fqdn)))
return self.singleton(res) | [
"def find_imaging_server_id(name):\n conn = sql.get_conn()\n\n # try inserting, ignoring failures (most likely due to duplicate row)\n try:\n conn.execute(model.imaging_servers.insert(),\n fqdn=name)\n except sqlalchemy.exc.SQLAlchemyError:\n pass # probably already exists\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of the fqdn's of all imaging servers | def list(self):
res = self.db.execute(select([model.imaging_servers.c.fqdn]))
return self.column(res) | [
"def all_imaging_servers():\n res = sql.get_conn().execute(select([model.imaging_servers.c.fqdn]))\n return [ row['fqdn'] for row in res.fetchall() ]",
"def dns_servers(self) -> List[str]:\n # Read all local dns servers\n servers: List[str] = []\n for config in self.sys_dbus.network.dns... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Place various obstacles. E.g. put in rectangles which block the line of site of the towers. | def place_obstacles():
#Randomly generate different sized rectangles
#Soem may overlap, which gives more variety in shape of obstacles
xvals = np.random.randint(0,self.map_dimensions[1],size=self.N_obstacles)
yvals = np.random.randint(0,self.map_dimensions[0],size=self.N_... | [
"def __draw_obstacles(self):\n self.canvas.delete(OBSTACLES_TAG)\n for i in range(0, PACMAN_BOARD_SIDE_SQUARES_NUMBER):\n for j in range(0, PACMAN_BOARD_SIDE_SQUARES_NUMBER):\n if self.board[j][i] == 1:\n self.canvas.create_rectangle(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Place the target locations | def place_targets():
coords = []
while len(coords)<self.N_targets:
x = np.random.randint(self.BORDER_MARGIN,self.map_dimensions[1]+1-self.BORDER_MARGIN,size=1)[0]
y = np.random.randint(self.BORDER_MARGIN,self.map_dimensions[0]+1-self.BORDER_MARGIN,si... | [
"def find_targets(self):\n for asteroid in self.asteroid_map:\n self.targets.append([angle(self.station, asteroid),\n distance(self.station, asteroid),\n asteroid])",
"def setTargets(self):",
"def update_targets(self, targets):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Place the potential tower locations. These are the locations where towers can potentially be placed. Not every location is necesarily used (only when N_tower_sites = N_towers). THe optimization problem is to determine which of these possible locations to use. | def place_allowed_tower_sites():
self.coordinates__tower_sites = []
for tk in xrange(self.N_tower_kinds):
#Each kind of tower will have the correct number of sites placed
coords = []
while len(coords)<self.N_tower_sites[tk]:
... | [
"def get_safe_locations(self):\n if not self.is_wumpus_alive:\n return self.no_pit_locations\n else:\n if self.possible_wumpus_locations:\n return self.no_pit_locations.difference(self.possible_wumpus_locations)\n else:\n return self.no_pi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return True if r1 r2 line of sight is obstrucetd; oherwise False | def check_obstructed(r1,r2):
if r1==r2:
return False
#Densely sample line connecting r1 and r2.
#If any of those sampled points is inside the rectangle, then the
#line of sight intersects the rectangle and the tower's... | [
"def line_segment_touches_or_crosses_line(a: LineSegment, b: LineSegment) -> bool:\n return (\n is_point_on_line(a, b.p1)\n or is_point_on_line(a, b.p2)\n or (is_point_right_of_line(a, b.p1) ^ is_point_right_of_line(a, b.p2))\n )",
"def properly_intersects(self, other: 'LineSegment') ->... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visualize the map environment and solved tower locations. env_state = 'solved', 'initial' | def visualize_environment(self,env_state):
fig=plt.figure(figsize=self.figsize)
ax=plt.subplot(111)
#Plot the targets
plt.plot([i[0] for i in self.coordinates__targets],\
[i[1] for i in self.coordinates__targets],\
marker='x',markersize=15,linestyle='Non... | [
"def visualize_world(self, brain):\n state_str = ' || '.join([str(self.sensors),\n str(self.actions),\n str(self.reward),\n str(self.size),\n str(self.color),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the whole scenario. Initialize map, solve placement, visualize everything. | def run_scenario(self):
self.initialize_random_map()
self.visualize_environment('initial')
self.get_tower_target_coverages()
self.solve_environment()
self.visualize_environment('solved') | [
"def run(self):\n self.simulate_test_data()\n self.pipeline_test_data()\n self.plot_jump_flags_image()\n self.plot_groupdq_flags(pixel=[884, 550])\n self.plot_ramps_pre_post_correction(pixel=[884, 550])",
"def main():\n move_to_beeper()\n place_in_puzzle()\n return_to_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converting from cv2 image class to yolo image class | def _convert_to_yolo_img(self, img):
img = img / 255.0
h, w, c = img.shape
img = img.transpose(2, 0, 1)
outimg = make_image(w, h, c)
img = img.reshape((w*h*c))
data = c_array(c_float, img)
outimg.data = data
rgbgr_image(outimg)
return outimg | [
"def yolo(image, classes=\"src/yolo/classes.txt\", config=\"src/yolo/yolo.cfg\", weights=\"src/yolo/yolov3.weights\"):\n\n with open(classes, 'r') as in_file:\n classes = [line.strip() for line in in_file.readlines()]\n\n Width = image.shape[1]\n Height = image.shape[0]\n scale = 0.00392\n\n n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Predicting from cv2 format | def predict_from_cv2(yolo, inputfilepath):
print("call func of predict_from_cv2")
img = cv2.imread(inputfilepath)
yolo_results = yolo.predict(img)
for yolo_result in yolo_results:
print(yolo_result.get_detect_result()) | [
"def read_and_predict(img,model,conf_thresh,dist_thresh,K):\n img = cv2.imread(img, cv2.IMREAD_GRAYSCALE)\n img[img<255/2] = 0\n img[img>255/2] = 255\n mask_dim = img.shape[0]\n pred = interpret(model.predict(cv2.bitwise_not(img)[None].astype('float32')),\n conf_thresh = conf_thresh, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Predicting from PIL format | def predict_from_pil(yolo, inputfilepath):
print("call func of predict_from_pil")
img = np.array(Image.open(inputfilepath))
yolo_results = yolo.predict(img)
for yolo_result in yolo_results:
print(yolo_result.get_detect_result()) | [
"def predict_image(image):\n global graph\n with graph.as_default():\n img_out = image / 255.\n return dl_model.predict_classes(img_out.reshape(1, 1, 48, 48))",
"def predict(input_shape, model, image_path):\n \n # Load and resize the image using PIL.\n img = PIL.Image.open(image_path... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch a single user's data if a user_id is specified. Otherwise fetch the list of all users. Returned info contains user_id, name, group name,email, admin status, and date_created. | def get(self, user_id):
if user_id:
return get_from_user_id(user_id)
else:
# No user_id given; this is a GET all users request.
if not current_user.is_admin:
error(403, "Logged in user not admin ")
user_db_data = user_db_util.fetchall(g.da... | [
"def fetch_user_data(self):\n request_uri = '/api/user/%s' % self.user_id\n request_parameters = {}\n response = self._call_api(request_uri, request_parameters)\n\n return response",
"async def fetch_user(self, id: str):\n user = await self.http.get_user(id)\n return User... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new user with provided email, password, and admin flag. If required fields are missing in the request, return 400 Password must be 8 or more characters long. Otherwise return 422 Email must not already be in use by an existing user. Otherwise return 422 If success, return 201 with the new user's email, admin f... | def post(self):
data = request.get_json()
if data is None:
error(400, "No json data in request body")
check_data_fields(data, ["email", "name", "group_name", "password", "admin"])
if len(data["password"]) < 8:
error(422, "New password is less than 8 characters... | [
"def create_user():\n record = request.get_json()\n if record is None:\n return {\"Error\": \"No data Supplied.\"}, 400\n\n schema = user_schema.load(record)\n\n if UserModel.objects(email=schema['email']):\n return {\"Error\": \"User Data already exists.\"}, 400\n user = UserModel(**s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Distatches an event to any matching event handlers. The handler which specifically matches the event name will be called first, followed by any handlers with a 'match' method which matches the event name concatenated to the args string. | def dispatch(self, event, args=''):
try:
if event in self.events:
self.events[event](args)
for matcher, action in self.eventmatchers.iteritems():
ary = matcher.match(' '.join((event, args)))
if ary is not None:
action(*a... | [
"def run_handlers(self, event, method=EVENT_CAPTURE):\n if event not in self.events:\n return None\n for handler in self.events[str(event)].with_method(method):\n handler(event)",
"def dispatch(event):\n logger.info(\"%s: Dispatched\", event)\n for etype in event.__class_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enters the event loop, reading lines from wmii's '/event' and dispatching them, via dispatch, to event handlers. Continues so long as alive is True. | def loop(self):
keys.mode = 'main'
for line in client.readlines('/event'):
if not self.alive:
break
self.dispatch(*line.split(' ', 1))
self.alive = False | [
"async def raw_event_handler(self):\n self.log.info(\"Raw Event Handler started\")\n while True:\n event = await self.buffers.raw.aget()\n self.notify_listeners(event)\n self.log.debug(\"Raw Event handler called\")\n\n if event.name == \"kytos/core.shutdown\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Binds a number of event handlers for wmii events. Keyword arguments other than 'items' are added to the 'items' dict. Handlers are called by loop when a matching line is read from '/event'. Each handler is called with, as its sole argument, the string read from /event with its first token stripped. | def bind(self, items={}, **kwargs):
kwargs.update(items)
for k, v in flatten(kwargs.iteritems()):
if hasattr(k, 'match'):
self.eventmatchers[k] = v
else:
self.events[k] = v | [
"def add_handler(self, fd, handler, events):\n ...",
"def _register_handlers(self):\n DBG(\"\\nregister handlers\")\n for hook, handler in self.handlers:\n g.registerHandler(hook, handler)\n\n signal_manager.connect(self.c, 'body_changed', self._after_body_key)",
"def setu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A decorator which binds its wrapped function, as via bind, for the event which matches its name. | def event(self, fn):
self.bind({fn.__name__: fn}) | [
"def on_event(self, name):\n def wrapper(func):\n self.listen_for(name, func)\n return func\n return wrapper",
"def event_handler(event_name):\n\n def wrapper(func):\n func._event_handler = True\n func._handled_event = event_name\n return func\n\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Binds a series of keys for the given 'mode'. Keys may be specified as a dict or as a sequence of tuple values and strings. In the latter case, documentation may be interspersed with key bindings. Any value in the sequence which is not a tuple begins a new key group, with that value as a description. A tuple with two va... | def bind(self, mode='main', keys=(), import_={}):
self._add_mode(mode)
mode = self.modes[mode]
group = None
def add_desc(key, desc):
if group not in mode['desc']:
mode['desc'][group] = []
mode['groups'].append(group)
if key not in m... | [
"def bind_modifiers(widget, event:Callable, button='Button-1',\n modes=frozendict({'Shift': KeyModes.SHIFT, 'Control': KeyModes.CONTROL, 'Alt': KeyModes.ALT, })):\n widget.bind(button, event)\n for modifier, keymode in modes.items():\n # We must provide 'keymode' as a default argument... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls a method named for the first token of 'args', with the rest of the string as its first argument. If the method doesn't exist, a trailing underscore is appended. | def _call(self, args):
a = args.split(' ', 1)
if a:
getattr(self, a[0])(*a[1:]) | [
"def _func_named(self, arg):\n result = None\n target = 'do_' + arg\n if target in dir(self):\n result = target\n else:\n if self.abbrev: # accept shortened versions of commands\n funcs = [func for func in self.keywords if func.startswith(arg) and fu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the access key as key=your_googlemaps_key. This must be called prior to contacting the API. | def set_api_access_keys(**kwargs):
API_BASE_PARAMS['key'] = kwargs['key'] | [
"def update_google_api_key(self):\n from ...main import add_api_key\n add_api_key(\"google_api_key\", self.google_api_key.get())",
"def set_api_key(self, api_key):\n self.params['api_key'] = api_key",
"def SetAPIKey(self, api_key):\n self._api_key = api_key",
"def set_api_key(key):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process response from authority API and return a list of humanreadable addresses for any matches. Raise GeoAuthorityError with an appropriate message otherwise. | def parse_location_response(self, location_json):
street_addresses = []
try:
if location_json['status'] == 'ZERO_RESULTS':
return []
elif location_json['status'] != 'OK':
self.logger.error("Unexpected response status: %s", location_json['status'])
... | [
"def parse_reverse_geocodes(response):\n data = parse_json(response, required_keys=[\"geocodePoints\"])\n _check_for_errors(data, response)\n records = data.get(\"geocodePoints\")\n records = [\n {\n _map_field(key): value\n for key, value in record.items()\n }\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the three final Libraries. | def createIntermediateLibraries(LISTPRELIBRARIES, DICOLIBRARIES, CONFIG, DICOFINALCLASSIF):
#### Parse all the intermediate libraries files
for preLibrary in LISTPRELIBRARIES:
#### Retrieve the final classification name of the ET from the file name
finalClassification = os.path.basename(preLibrary).split(".fasta"... | [
"def createFinalLibraries(INTERMEDIATELIBRARIES, DICOLIBRARIES):\n\t#### Parse all the intermediate libraries files\n\tfor file in INTERMEDIATELIBRARIES:\n\t\tfileName = os.path.basename(file).split(\".fasta\")[0]\n\t\t#### Read and store the fasta sequences of the prelibraries\n\t\tsequences=readInput.readFasta(fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply the cdhitest on all the intermediate Libraries. | def applyCDHIT(INTERMEDIATELIBRARIES):
#### Apply cd-hit-est for all the intermediate library
for file in INTERMEDIATELIBRARIES:
fileName = os.path.basename(file).split(".fasta")[0]
os.chdir("classification_result/intermediateLibraries/")
subprocess.call('cdhit-est -aS 0.9 -c 0.9 -g 1 -r 1 -i {input}.fasta -o {... | [
"def test_all():\n failed_command = False\n for runtime, toolkits in supported_combinations.items():\n for toolkit in toolkits:\n args = [\n '--toolkit={}'.format(toolkit),\n '--runtime={}'.format(runtime),\n ]\n try:\n test_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the three final Libraries. | def createFinalLibraries(INTERMEDIATELIBRARIES, DICOLIBRARIES):
#### Parse all the intermediate libraries files
for file in INTERMEDIATELIBRARIES:
fileName = os.path.basename(file).split(".fasta")[0]
#### Read and store the fasta sequences of the prelibraries
sequences=readInput.readFasta(file)
#### Save the ... | [
"def createIntermediateLibraries(LISTPRELIBRARIES, DICOLIBRARIES, CONFIG, DICOFINALCLASSIF):\n\t#### Parse all the intermediate libraries files\n\tfor preLibrary in LISTPRELIBRARIES:\n\t\t#### Retrieve the final classification name of the ET from the file name\n\t\tfinalClassification = os.path.basename(preLibrary)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return df with all enteries which df.query(pattern) match with removed | def remove(df, pattern):
return df[~df.index.isin(df.query(pattern).index)] | [
"def prune(df, regex_list):\n for regex_pattern in regex_list:\n df = df[~df.case_action.str.contains(regex_pattern)]\n return df",
"def FilterBy(df, **kwargs):\n for column, pattern in kwargs.items():\n if pattern is not None:\n df = df[df[column].str.match(fnmatch.translate(pattern), case=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split design by subexperiment (1, 2, 3) and create SubExperiment objects | def create_subexperiments(self):
subexperiments = {}
for label, df in self.design.groupby(level=0):
subexperiments[label] = SubExperiment(label, df.loc[label], self.root)
return subexperiments | [
"def set_sub_models(self):\r\n sub_data_grid = [0.1 * i for i in range(1, 10)]\r\n self.sub_models = [\r\n copy.deepcopy(self.model_) for _ in range(len(sub_data_grid))]\r\n # fit sub-models to subset of data\r\n for key, data_size in enumerate(sub_data_grid):\r\n X, _,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get baseline data without treatment time courses | def baseline(self):
return self.data[self.data['treatment'] == 'Baseline'] | [
"def emissions_baseline(self):\n baseline = DataFrame(columns=[\"CO2\", \"NOx\", \"PM10\", \"PM2.5\", \"SO2\"])\n baseline = baseline.append(year_1(self.plant.emissions()))\n baseline = baseline.append(year_1(self.plant.fuel_reseller().emissions()))\n baseline = baseline.append(year_1(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |