query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
r""" Setter for the ground truth shape associated to the image. | def gt_shape(self, value):
self._gt_shape = value | [
"def _format_groundtruth_data(self, true_image_shapes):\n groundtruth_boxlists = [\n box_list_ops.to_absolute_coordinates(\n box_list.BoxList(boxes), true_image_shapes[i, 0],\n true_image_shapes[i, 1])\n for i, boxes in enumerate(\n self.groundtruth_lists(fields.Box... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Returns the final fitting cost. | def final_cost(self):
return self.algorithm_results[-1].final_cost | [
"def end_point_cost(self, ti, xi, tf, xf, f_prm):\n\t\tmf = xf[-1]\n\t\treturn - mf / self.mass0",
"def get_cost(self) -> float:\n if self.pulp_problem.status == pulp.LpStatusNotSolved: # Not solved\n raise ValueError(\"Cannot get the cost of an unsolved problem\")\n return sum(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Returns the initial fitting cost. | def initial_cost(self):
return self.algorithm_results[0].initial_cost | [
"def cost(params):\n\n # get the F(x) response\n Fx = model(params)\n\n # compute goodness of fit\n return scale * (Fx - G)**2",
"def current_cost(self) -> float:\n return calculate_cost(self.population[0], self.settings)",
"def __compute_initial_learning_rate__(self):\n eigen_values =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" The list containing the warped images obtained at each fitting iteration. | def warped_images(self):
mask = self.algorithm_results[-1].fitter.template.mask
transform = self.algorithm_results[-1].fitter.transform
interpolator = self.algorithm_results[-1].fitter.interpolator
warped_images = []
for s in self.shapes():
transform.set_target(s)
... | [
"def warped_images(self):\n mask = self.fitter.template.mask\n transform = self.fitter.transform\n interpolator = self.fitter.interpolator\n return [self.image.warp_to(mask, transform.from_vector(p),\n interpolator=interpolator)\n for p in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" The list containing the appearance reconstruction obtained at each fitting iteration. | def appearance_reconstructions(self):
return flatten_out(
[f.appearance_reconstructions for f in self.algorithm_results]) | [
"def appearance_reconstructions(self):\n if self.appearance_parameters:\n return [self.fitter.appearance_model.instance(w)\n for w in self.appearance_parameters]\n else:\n return [self.fitter.template for _ in self.shapes]",
"def getDisplacements(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" The list containing the error images obtained at each fitting iteration. | def error_images(self):
return flatten_out(
[f.error_images for f in self.algorithm_results]) | [
"def errors(self):\n return [thread.err for thread in self._threads]",
"def get_errors(self):\n result = []\n for error in self.errors:\n result.append(os.path.basename(error[0]) +\n ':\\n ' + str(error[1]) + '\\n')\n return result",
"def get_all... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get schema name from table_name, the default schema name is public | def _get_schema_name(self, table_name):
items = table_name.split('.')
if len(items) == 2:
return items[0]
else:
return 'public' | [
"def get_schema_name(self):\n obj = self._get_db_obj_query().first()\n return obj.schema_name if obj else None",
"def get_schema_name(cls, url: URL) -> Optional[str]:\n schema = None\n database = url.database\n if cls.supports_schemas and database is not None and \"/\" in databa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Joue le tour de l'ennemi | def tour(self, lieu):
if random.randint(0, 100) <= self.agressivite: # si l'ennemi attaque
persos_l = self.game.get_all_persos_lieu(lieu) # on recupere tous les persos dans ce lieu
#
if len(persos_l) >= 1: # s'il y a des persos dans ce lieu
# on va d'abord ... | [
"def jouer(self, joueur, colonne):\n colonne -= 1 # offset\n if colonne > self.largeur-1:\n colonne = self.largeur-1\n elif colonne < 0:\n colonne = 0\n\n for y in range(0, self.hauteur):\n if self.grille[y][colonne] == EMPTY:\n self.grille... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute command on node. | def execute(self, command):
Execution.__log.info('Executing command on node %s..' % self.hostname)
return self._execute(command) | [
"def run_command(self, host, command):\n return self.remote_executor.run(host, command)",
"def execute_basic(self, node_context):\n raise NotImplementedError('execute() must be implemented')",
"def execute(self, name, command):\n if name in [\"localhost\"]:\n r = '\\n'.join(sh.sh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return OrderedDict of the groups and variables in Fortran namelist files. | def nmldict(nmlfnames):
if isinstance(nmlfnames, str):
nmlfnames = [nmlfnames]
nmlall = collections.OrderedDict() # dict keys are nml paths, values are Namelist dicts
for nml in nmlfnames:
nmlall[nml] = f90nml.read(nml)
if len(nmlall[nml]) == 0:
warnings.warn('{} does n... | [
"def generate_namelist():\n dataset_path = os.path.abspath(os.path.join(cwd, os.pardir)) + \"/data/\"\n f = h5py.File(dataset_path + \"dexnet_2_database.hdf5\", 'r')\n dataset = f['datasets']\n dataset_names = ['3dnet', 'kit']\n obj_list = np.load(os.getcwd() + \"/name_list.npy\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inplace remove all Namelists that are the same as the previous one in nmlall. Does nothing if nml is not an OrderedDict. | def nmlprune(nmlall, ignore={}):
if len(nmlall) > 1:
idx = 0
while True:
# need deepcopy to avoid in-place modification by nmldiff
pair = copy.deepcopy(collections.OrderedDict(
itertools.islice(nmlall.items(), idx, idx+2)))
for group in ign... | [
"def remove_duplicates(self):\n seen = set()\n self.nodes = [x for x in self.nodes if x not in seen and not seen.add(x)]",
"def nmldict(nmlfnames):\n if isinstance(nmlfnames, str):\n nmlfnames = [nmlfnames]\n\n nmlall = collections.OrderedDict() # dict keys are nml paths, values are Na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reduces a list of DNA sequences to ones with CG content in the range (lower,upper). Verbose prints the actual content | def CGContent(lst,lower,upper, verbose=True):
newlist=[]
for item in lst:
cont=0
for char in item:
if char=="G" or char=="C":cont=cont+1
cont=cont/float(len(item))
if (lower<cont) & (cont<upper):
newlist=newlist+[item]
if verbose==True: print ... | [
"def cleanSeq(seq, db):\n #print repr(seq)\n if seq.startswith(\"random\"):\n seq = rndSeq(800)\n lines = seq.strip().splitlines()\n #print \"<br>\"\n #print \"before fasta cleaning\", \"|\".join(lines)\n if len(lines)>0 and lines[0].startswith(\">\"):\n line1 = lines.pop(0)\n #pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the key of dictionary dic given the value | def find_key(dic, val):
#
#
return [k for k, v in dic.iteritems() if v == val][0] | [
"def find_key(dic, val):\n\treturn [k for k, v in dic.items() if v == val][0]",
"def find_first_key_of_a_value(val: int, d: dict) -> str:\n\n for k, v in d.items():\n if v == val:\n return k\n\n raise IndexError(\"Variable, val, must be a key in dictionary, d\")",
"def key(dict_, key_):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sort a dictionary's values by the order of the keys in it. | def sortedDictValues(adict):
keys = adict.keys()
keys.sort()
return map(adict.get, keys) | [
"def sort_dictionary(dct):\r\n key_list = []\r\n for i in range(0, len(dct)):\r\n dct[dct.keys()[i]].sort()\r\n key_list.append(dct.keys()[i])\r\n key_list.sort()\r\n return key_list",
"def sort_dict_by_keys(adict):\n return collections.OrderedDict(sorted(adict.items(), key=lambda t: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
passes a DNA sequence to the external MELTING Java app and returns the approximate melting temperature, entropy and enthalpy. Default values for Mg++ and DNA concentration can be adjusted as well as the location of the melting5.jar | def TMelt(string, mg="12.5e-3", conc="5e-7", meltdir=testdir+'../MELTING5.0.3/executable', comp='', verbose=False):
thisdir=os.getcwd()
#os.chdir(meltdir)
#if os.path.exists('melttemp.txt'): os.remove('melttemp.txt')
if len(comp) >0: os.system('melting -S%s -C%s -G%s -P%s -Hdnadna -Omelttemp.txt'%(strin... | [
"def getMRna(self, sequence):\n assert(self.chromosomeInterval.chromosome == sequence.name)\n assert(self.chromosomeInterval.stop <= sequence.getLength())\n s = ''\n # chromosome ttttTTTTTTTTTTTtttt t: thin T: THICK\n # exon eeeeee eeee eee\n # mrna mmmm mmmm m\n for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
identifies SEED tile strings according to the seed ID and writes them into the stringIDs dictionary | def getIDs(self):
self.stringIDs[12]="tw-ICEN-12"
self.stringIDs[20]="tw-ICEN-20"
a=[10,14,15,16,17,18]
for i in a:
self.stringIDs[i]="tw-%s-%02d"%(self.seedID,i)
a=[11,13]
for i in a:
self.stringIDs[i]="tw-%s%d-%02d"%(2*self.seedID[0],tvsn, i)
... | [
"def entity_name_id_map_from_dump():\n doc_cnt = 0\n my_ent_name_id_map = dict()\n my_ent_id_name_map = dict()\n duplicate_names = 0 # different articles with identical title\n duplicate_ids = 0 # with the same id\n with open(config.base_folder+\"data/basic_data/tokenizedWiki.txt\") as fin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
splits all sequences into possible subsequences of length num (for num=5, as in 12345, 23456, 34567 ...). Identifiers AABBB, with AA sequence number, BBB position of first base in string. Negative identifiers denote reversed sequences. If comp is set, the function returns complementary subsequences instead. | def getSubseq(self,num, comp=False):
##add reverses!!!
self.getStrands()
for key in self.stringSequences.keys():
string=self.stringSequences[key].replace("5'-","")
string=string.replace("-3'","")
string=string.replace(" ","")
for i in range(len(st... | [
"def split_subsequences(iterable, length=2, overlap=0, \r\n join_substr=True):\r\n isstring = isinstance(iterable, str) and join_substr\r\n it = iter(iterable)\r\n results = list(itertools.islice(it, length))\r\n while len(results) == length:\r\n yield ''.join(results) if i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load fstype information from the parser instance. | def _get_fstype_from_parser(self, fstype=None):
if not fstype:
if self.index in self.disk.parser.fstypes:
fstype = self.disk.parser.fstypes[self.index]
elif '*' in self.disk.parser.fstypes:
fstype = self.disk.parser.fstypes['*']
elif '?' in sel... | [
"def family_symbol_and_types_from_family(self, familyLoaded): # this is only used by check_family_dict()\n doc = __revit__.ActiveUIDocument.Document\n try:\n symbolIds = list(familyLoaded.GetFamilySymbolIds())\n familySymbol = doc.GetElement(symbolIds[0])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtains a generic description of the volume, containing the file system type, index, label and NTFS version. If with_size is provided, the volume size is also included. | def get_description(self, with_size=True, with_index=True):
desc = ''
if with_size and self.size:
desc += '{0} '.format(self.get_formatted_size())
s = self.info.get('statfstype') or self.info.get('fsdescription') or '-'
if with_index:
desc += '{1}:{0}'.format(s... | [
"def info(self):\n ret = libvirtmod.virStorageVolGetInfo(self._o)\n if ret is None: raise libvirtError ('virStorageVolGetInfo() failed', vol=self)\n return ret",
"def volume_size(self, volume, new_size=None):\n return self.request( \"volume-size\", {\n 'volume': [ volume, 'v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtains the size of the volume in a humanreadable format (i.e. in TiBs, GiBs or MiBs). | def get_formatted_size(self):
if self.size is not None:
if self.size < 1024:
return "{0} B".format(self.size)
elif self.size < 1024 ** 2:
return "{0} KiB".format(round(self.size / 1024, 2))
elif self.size < 1024 ** 3:
return "{... | [
"def get_size(self):\n units = (\"B\", \"KB\", \"MB\", \"GB\", \"TB\")\n for i, unit in enumerate(units):\n high = 10**(i*3)\n if self.size < high*1000:\n return f\"{round(self.size/high, 3)} {unit}\"",
"def size_unit(self) -> str:\n return pulumi.get(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the FS type from the blkid command. | def _get_blkid_type(self):
try:
result = _util.check_output_(['blkid', '-p', '-O', str(self.offset), self.get_raw_path()])
if not result:
return None
# noinspection PyTypeChecker
blkid_result = dict(re.findall(r'([A-Z]+)="(.+?)"', result))
... | [
"def GetFilesystem(path):\n cmd = ['lsblk', path, '-f', '-o', 'FSTYPE', '-n']\n log.info('Running {0!s}'.format(cmd))\n fstype = subprocess.check_output(cmd).split()\n if not fstype:\n # Lets wait a bit for any previous blockdevice operation to settle\n time.sleep(2)\n fstype = subprocess.check_output(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks the volume for its magic bytes and returns the magic. | def _get_magic_type(self):
try:
with io.open(self.disk.get_fs_path(), "rb") as file:
file.seek(self.offset)
fheader = file.read(min(self.size, 4096) if self.size else 4096)
except IOError:
logger.exception("Failed reading first 4K bytes from volum... | [
"def magic_number(self) -> 'bytes':\n return self._magic",
"def check_magic_no(header):\n try:\n magic_no = ((header[0] << 8) + header[1]).to_bytes(2, 'big')\n if int.from_bytes(magic_no, 'big') != 0x497E:\n sys.exit(1)\n print('Magic number acceptable.\\n')\n\n except... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a label that is safe to add to a path in the mountpoint for this volume. | def get_safe_label(self):
if self.info.get('label') == '/':
return 'root'
suffix = re.sub(r"[/ \(\)]+", "_", self.info.get('label')) if self.info.get('label') else ""
if suffix and suffix[0] == '_':
suffix = suffix[1:]
if len(suffix) > 2 and suffix[-1] == '_':
... | [
"def udev_device_get_label(info):\n return info.get(\"ID_FS_LABEL\")",
"def format_label(self, label):\n# logging.debug(\"format_label(%s (type %s))\" % (label, type(label)))\n if isinstance(label, basestring):\n if config_pathtools.is_server_path(label):\n return config... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to call vshadowmount and mount NTFS volume shadow copies. | def detect_volume_shadow_copies(self):
volume = self.volumes._make_subvolume(flag='alloc', offset=0, fstype='vss-container')
volume.mount()
return volume.volumes | [
"def mount(self, volume_id, client_name, mountpath, do_vssprotection=True):\n return self._snap_operation(0, volume_id, client_name, mountpath, do_vssprotection)",
"def mount_ss(self):\n if match_fs(self.mp, ['nilfs', 'nilfs2']):\n self.mount_tmpfs()\n if not self.passive:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generator that mounts this volume and either yields itself or recursively generates its subvolumes. | def init(self, only_mount=None, skip_mount=None, swallow_exceptions=True):
if swallow_exceptions:
self.exception = None
try:
if not self._should_mount(only_mount, skip_mount):
yield self
return
if not self.init_volume():
... | [
"def _iter_volumes(self):\n if self.volumes:\n for volume_name, container_path in self.volumes.iteritems():\n if \"/\" in volume_name:\n # if a / is found in the name, assume it's a full path specified on the host\n host_path = volume_name\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bind mounts the volume to another mountpoint. Only works if the volume is already mounted. | def bindmount(self, mountpoint):
if not self.mountpoint:
raise NotMountedError(self)
try:
_util.check_call_(['mount', '--bind', self.mountpoint, mountpoint], stdout=subprocess.PIPE)
self.bindmounts.append(mountpoint)
return True
except Exception a... | [
"def volumeBind(influence=\"string\", name=\"string\"):\n pass",
"def attach_volume(self, context, connection_info, instance, mountpoint,\n disk_bus=None, device_type=None, encryption=None):\n instance_name = instance['name']\n if instance_name not in self.__mounts:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively gets a list of all subvolumes and the current volume. | def get_volumes(self):
if self.volumes:
volumes = []
for v in self.volumes:
volumes.extend(v.get_volumes())
volumes.append(self)
return volumes
else:
return [self] | [
"def all_volumes(self):\n _logger.debug('%s', where_am_i())\n volumes = []\n for compartment in self.all_compartments():\n comp_volumes = compartment.all_volumes()\n if comp_volumes is not None:\n volumes += comp_volumes\n return volumes",
"def get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes window constant bordered. | def set_constant_bordered(self):
self._borders_state.change_to_constant() | [
"def make_border(self):\n self.is_border = True",
"def showBorders(self,window):\n mx,my,Mx,My=self.getCorners(window)\n p=[(mx,my),(mx,My),(Mx,My),(Mx,my)]\n for i in range(len(p)):\n j=(i+1)%len(p)\n start=p[i]\n end=p[j]\n start=self.getTo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes image to `new_image`. Does not copy `new_image`. Use this instead of `=` or `blit`. | def reset_image(self, new_image: pygame.Surface):
# We use `=` instead of `blit` because `=` does not save alpha.
self.image = new_image
self._borders_state.fix_borders() | [
"def new_image(image):\n os.replace(image,PICTURES_IN + image)\n return",
"def updateImage(self):\n self.image = self.getImage(self.location, self.name, self.imageType)",
"def copy_image(self): \r\n\r\n for i in range(0, self.width):\r\n for j in range(0, self.height): \r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switchs window to `hidden` state. | def hide(self):
self._state = window_states.HiddenWindowState(self)
self.action_after_hide() | [
"def __toggleWindow(self, w):\n if w.isHidden():\n w.show()\n else:\n w.hide()",
"def became_invisible(window):\n log.debug(\"Window is invisible\")\n\n # FIXME - notify the manager that operation has completed.\n # For now, terminate.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if window is in hidden state. | def is_hidden(self):
return isinstance(self._state, window_states.HiddenWindowState) | [
"def is_hidden(self):\n if self.cellStatus == 'H':\n return True\n else:\n return False\n pass",
"def is_visible(self):\n return not self._panel.hidden()",
"def is_visible() -> bool:\n return win.winfo_ismapped()",
"def has_hidden(self, ):\n return s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Action window does when it switchs to `hidden` state. | def action_after_hide(self): | [
"def hide(self):\n self._state = window_states.HiddenWindowState(self)\n self.action_after_hide()",
"def became_invisible(window):\n log.debug(\"Window is invisible\")\n\n # FIXME - notify the manager that operation has completed.\n # For now, terminate.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switchs window to `passive` state. | def passive(self):
self._state = window_states.PassiveWindowState(self)
self.action_after_passive() | [
"def is_passive(self):\n return isinstance(self._state, window_states.PassiveWindowState)",
"def _update_is_passive(self):\n passive_setting = self._view.settings().get('wrap_as_you_type_passive')\n if passive_setting in (None, False, True):\n self.is_passive = bool(passive_setting... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if window is in passive state. | def is_passive(self):
return isinstance(self._state, window_states.PassiveWindowState) | [
"def passive(self):\n self._state = window_states.PassiveWindowState(self)\n self.action_after_passive()",
"def is_passive(self, node):\n return bool(self.network_graph.nodes[node]['node_passive'])",
"def is_passive(self, item):\n return item in self._passive.get((item.next, item.dot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Action window does when it switchs to `passive` state. | def action_after_passive(self): | [
"def passive(self):\n self._state = window_states.PassiveWindowState(self)\n self.action_after_passive()",
"def is_passive(self):\n return isinstance(self._state, window_states.PassiveWindowState)",
"def _update_is_passive(self):\n passive_setting = self._view.settings().get('wrap_as... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switchs window to `active` state. | def active(self):
self._state = window_states.ActiveWindowState(self)
self.action_after_active() | [
"def change_focus(window):\n xdotool('windowactivate', window)",
"def active(self, active):\n \n self._active = active",
"def set_active(self):\n bytes_to_write = self._to_byte_array((Commands.TOGGLE_STATE_COMMAND, Commands.ACTIVE))\n Controller._write_bytes(bytes_to_write)",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if window is in active state. | def is_active(self):
return isinstance(self._state, window_states.ActiveWindowState) | [
"def is_active(self):\n return self.element_info.active",
"def is_monitor_active(self):\n return self._monitor and self._monitor.is_alive()",
"def in_window(self):\n if self.actions == -1:\n return True\n else:\n return False",
"def is_active(self):\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Action window does when it switchs to `active` state. | def action_after_active(self): | [
"def active(self):\n self._state = window_states.ActiveWindowState(self)\n self.action_after_active()",
"def change_click(self):\r\n self.switch_window.emit()",
"def action(self, state):\n pass",
"def active(self, active):\n \n self._active = active",
"def activate(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if window can handle mouse click. | def can_handle_click(self, mouse_pos: Tuple[int, int]) -> bool:
return self._state.can_handle(mouse_pos) | [
"def _should_handle_mouse_press(self, buttons: int) -> bool:\n return (\n self.definition.on_press is not None\n # Also handle if on_release is defined so we can record which mouse button was used.\n or self.definition.on_release is not None\n or self.definition.de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test request cycle with one request without composite get condition. post, get, put | def testRequestSimpleCycle(self):
# test post method
requestName = self.insertRequest(self.rerecoCreateArgs)
## test get method
# get by name
response = self.getRequestWithNoStale('name=%s' % requestName)
self.assertEqual(response[1], 200, "get by name")
self.as... | [
"def test_returns_true_if_request_method_is_get(self):\n self.request_mock.method = 'GET'\n self.assertTrue(is_get(self.get_response_mock, self.request_mock))",
"def test_returns_false_if_request_method_is_not_post(self):\n self.request_mock.method = 'FOOBAR'\n self.assertFalse(is_put(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return LRP module from keras model | def read_kerasmodel(model):
lrpmodules = []
for layer in model.layers:
module, activation_module = get_lrpmodule(layer)
if module is not None:
lrpmodules.append(module)
if activation_module is not None:
lrpmodules.append(activation_module)
return LRPModel(lr... | [
"def _get_lr():\n raise NotImplementedError",
"def load_module(prefix, epoch, data_names, data_shapes):\n sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)\n\n # We don't need CTC loss for prediction, just a simple softmax will suffice.\n # We get the output of the layer just b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a utility function used to calculate the average of the last three datapoints in the series as a measure, instead of just the last datapoint. It reduces noise, but it also reduces sensitivity and increases the delay to detection. | def tail_avg(timeseries, end_timestamp, full_duration):
try:
t = (timeseries[-1][1] + timeseries[-2][1] + timeseries[-3][1]) / 3
return t
except IndexError:
return timeseries[-1][1] | [
"def get_average(self, last_n=None):\n if not self.has_samples():\n msg = \"get_average() cannot be called when no samples exist\"\n raise IllegalStateError(msg)\n\n samples = self.get_samples(last_n)\n return reduce(add, samples) / float(len(samples))",
"def measure_ave... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A timeseries is anomalous if the deviation of its latest datapoint with respect to the median is X times larger than the median of deviations. | def median_absolute_deviation(timeseries, end_timestamp, full_duration):
try:
series = pandas.Series([x[1] for x in timeseries])
median = series.median()
demedianed = np.abs(series - median)
median_deviation = demedianed.median()
except:
return None
# The test stati... | [
"def errmedian(x):\n\t \n\ty = []\n\tfor i in range(1000):\n\t\txr = resample(x)\n\t\ty.append(Median(xr))\n\ty = np.array(y)\n\treturn np.std(y)",
"def nanmedian(x):\n try:\n return np.nanmedian(x)\n except:\n return np.median(x[np.isfinite(x)])",
"def std_from_mad(self, x):\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calcuate the simple average over 60 datapoints (maybe one hour), FULL_DURATION seconds ago. A timeseries is anomalous if the average of the last three datapoints are outside of three standard deviations of this value. | def first_hour_average(timeseries, end_timestamp, full_duration):
try:
int_end_timestamp = int(timeseries[-1][0])
int_start_timestamp = int(timeseries[0][0])
int_full_duration = int_end_timestamp - int_start_timestamp
# Determine data resolution
# last_hour_threshold = int_end_t... | [
"def tail_avg(timeseries, end_timestamp, full_duration):\n try:\n t = (timeseries[-1][1] + timeseries[-2][1] + timeseries[-3][1]) / 3\n return t\n except IndexError:\n return timeseries[-1][1]",
"def _get_duration_average(test_list):\n return arrow.get(sum([test._duration for test in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A timeseries is anomalous if the absolute value of the average of the latest three datapoint minus the moving average is greater than three standard deviations of the moving average. This is better for finding anomalies with respect to the short term trends. | def stddev_from_moving_average(timeseries, end_timestamp, full_duration):
try:
series = pandas.Series([x[1] for x in timeseries])
if PANDAS_VERSION < '0.18.0':
expAverage = pandas.stats.moments.ewma(series, com=50)
stdDev = pandas.stats.moments.ewmstd(series, com=50)
... | [
"def anomaly_filter(self, df):\n # calculate forward means\n df['30_PERIOD_FWD_MEAN'] = df[self.endog].rolling(30, min_periods=0).mean().tolist()\n df['30_PERIOD_FWD_MEAN'].fillna(inplace=True, method='bfill')\n df['30_PERIOD_FWD_MEAN'][1:] = df['30_PERIOD_FWD_MEAN'][:-1]\n\n # ca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A timeseries is anomalous if the value of the next datapoint in the series is farther than three standard deviations out in cumulative terms after subtracting the mean from each data point. | def mean_subtraction_cumulation(timeseries, end_timestamp, full_duration):
try:
series = pandas.Series([x[1] if x[1] else 0 for x in timeseries])
series = series - series[0:len(series) - 1].mean()
stdDev = series[0:len(series) - 1].std()
# @modified 20160814 - pyflaked
# if ... | [
"def demean(data):\n return data - data.mean()",
"def robustmean(arr):\n\t\n\t# First pass discarding points >3 sigma above mean\n\tmean = arr.mean()\n\tsd = arr.std()\n\tthresh = mean + 3.0*sd\n\tidx = numpy.where(arr < thresh)\n\tnewarr = arr[idx]\n\t\n\tif len(newarr) == 0:\n\t\t# Warning, all points discar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A timeseries is anomalous if 2 sample KolmogorovSmirnov test indicates that data distribution for last 10 datapoints (might be 10 minutes) is different from the last 60 datapoints (might be an hour). It produces false positives on nonstationary series so Augmented DickeyFuller test applied to check for stationarity. | def ks_test(timeseries, end_timestamp, full_duration):
try:
int_end_timestamp = int(timeseries[-1][0])
# @modified 20160814 - pyflaked
# hour_ago = int_end_timestamp - 3600
# ten_minutes_ago = int_end_timestamp - 600
# Determine resolution of the data set
# reference = s... | [
"def test_time_series(self):\n\n assert False",
"def test_same_verifs_valid_time_no_nan(hindcast_hist_obs_1d):\n skill = hindcast_hist_obs_1d.verify(\n metric=\"rmse\",\n comparison=\"e2o\",\n dim=[], # important\n alignment=\"same_verifs\",\n )\n assert not skill.coor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A timeseries is anomalous if the average of the last ten datapoints is times greater than the last data point. This algorithm is most suited to timeseries with most datapoints being > 100 (e.g high rate). The arbitrary values become more noisy with lower value datapoints, but it still matches drops off cliffs. | def detect_drop_off_cliff(timeseries, end_timestamp, full_duration):
try:
if len(timeseries) < 21:
return False
int_end_timestamp = int(timeseries[-1][0])
# Determine resolution of the data set
int_second_last_end_timestamp = int(timeseries[-2][0])
resolution = ... | [
"def high_storm_peaks(self):\n\n if (self.postprocessor.sim_storm_peaks > \n self.postprocessor.obs_storm_peaks): \n return True\n\n return False",
"def checkLatestAnomaly(df):\n anomalies = df[df[\"anomaly\"] == 15]\n if anomalies.shape[0] > 0:\n lastAnomalyRow = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints a circle with radius r | def circle(r):
for y in range(r*2 + 1):
for x in range(r*2 + 1):
time.sleep(0.1)
sys.stdout.flush()
dist = math.sqrt((x - r)**2 + (y - r)**2)
diff = abs(dist - r)
print("*" if diff <= 0.5 else " ", end="")
print() | [
"def drawCircle(tortle, radius):\n tortle.penup()\n tortle.goto(0,-1)\n tortle.pendown()\n tortle.circle(radius, steps=360)",
"def circle(r):\n A = pi * r**2\n return A",
"def svgCircle(center, radius):\n\tsvgTag('circle cx=\"%d\" cy=\"%d\" r=\"%s\"' % (center+(radius,)) )",
"def dra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints a heart with size parametrized by r (must be an even number) | def heart(r):
if r % 2 != 0:
print("r must be even")
return
for y in range(r*2 + 1 - r//2):
for x in range(r*2 + 1):
# top two half-circles
if y <= r//2:
# first half circle
if x <= r:
dist = math.sqrt((x - r//2... | [
"def _print_heart(activity: Activity):\n lrp = LeftRightPrinter(left_width=60)\n _print_hr_data(activity, lrp)\n _print_hr_zones(activity, lrp)\n lrp.print()",
"def draw_heart(pos: np.ndarray) -> None:\n pygame.draw.lines(PSEUDO_SCREEN, colours['red'], False, (\n pos + (0, 1),\n pos +... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints a skewed square with side length a | def skewed(a):
for i in range(a):
# conscise: print(' '*i, end="")
for j in range(i):
print(' ')
for j in range(a):
print("*", end="")
print() | [
"def draw_square(self, side_length):\n self.draw_polygon(side_length, 4)",
"def draw_square(t, sz, col, ps, step):\t\n t.color(col)\n t.pensize(ps)\n for i in range(4):\n t.fd(sz)\n t.left(90)\n t.penup()\n t.goto(t.pos()+ (-step,-step))\n t.pendown()",
"def draw_square(t,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print frequency of each word in text. Type of text is string | def print_freq_words(text):
assert isinstance(text, str), "Please input parameter 'text' to string."
sent = nltk.word_tokenize(text)
fd = nltk.FreqDist(w.lower() for w in sent if re.match(r'[a-zA-Z0-9]',w))
for w in fd:
print('%12s, %3d' % (w, fd[w])) | [
"def word_frequency(text: str):\n # get individual words\n tokenized = text.split()\n\n # count the frequency\n word_counter = collections.Counter(tokenized)\n #frequencies = list(collections.Counter(tokenized).items())\n\n return word_counter",
"def word_frequency(text: str):\n # get individ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A ParentField should receive its parent form the form | def test_forminit(self, client):
## unfortunately, BaseForm depends on lots of stuff, including
## database access
class Form(BaseForm):
class Meta:
model = Type1
field = ParentField()
parent = mock.MagicMock()
form = Form(parent)
... | [
"def related_parent (field):\n return field.related.parent_model",
"def validate_parent(self, raises: type[Exception] = ValidationError):\n if not self._state.adding:\n if self.parent:\n # Prevent the model instance from being its own parent, which would\n # resu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
flip all the images in dir, and then save them to another dir | def do_all_flip(base_dir="F:/ad_samples/train_samples/ad_web_2/"):
# get all files
# base_dir = "F:/ad_samples/train_samples/ad_text/"
# base_dir = "F:/ad_samples/download_sample/14/"
# base_dir = "F:/ad_samples/train_samples/ad_web/"
# files = glob.glob(base_dir + "*.jpg")
files = glob.glob(ba... | [
"def flipImages(rootDir, imgFormat=None):\n if imgFormat is None:\n flipImages(rootDir, 'jpg')\n flipImages(rootDir, 'png')\n else:\n string = rootDir + \"/*/*.\" + imgFormat\n filenames = glob.glob(string)\n if len(filenames) == 0:\n string = rootDir + \"/*.\" + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes dropEvent when taegetlocation is within first row | def dropEvent(self, evt):
#TODO: self.indexAt(index).row()==0 insted
if self.header().sectionSize(0)>evt.pos().x():#Only execute drop when on first column
QTreeView.dropEvent(self, evt) | [
"def at_drop(self, dropper):\r\n pass",
"def dropEvent(self, event):\n # copied from DocTree but not implemented yet\n # dragitem = self.selectedItems()[0]\n # dragparent = dragitem.parent()\n # dropitem = self.itemAt(event.pos())\n # if not dropitem:\n # # ## ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all n grams from l after normalizing. | def ngram(n, l):
filtered = normalize(l)
for start in range(0, len(filtered) - n + 1):
yield ''.join(filtered[start:start + n]) | [
"def get_all_ngrams(self):\n flattened_list = [y for x in self.model.values() for y in x]\n print(f'This is every possible n gram {flattened_list}')\n return flattened_list\n pass",
"def list2ngrams(l, size):\n\tif size >= len(l):\n\t\treturn [tuple(l)]\n\treturn [tuple(l[i:i+size]) for i ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the average transition prob from l through log_prob_mat. | def avg_transition_prob(l, log_prob_mat):
log_prob = 0.0
transition_ct = 0
for a, b in ngram(2, l):
log_prob += log_prob_mat[pos[a]][pos[b]]
transition_ct += 1
# The exponentiation translates from log probs to probs.
return math.exp(log_prob / (transition_ct or 1)) | [
"def reward_log_prob(target_distribution, xs, accepteds):\n return np.mean([target_distribution.log_probability(x) for x in xs])",
"def gen_aval_prob_log(L):\n s_list = gen_aval_list(L)\n s_range, s_prob = log_bin(s_list,0,1,1.2,'integer')\n return s_prob, s_range",
"def logprob_a(self, X, Xerr):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For each student response, return the feedback, if any | def check_all_errors(student_resp_list, expected_resp_list):
all_errors = [] # list that will hold all the feedback
for student_resp, expected_resp in zip(student_resp_list, expected_resp_list):
if student_resp == "" or student_resp is None:
return "Nothing entered"
if "\n" in stude... | [
"def response_strings(self):\n for response in self.responses:\n yield string.join([\n self.student.student_id,\n response.item.item_id,\n str(response.time_taken),\n str(response.correct),\n ],\n ',')",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a command that requests actor to move entity to a new location. | def move(cls, actor, entity, location):
return Command(actor, "move", (entity, location)) | [
"def move(self, new_location):\n pass",
"def _move_agent(self, agent_id: str, new_pos: Position):\n agent = self.agents[agent_id]\n if self.is_free(new_pos):\n agent.pos = new_pos",
"def move(self, direction, distance):\n\n return self.send('%s %s' % (direction, distance))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Divide the ranks into chunks, attempting to have `N` ranks in each chunk. This removes the master (0) rank, such that `N_ranks 1` ranks are available to be grouped | def split_ranks(N_ranks, N):
available = list(range(1, N_ranks)) # available ranks to do work
total = len(available)
extra_ranks = total % N
for i in range(total//N):
yield i, available[i*N:(i+1)*N]
if extra_ranks and extra_ranks >= N//2:
remove = extra_ranks % 2 # make it an even ... | [
"def testNGroupSplit(self):\n # Test 2 groups like HalfSplitter first\n hs = NGroupSplitter(2)\n hs_reversed = NGroupSplitter(2, reverse=True)\n\n for isreversed, splitter in enumerate((hs, hs_reversed)):\n splits = list(splitter(self.data))\n self.failUnless(len(sp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the `RSDFitDriver` object on all ranks | def initialize_driver(self):
# update with first value
itask = 0
# master will parse the args
this_config = None; rsdfit_args = None
if self.comm.rank == 0:
# get the kwargs
kwargs = self.task_kwargs(itask)
# this writes out the param file
... | [
"def __init__(self, ranker):\n super().__init__(Tautology() if ranker is None else ranker)",
"def __init__(self, ranker=None):\n super().__init__(Tautology() if ranker is None else ranker)",
"def rank_dependent_metrics(self):\n rank = self.last_extr_aut.nbS\n self.ranks.append(rank)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify signing out a user with an invalid token throws an error. | def test_get_signout_invalid_user(self):
with self.client:
response = self.client.get(
'/auth/signout',
headers={'Authorization': 'Bearer invalid'}
)
data = json.loads(response.data.decode())
self.assertEqual(data['status'], 'error... | [
"def test_user_with_invalid_token(self):\n result = self.app.post(url_prefix+'/auth/logout',\n headers={'Content-Type': 'application/json',\n 'Authorization': \"abcdefghijklm\"})\n self.assertEqual(result.status_code, 401)\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify signing out a user with an expired token throws an error. | def test_get_signout_user_with_expired_token(self):
user = add_user(USERNAME, EMAIL, PASSWORD)
with self.client:
token = get_jwt(self.client, user.email)
time.sleep(4)
response = self.client.get(
'/auth/signout',
headers={'Authorizatio... | [
"def test_get_signout_invalid_user(self):\n\n with self.client:\n response = self.client.get(\n '/auth/signout',\n headers={'Authorization': 'Bearer invalid'}\n )\n data = json.loads(response.data.decode())\n self.assertEqual(data['sta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify signing out an inactive user throws an error. | def test_get_signout_inactive_user(self):
user = add_user(USERNAME, EMAIL, PASSWORD)
user.active = False
db.session.commit()
with self.client:
token = get_jwt(self.client, user.email)
response = self.client.get(
'/auth/signout',
he... | [
"def logout():\n if g._current_user is None:\n raise UserNotLoggedInException()\n\n if not invalidate(g._current_session_token):\n raise UserNotLoggedInException()",
"def test_get_signout_invalid_user(self):\n\n with self.client:\n response = self.client.get(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify user cannot get profile with invalid token. | def test_get_profile_invalid_token(self):
with self.client:
response = self.client.get(
'/auth/profile',
headers={'Authorization': 'Bearer invalid'}
)
data = json.loads(response.data.decode())
self.assertEqual(data['status'], 'erro... | [
"def test_user_profile_invalid_token():\n clear()\n user = auth_register(\"test@test.com\", \"password\", \"firstName\", \"lastName\")\n # Logging out invalidates your token\n auth_logout(user['token'])\n with pytest.raises(AccessError):\n user_profile(user['token'], user['u_id'])",
"def tes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify getting the profile of an inactive user throws an error. | def test_get_profile_inactive_user(self):
user = add_user(USERNAME, EMAIL, PASSWORD)
user.active = False
db.session.commit()
with self.client:
token = get_jwt(self.client, user.email)
response = self.client.get(
'/auth/profile',
he... | [
"def verify_profile_availability(self, profile):\n pass",
"def testUserWithProfileAccessDenied(self):\n user = profile_utils.seedNDBUser()\n profile_utils.loginNDB(user)\n profile_utils.seedNDBProfile(self.program.key(), user=user)\n\n access_checker = access.HasNoProfileAccessChecker()\n wi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This command reads the digital port tristate register. The tristate register determines if the latch register value is driven onto the port pin. A '1' in the tristate register makes the corresponding pin an input, a '0' makes it an output_data. | def DTristateR(self):
request_type = (DEVICE_TO_HOST | VENDOR_TYPE | DEVICE_RECIPIENT)
wValue = 0
wIndex = 0
value, = self.udev.controlRead(request_type, self.DTRISTATE, wValue, wIndex, 1, self.HS_DELAY)
return value | [
"def DTristateW(self, value):\n request_type = (HOST_TO_DEVICE | VENDOR_TYPE | DEVICE_RECIPIENT)\n request = self.DTRISTATE\n wValue = value & 0xff\n wIndex = 0\n self.udev.controlWrite(request_type, request, wValue, wIndex, [0x0], self.HS_DELAY)",
"def digitalRead(self,pinNum):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This command writes the digital port tristate register. The tristate register determines if the latch register value is driven onto the port pin. A '1' in the tristate register makes the corresponding pin an input, a '0' makes it an output_data. | def DTristateW(self, value):
request_type = (HOST_TO_DEVICE | VENDOR_TYPE | DEVICE_RECIPIENT)
request = self.DTRISTATE
wValue = value & 0xff
wIndex = 0
self.udev.controlWrite(request_type, request, wValue, wIndex, [0x0], self.HS_DELAY) | [
"def DTristateR(self):\n request_type = (DEVICE_TO_HOST | VENDOR_TYPE | DEVICE_RECIPIENT)\n wValue = 0\n wIndex = 0\n value, = self.udev.controlRead(request_type, self.DTRISTATE, wValue, wIndex, 1, self.HS_DELAY)\n return value",
"def set_tmds_output(self, value):\n asser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This command reads the value of an analog input channel. This command will result in a bus stall if an AInScan is currently running. | def AIn(self, channel):
request_type = (DEVICE_TO_HOST | VENDOR_TYPE | DEVICE_RECIPIENT)
wValue = channel
wIndex = 0x0
value, = unpack('H', self.udev.controlRead(request_type, self.AIN, wValue, wIndex, 2, timeout=100))
data = round(float(value) * self.table_AIn[channel].slope + s... | [
"def analog_read_once (ser_port, channel):\n\n\tprint 'Analog ', channel, '\\r'\n\tser_port.write (str (channel))\n\n\tch_in = '\\0'\n\twhile ch_in != '\\n':\n\t\tch_in = ser_port.read ()\n\t\tprint ch_in",
"def ReadAnalogVal(self, pin):\r\n \r\n if (type(pin) != type(1)):\r\n raise TypeError, \"Read a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This command allow for reading and writing the nonvolatile user memory. wLength specifies the number of bytes to read or write. The user memory is 256 bytes (address 00xFF) | def UserMemoryR(self, address, count):
request_type = (DEVICE_TO_HOST | VENDOR_TYPE | DEVICE_RECIPIENT)
wValue = address & 0xffff # force to be 16 bits
wIndex = 0
if count > 256:
raise ValueError('UserMemoryR: max bytes that can be read is 256.')
if address > 0xff:... | [
"def writemem(self, address, data):\n\n if 'qemu-' in os.path.realpath('/proc/%i/exe' % self.pid):\n self.error(\"Cannot use leaker on binaries under QEMU.\")\n\n with open('/proc/%i/mem' % self.pid, 'wb') as mem:\n mem.seek(address)\n return mem.write(data)",
"def r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This command allows for reading and writing the nonvolite MBD memory. wLength specifies the number of bytes to read or write. The MBD memory is 1024 bytes (address 0 0x3FF). | def MBDMemoryR(self, address, count):
request_type = (DEVICE_TO_HOST | VENDOR_TYPE | DEVICE_RECIPIENT)
wValue = address & 0xffff # force to be 16 bits
wIndex = 0
if count > 1023:
raise ValueError('MBDMemoryR: max bytes that can be read is 512.')
if address > 0x3ff:... | [
"def readMemory(mbed, address, count):\n write(mbed, 0xfe)\t\t# Send the read memory opcode\n write32(mbed, address)\t# Send the 32 bits start address (4 bytes)\n write16(mbed, count)\t# Send how many bytes we want to read (2 bytes)\n return read(mbed, count)\t# Read the number of bytes from the device"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This commands reads the device USB serial number. The serial number consists of 8 bytes, typically ASCII numeric or hexadecimal digits (i.e. "00000001"). The new serial number will be wtored but not used until the device is reset. | def GetSerialNumber(self):
request_type = (DEVICE_TO_HOST | VENDOR_TYPE | DEVICE_RECIPIENT)
wValue = 0x0
wIndex = 0x0
value = self.udev.controlRead(request_type, self.SERIAL, wValue, wIndex, 8, self.HS_DELAY)
return value.decode() | [
"def get_serial_number(self):\n return usb.util.get_string(self.dev, 256, 3)",
"def get_virtio_disk_serial(device_name):\n dev_path = ('/sys/block/%s/serial' % device_name)\n out, err, rc = run_command([CAT, dev_path], throw=False)\n if (rc != 0):\n return ''\n # our out list has one ele... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert 12 bit raw value to volts. All values single ended +/ 10V. | def volts(self, value):
volt = ((value - 2048) * 10.) / 2048.
return volt | [
"def Convert2Volt(values):\n for val in values:\n val *= 10e-4 / 167",
"def to_voltage(val):\n return (val / 1024.0) * 3.3",
"def _hexword2volt(self, hex_str):\n byte1 = format(int(hex_str[0:2], 16), \"08b\")\n byte2 = format(int(hex_str[2:4], 16), \"08b\")\n byte3 = format(int... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the play_as method call | def test_play_as(self):
queue = Queue()
thread = Thread(
target=self.__client_send_thread, args=[self.client, json.dumps("void"), queue])
thread.daemon = True
thread.start()
comm.play_as(self.remote_player, "red")
thread.join()
data_load = queue.get()
... | [
"def test_cps_play(self):\n self.skill.play_service_string = 'play on godzilla'\n self.skill.CPS_play(['looking_for_freedom.mp3'],\n utterance='play on mothra')\n self.audioservice.play.assert_called_once_with(\n ['looking_for_freedom.mp3'], utterance='play... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
starts the glut main loop | def main_loop():
glutMainLoop() | [
"def main():\n make_glut()",
"def mainloop(self):\n while self.running:\n self.updateview();\n self.handlekey(self.scr.getch());",
"def mainloop() -> None:\n handle_key_down()\n\n if SS.on_start_screen:\n return\n\n if MAIN not in characters:\n return\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return newly create session if it is external user needed else session from the pool. | def get_session(self, obj_dict):
return session_pool.create_session(
users.current_user(), is_external=True) if (
self.is_external_user_needed(obj_dict)) else (
session_pool.get_session(users.current_user())) | [
"def get_or_create_session (self):\n\n session_name = self.session_class.name_prefix + '_session'\n session = cherrypy.session.get (session_name, self.session_class ())\n cherrypy.session[session_name] = session\n return session",
"def get_session(self, session_id='', create_if_null=Fa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if endpoint is external. | def is_endpoint_external(self):
return self.endpoint in objects.EXTERNAL_END_POINTS | [
"def IsExternal(self):\n return self.location is not None",
"def is_external(url):\r\n return url.startswith(('//', 'http://', 'https://'))",
"def uses_webhook(self):\n url = self.config.server.base_url\n return 'https' in url and not ('localhost' in url or '127.0.0.1' in url)",
"def validate_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if source or destination objects type is external. | def is_relationship_types_external(self, obj_dict):
return (self.endpoint == objects.get_singular(objects.RELATIONSHIPS) and
(any(x for x in objects.SINGULAR_DISABLED_OBJS
if x.title() in (obj_dict["source"]["type"],
obj_dict["destination"]["type"])))) | [
"def IsExternal(self):\n return self.location is not None",
"def IsExternal(self):\n return isinstance(self.definition, XMLExternalID)",
"def check_source(self):\r\n source_bool = False\r\n for a in G.nodes():\r\n if a in self.source:\r\n source_bool = True\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if custom attribute is external. | def is_ca_external(self, obj_dict):
return (self.endpoint == objects.get_singular(
objects.CUSTOM_ATTRIBUTES) and
obj_dict["definition_type"] in objects.ALL_SINGULAR_DISABLED_OBJS) | [
"def IsExternal(self):\n return self.location is not None",
"def IsExternal(self):\n return isinstance(self.definition, XMLExternalID)",
"def is_not_known_attribute(cls, attr):\r\n return attr not in cls.known_attributes",
"def _check_rule_has_attribute(self, data_sources, conditions):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log error and exit when set use_gpu=true in paddlepaddle cpu version. | def check_gpu(use_gpu):
err = "Config use_gpu cannot be set as true while you are " \
"using paddlepaddle cpu version ! \nPlease try: \n" \
"\t1. Install paddlepaddle-gpu to run model on GPU \n" \
"\t2. Set use_gpu as false in config file to run " \
"model on CPU"
try:
... | [
"def check_gpu(use_gpu):\n err = \"Config use_gpu cannot be set as true while you are \" \\\n \"using paddlepaddle cpu version ! \\nPlease try: \\n\" \\\n \"\\t1. Install paddlepaddle-gpu to run model on GPU \\n\" \\\n \"\\t2. Set use_gpu as false in config file to run \" \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log error and exit when the installed version of paddlepaddle is not satisfied. | def check_version():
err = "PaddlePaddle version 1.6 or higher is required, " \
"or a suitable develop version is satisfied as well. \n" \
"Please make sure the version is good with your code." \
try:
fluid.require_version('1.7.0')
except Exception as e:
logger.error(err... | [
"def validate_python() -> None:\n if sys.version_info[:3] < REQUIRED_PYTHON_VER:\n print(\n \"ninewatt Device requires at least Python {}.{}.{}\".format(\n *REQUIRED_PYTHON_VER\n )\n )\n sys.exit(1)",
"def on_build_failure():\n\n message_titl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The datetime that a reminder should be sent at | def send_reminder_at(self):
previous_meeting = self.study_group.meeting_set.active().filter(
models.Q(meeting_date__lt=self.meeting_date)
| models.Q(meeting_date=self.meeting_date, meeting_time__lt=self.meeting_time)
).order_by('-meeting_date', '-meeting_time').first()
tw... | [
"def datetime():\n return _get_rtc().datetime()",
"def get_followup_time(self):\n\n contact_time = arrow.get(self.time)\n reminder_time = contact_time.replace(minutes=+self.delta)\n return reminder_time",
"def get_alarm(self):\n return self.alarm_time",
"def received_time(self) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns weight of the connection. | def get_weight(self):
return self.weight | [
"def _get_connection_weight(self, weight):\n\n return weight if weight else uniform(-1, 1)",
"def get_sum_connections_weight(self):\n total = 0.0\n for conn in self.connections:\n total += conn.weight\n return total",
"def getWeight(self):\n return self.vertexWeight... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mutates the weight (assigns from a uniform distribution). | def mutate_weight(self):
self.weight += np.random.uniform(low = -2.0, high = 2.0)
return | [
"def shift_weight(self):\n # Shift a randomly selected weight\n gene: Gene = choice(self.__genes)\n rand = uniform(0, 1)\n if rand <= 0.2:\n # Perturb\n gene.weight += 0.1 * choice([-1, 1])\n elif 0.2 < rand <= 0.5:\n # New random value\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
loglike, grad = pylag.mlfit.MLFit.log_likelihood(params, eval_gradient=True) Evaluate log(marginal likelihood), as well as its gradient, for the covariance matrix defined by some set of input parameters, applied to the data points we have. Based on the Algorithm 2.1 of Rasmussen & Williams "Gaussian Processes for Machi... | def log_likelihood(self, params, eval_gradient=True):
c = self.cov_matrix(params)
# add white noise along the leading diagonal
# this should be the Poisson noise term when calculating a PSD
if self.noise is not None:
c += np.diag(self.noise)
try:
L = cho... | [
"def log_likelihood(self, params, eval_gradient=True):\n if eval_gradient:\n segment_loglike = [c.log_likelihood(params, eval_gradient) for c in self.mlcross_spec]\n # separate and sum the likelihoods and the gradients\n like = np.array([l[0] for l in segment_loglike])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pylag.mlfit.MLFit.set_param(param, value, min, max) Set the value, lower and upper bounds for a parameter. If any of value, min or max are None, these values will not be altered. | def set_param(self, param, value=None, min=None, max=None, vary=None):
if value is not None:
self.params[param].value = value
if min is not None:
self.params[param].min = min
if max is not None:
self.params[param].max = max
if vary is not None:
... | [
"def setparam(self, param, value):\n\t\treturn self.__command(\"param.set %s %s\" % (param, value))",
"def set_parameter_guess_and_limits(parameter_dictionary, param_name, guess_min_max):\n if 'parameter_info' not in parameter_dictionary:\n print(\"Provided parameter dictionary did not have 'parameter_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
result = pylag.mlfit.MLFit._dofit(init_params, method='LBFGSB', kwargs) Function to actually perform the minimisation of log(likelihood). This method is not normally called on its own, rather it is called by the fit() or steppar() method. | def _dofit(self, init_params, method='L-BFGS-B', **kwargs):
initial_par_arr = np.array([init_params[p].value for p in init_params if init_params[p].vary])
bounds = [(init_params[p].min, init_params[p].max) for p in init_params if init_params[p].vary] if method == 'L-BFGS-B' else None
def object... | [
"def fit(self):\n ln_l_all_array = [] #array of all log likelihoods\n ln_l_max = float(\"-inf\") #keep track of the maximum likelihood\n cp_parameter_array = None #parameters with the maximum likelihood\n #for multiple initial values\n for i in range(self.n_initial):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pylag.mlfit.MLFit._dofit(init_params, method='LBFGSB', kwargs) Fit the model covariance matrix to the data by minimising log(likelihood). Once the fit is complete, the parameters stored in the member variable params will be updated, the uncertainties will be estimated from the Hessian matrix, and the process_fit_result... | def fit(self, init_params=None, update_params=True, **kwargs):
if init_params is None:
init_params = self.params
self.fit_result = self._dofit(init_params, **kwargs)
print(self.fit_result)
if True or self.fit_result.success and update_params:
for par, value in z... | [
"def _dofit(self, init_params, method='L-BFGS-B', **kwargs):\n initial_par_arr = np.array([init_params[p].value for p in init_params if init_params[p].vary])\n bounds = [(init_params[p].min, init_params[p].max) for p in init_params if init_params[p].vary] if method == 'L-BFGS-B' else None\n\n d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pylag.mlfit.MLFit.run_mcmc(init_params=None, burn=300, steps=1000, thin=1, walkers=50, kwargs) Run MCMC to obtain the posterior distributions of the model parameters. MCMC calculation is run using the GoodmanWeare algorithm, via emcee, called via lmfit's Minimzer class. | def run_mcmc(self, init_params=None, burn=300, steps=1000, thin=1, walkers=50, **kwargs):
if init_params is None:
init_params = self.params
# we initialise a Minimizer object, but only if there isn't one already, so we can
if self.mcmc_minimizer is None:
self.mcmc_minimi... | [
"def run_mcmc(self):\n if self.sampler is not None:\n instance = None\n prev_samples = self.sampler.iterations\n else:\n instance = self._setup_instance()\n if self.fit_type == \"both\":\n optres = self.run_downhill(instance)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
wrapper around log_likelihood method to evaluate for an array of just the variable parameters, which can be used directly with scipy.optimise methods. | def objective(par_arr):
fit_params = copy.copy(params)
for par, value in zip([p for p in params if params[p].vary], par_arr):
fit_params[par].value = value
return self.log_likelihood(fit_params, eval_gradient=False) | [
"def likelihood(self, x: np.ndarray) -> np.ndarray:",
"def evaluate_likelihood(self, X):\n Y = np.apply_along_axis(self.likelihood_l, 1, X)\n return(Y)",
"def compute_log_likelihood(X, params):\n m, n, _ = X.shape\n likelihood = 0.\n for i in range(m):\n p_y_0 = p_y(0, params)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
c = pylag.mlfit.MLPSD.cov_matrix(params) Calculate the model covariance matrix for the specified parameter values. | def cov_matrix(self, params):
# if no model is specified, the PSD model is just the PSD value in each frequency bin
# note the factor of 2 to integrate over the negative frequencies too!
if self.model is None:
psd = np.exp(np.array([params[p].value for p in params])) * self.psdnorm
... | [
"def cross_cov_matrix(self, params):\n # if no model is specified, the PSD model is just the PSD value in each frequency bin\n if self.cpsd_model is None:\n cpsd = np.exp(np.array([params['%sln_cpsd%01d' % (self.prefix, i)].value for i in range(len(self.fbins))])) * self.psdnorm\n el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dc = pylag.mlfit.MLPSD.cov_matrix_deriv(params) Calculate the first derivative of the covariance matrix wrt the parameters | def cov_matrix_deriv(self, params):
if self.model is None:
psd = np.exp(np.array([params[p].value for p in params])) * self.psdnorm
# in this simple case, the covariance matrix is just a linear sum of each frequency term
# so the derivative is simple - we multiply by p when ... | [
"def cross_cov_matrix_deriv(self, params):\n # if no model is specified, the PSD model is just the PSD value in each frequency bin\n if self.cpsd_model is None:\n cpsd = np.exp(np.array(\n [params['%sln_cpsd%01d' % (self.prefix, i)].value for i in range(len(self.fbins))])) * ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
psd = pylag.mlfit.MLPSD.get_psd(params) Calculate the power spectrum in each frequency bin for a given set of parameters. | def get_psd(self, params=None):
if params is None:
params = self.params
if self.model is None:
return np.array([self.params[p].value for p in self.params])
else:
return np.log(self.model(self.params, self.fbins.bin_cent)) | [
"def welch_psd(data, fs, plot=True, window='hanning', overlap=0.5, len_seg=None, axis=-1):\n# data = data.reshape(data.shape[0],)\n if len_seg is None:\n overlap = overlap * 256\n else:\n overlap = overlap * len_seg\n freqs, psd = signal.welch(data, fs=fs, noverlap=overlap, nperseg=len_se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pylag.mlfit.MLPSD.process_fit_results(fit_result, params) Process a scipy.optimise fit result to calculate the bestfitting power spectrum and error from the model. | def process_fit_results(self, fit_result, params):
self.psd = self.get_psd()
if self.model is None:
self.psd_error = self.param_error
else:
# calculate the error on each PSD point from the error on each parameter
psd_deriv = self.model.eval_gradient(params, se... | [
"def process_fit_results(self, fit_result, params):\n hess = fit_result.hess_inv(fit_result.x) if callable(fit_result.hess_inv) else np.diag(fit_result.hess_inv)\n\n self.cpsd = self.get_cpsd()\n if self.cpsd_model is None:\n self.cpsd_error = hess[:len(self.fbins)] ** 0.5\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pylag.mlfit.MLCrossSpectrum.fit_psd() Perform preliminary fits of the power spectra to the individual light curves. This function will prepopulate the stored autocovariance components of the matrix (when the psd is frozen) and will set an initial estimate of the cross spectral powers to use as the starting point for fi... | def fit_psd(self):
print("Fitting PSD of light curve 1...")
self.mlpsd1.fit()
self.ac1 = self.mlpsd1.cov_matrix(self.mlpsd1.params)
print("Fitting PSD of light curve 2...")
self.mlpsd2.fit()
self.ac2 = self.mlpsd1.cov_matrix(self.mlpsd2.params)
if self.cpsd_mode... | [
"def fit_powerlaw(xdata, ydata, fitparams=None, domain=None, showfit=False, showstartfit=False,\n verbose=True, **kwarg):\n if fitparams is None:\n print(\"Please specify fit parameters in function input\")\n return\n\n if domain is not None:\n fitdatax, fitdatay = selectd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cc = pylag.mlfit.MLCrossSpectrum.cross_cov_matrix(params) Calculate the cross component of the covariance matrix for the model cross spectrum (i.e. the upper right and lower left quadrants of the matrix for the terms that use rates from both light curves). | def cross_cov_matrix(self, params):
# if no model is specified, the PSD model is just the PSD value in each frequency bin
if self.cpsd_model is None:
cpsd = np.exp(np.array([params['%sln_cpsd%01d' % (self.prefix, i)].value for i in range(len(self.fbins))])) * self.psdnorm
else:
... | [
"def cov_matrix(self, params):\n if self.freeze_psd:\n if self.ac1 is None or self.ac2 is None:\n raise AssertionError(\"Autocovariance matrices are not available. Did you fit the PSDs?\")\n ac1 = self.ac1\n ac2 = self.ac2\n else:\n ac1 = self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
c = pylag.mlfit.MLCrossSpectrum.cov_matrix(params) Calculate the cross spectral model covariance matrix for the specified parameter values. The cross spectral covariance matrix is the stack of the autocovariance and crosscovariance matrices, and is applicable to the stacked data vector. If the freeze_psd member variabl... | def cov_matrix(self, params):
if self.freeze_psd:
if self.ac1 is None or self.ac2 is None:
raise AssertionError("Autocovariance matrices are not available. Did you fit the PSDs?")
ac1 = self.ac1
ac2 = self.ac2
else:
ac1 = self.mlpsd1.cov_ma... | [
"def cross_cov_matrix(self, params):\n # if no model is specified, the PSD model is just the PSD value in each frequency bin\n if self.cpsd_model is None:\n cpsd = np.exp(np.array([params['%sln_cpsd%01d' % (self.prefix, i)].value for i in range(len(self.fbins))])) * self.psdnorm\n el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dc = pylag.mlfit.MLPSD.cross_cov_matrix_deriv(params) Calculate the first derivative of the cross components of the covariance matrix wrt the parameters | def cross_cov_matrix_deriv(self, params):
# if no model is specified, the PSD model is just the PSD value in each frequency bin
if self.cpsd_model is None:
cpsd = np.exp(np.array(
[params['%sln_cpsd%01d' % (self.prefix, i)].value for i in range(len(self.fbins))])) * self.psdn... | [
"def cov_matrix_deriv(self, params):\n cc = self.cross_cov_matrix_deriv(params)\n\n if self.freeze_psd:\n Z = np.zeros_like(self.ac1)\n return np.stack(\n [np.vstack([np.hstack([Z, cc[..., p].T]), np.hstack([cc[..., p], Z])]) for p in\n range(len([p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dc = pylag.mlfit.MLPSD.cov_matrix_deriv(params) Calculate the first derivative of the covariance matrix wrt the parameters by stacking the derivatives of the four quadrants of the covariance matrix (the autocovariance and crosscovariance matrices) | def cov_matrix_deriv(self, params):
cc = self.cross_cov_matrix_deriv(params)
if self.freeze_psd:
Z = np.zeros_like(self.ac1)
return np.stack(
[np.vstack([np.hstack([Z, cc[..., p].T]), np.hstack([cc[..., p], Z])]) for p in
range(len([p for p in pa... | [
"def cross_cov_matrix_deriv(self, params):\n # if no model is specified, the PSD model is just the PSD value in each frequency bin\n if self.cpsd_model is None:\n cpsd = np.exp(np.array(\n [params['%sln_cpsd%01d' % (self.prefix, i)].value for i in range(len(self.fbins))])) * ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cpsd = pylag.mlfit.MLCrossSpectrum.get_cpsd(params) Calculate the cross power spectrum in each frequency bin from the model for a given set of parameters. | def get_cpsd(self, params=None):
if params is None:
params = self.params
if self.cpsd_model is None:
return np.array([self.params['%sln_cpsd%01d' % (self.prefix, i)].value for i in range(len(self.fbins))])
else:
return np.log(self.cpsd_model(self.params, self... | [
"def cross_cov_matrix(self, params):\n # if no model is specified, the PSD model is just the PSD value in each frequency bin\n if self.cpsd_model is None:\n cpsd = np.exp(np.array([params['%sln_cpsd%01d' % (self.prefix, i)].value for i in range(len(self.fbins))])) * self.psdnorm\n el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |