query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Copy json files under external | def copy_json():
sourcePath = 'contents/external/'
targetPath = 'build/external/'
for base,subdirs,files in os.walk(sourcePath):
for file in files:
orig = os.path.join(base, file)
if os.path.isfile(orig) and file[-5:] == '.json':
targetBase = os.path.join(targ... | [
"def copy_json() -> None:\n example_paths = [\n EXAMPLE_FILEPATH_PREPROCESS, EXAMPLE_FILEPATH_ANALYSE,\n EXAMPLE_FILEPATH_BUILD, EXAMPLE_FILEPATH_VARIANTS,\n EXAMPLE_FILEPATH_ASSESS, EXAMPLE_FILEPATH_OPTIMISATION_SIMULATION,\n EXAMPLE_FILEPATH_OPTIMISATION_COMPUTATION\n ]\n for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies optimizations to reduce file sizes | def optimize():
optimizable_extensions = get_optimizable_extensions()
file_set = get_optimizable_files(optimizable_extensions)
files_no = len(file_set)
compressed_total = 0
original_total = 0
for index, (file_basename, file_extension) in enumerate(file_set):
puts(green("%.1f%% done (%d/%... | [
"def optimize(self):\n pass",
"def optimize():\n cleanup()\n # initialize\n local(\"ln -s ../lib/almond.js app/almond.js\")\n local(\"mkfifo _css\")\n # build html\n local(\"sed '%s' < index.html > upload/index.html\" % SED_PROGRAM)\n # build css\n local(\"bin/cssembed.sh media/main... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rolls back currently deployed version to its predecessor | def rollback():
with cd(env.basepath):
run('mv current/rollback rollback')
run('mv current undeployed')
run('mv rollback current')
version = run('readlink current')
previous = run('readlink undeployed')
puts(green('>>> Rolled back from %(previous)s to %(version)s' % {... | [
"def rollback(delete = 'delete'):\n\n print \"Rolling Back\"\n\n with cd(\"%s/releases/\" % env.path):\n folders = run(\"ls -A | tail -2\")\n folders = folders.split('\\r\\n')\n\n if folders.count < 2:\n print \"There is no available release to rollback to\"\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Garbage Collect older deploys by keeping only the last n (defaults to 10) This will delete any directory which is older than the last n releases, preventing rollbacks from before that. | def gc_deploys(n = 10):
for deploypath in [env.basepath, env.nodejs]:
with cd("%s/releases" % deploypath):
files = run("ls -1t").splitlines()
older_files = files[n:]
if len(older_files) > 0:
puts(yellow("Removing older deploys: %s" % ", ".join(older_files)... | [
"def cleanup(keep_num=5):\n\n keep_num = int(keep_num)\n assert keep_num > 0, \"[ERROR] keep_num must be > 0; refusing to proceed.\"\n\n with cd(\"%(path)s/packages\" % env):\n package_files = sorted(run(\"ls -1\").split())\n package_files = [_.replace(\".tar.gz\", \"\") for _ in package_file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the positionon the 'Scan Data' and adds additional 2 lines to give as a result the lenght of the header in number of lines. This is then used in csv function | def FindHeaderLength():
lookup = 'Lateral um'
with open(filename) as myFile:
for FoundPosition, line in enumerate(myFile, 1):
if lookup in line:
print 'Scan Data found at line:', FoundPosition
break
return FoundPosition+4 | [
"def __read_header(self):\n\n # These for loops are consuming a lot of energy !\n # optimise it...!\n\n print ('Reading header file...')\n fname = self.directory + '/SeisHeader_sem2d.hdr'\n data = pd.read_csv(fname, names=('dt','npts','nsta'), delim_whitespace=True, header=0, nrows=1)\n self.dt = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get follower information from youtube api subscriptions | def get_follower_info(self):
payload = self._get_subscription()
snippet = payload.get('items', [{}])[0].get('snippet', {})
#: re-processing publishedAt
if 'publishedAt' in snippet:
snippet['publishedAt'] = datetime.strptime(
snippet['publishedAt'],
... | [
"def get_followers(request):\n user = request.user\n social = user.social_auth.get(provider='twitch')\n client = TwitchClient(client_id='9hfygng7md3x7maw2g4uko0ednm3hk', oauth_token=social.extra_data['access_token'])\n follows = client.users.get_follows(social.uid)\n for follower in follows:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the global Qt style sheet of the GUI. Returns | def return_global_style_sheet():
style_sheet = '''
QLabel {
font: 12pt "Verdana";
margin-left: 5px;
background-color: transparent;
}
QPushButton {
background-color: #3D3D3D;
border-style: outset;
border: 2px solid #55555... | [
"def appstyle(whom, stylename = 'Plastique',stylecolor = 'Default'):\r\n\r\n## for iz in QtGui.QStyleFactory.keys():\r\n## print iz\r\n\r\n QtGui.QApplication.setStyle(QtGui.QStyleFactory.create(stylename))\r\n QtGui.QApplication.setPalette(QtGui.QApplication.style().standardPalette())\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Qt style sheet for the button that saves JSON configuration files. Returns | def return_save_json_button_style_sheet():
save_json_icon = pkg_resources.resource_filename(
'neurodatapub', "resources/save_json_icon_50x50.png"
)
save_json_icon_pressed = pkg_resources.resource_filename(
'neurodatapub', "resources/save_json_icon_50x50_pressed.png"
)
style_s... | [
"def on_save_style_clicked(self, obj):\n name = cuni(self.top.get_object(\"style_name\").get_text())\n\n self.save_paragraph()\n self.style.set_name(name)\n self.parent.sheetlist.set_style_sheet(name, self.style)\n self.parent.redraw()\n self.window.destroy()",
"def naked... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a path listing to a whitespace separated list. | def path2list(thePath):
theItems = thePath.split( os.pathsep )
theResult = '\n'.join( theItems )
return theResult | [
"def print_path_list(pathl):\n _ = (str(Path(*p.parts[-2:])) for p in pathl)\n return \" - \" + f\"{os.linesep} - \".join(_)",
"def reformatList( listOfPaths):\n newList = []\n first = True\n for seg in listOfPaths: \n newList += seg.asSVGCommand(first)\n first = False\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a tuple (index,value) of the maximum in an 1D array or list | def getMax(array_list):
m = array_list[0]
m_index = 0
for i,value in enumerate(array_list):
if value > m:
m = value
m_index = i
return (m_index,m) | [
"def max_array(func: Callable[[Tuple], np.ndarray], state: Tuple[Union[int, float]]) \\\n -> Tuple[float, Tuple[int], np.ndarray]:\n arr = func((state,)).ravel()\n max_index = np.argmax(arr)\n return (arr[max_index], (max_index,), arr)",
"def get_max_index(a):\n return a.argmax()",
"def maximum(x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns length of Input Layer | def getInputLength(self):
return len(self.X[0]) | [
"def enc_size(self):\n enc_layer = self.net.layers[1] \n assert enc_layer == self.net.layers[-2]\n return enc_layer.output_shape[1]",
"def get_maxlen():\n\n pretrained_model = load_model(cfg.get('data', 'model_file'))\n return pretrained_model.get_layer(name='EL').get_config()['input_length... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns length of Output Layer | def getOutputLength(self):
return len(self.Y[0]) | [
"def enc_size(self):\n enc_layer = self.net.layers[1] \n assert enc_layer == self.net.layers[-2]\n return enc_layer.output_shape[1]",
"def output_size(self):\r\n return self._output_size",
"def upperLayersSize(self):\n return sys.getsizeof(self.segment)",
"def output_size(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna preço e volatilidade realizada do ativo | def vol_e_preco_max(ativo):
rates_frames = pd.read_csv('Dados Históricos\{}_historico.csv'.format(ativo))
vol = rates_frames['retorno'].std() * 252 ** (1/2) # volatilidade realizada anualizada
preco_max = rates_frames['close'].max() # maxima historica
return vol, preco_max | [
"def calcular_preco_com_frete(self):\n\t\treturn self.__preco",
"def data_ultima_alteracao_vencimento(self):\n return self._data_ultima_alteracao_vencimento",
"def prix_tvac(self):\n return self.prix() + self.tva()",
"def data_vencimento_real(self):\n return self._data_vencimento_real",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna tickers de todas as calls negociadas com vencimento até 160 dias. | def call_negociadas(ativo, data_do_vencimento=[]):
ativo = ativo.rstrip('123456789')
calls_codigos = "ABCDEFGHIJKLN"
# Pegar o ticks de todas as opçoes negociadas.
calls_names = []
nomes_calls = []
for codigo in calls_codigos:
calls_name = "*{}".format(ativo)+"{}*".format(codigo)
... | [
"def get_stock_price(df_excld):\n\n ts = TimeSeries(os.environ['ALPHA_VANTAGE_KEY'])\n\n info = []\n symbols = []\n counter = 0\n\n for t in df_excld['Ticker']:\n\n if counter % 5 == 0:\n time.sleep(65)\n\n i, m = ts.get_daily(symbol=t, outputsize='full')\n info.appen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna os payoffs da call, dado o preço da call, strike, e último preço do ativo subjacente e se a opção foi comprada o vendida. | def payoffs(preco, strike, preco_ativo, tipo='c'):
## Gera uma array com preços do ativo subjacente baseado no preço do momento do ativo.
p_min, p_max = int(preco_ativo * 0.70), int(preco_ativo * 1.2)
step = (p_max - p_min) * 100
ativo_subjacente = np.round(np.linspace(p_min,p_max,step... | [
"def get_payoffs(self):\n raise NotImplementedError",
"def get_payoffs(self):\n return self.game.get_payoffs()",
"def get_payoffs(self, profiles):\n pass # pragma: no cover",
"def set_payoffs(self):\r\n\r\n\t\tfor p in self.get_players():\r\n\r\n\t\t\t# if no price (ie price-slider unove... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the colour for a single test point | def setPointColor(self, pointNo, colour):
self.colours[pointNo - 1] = colour
self.setData(pos=self.pos, symbolBrush=self.colours, size=1, symbol=self.symbols, pxMode=False, text=self.text) | [
"def setPointColor(self, color):\n for point in self.points:\n point.color = color",
"def set_color(self, color_id):\n for x in range(len(self.points)):\n self.points[x] = 0\n self.points[color_id] = 50",
"def SetColor(self, p_int, p_int_1, p_int_2, p_int_3):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a base58encoding string, returning bytes | def base58_decode(s):
if not s:
return b''
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
# Convert the string to an integer
n = 0
for c in s:
n *= 58
if c not in alphabet:
raise Exception('Character %r is not a valid base58 character' % ... | [
"def decode(s):\n try:\n if not s:\n return b''\n\n # Convert the string to an integer\n n = 0\n for c in s:\n n *= 58\n if c not in b58_digits:\n raise InvalidBase58Error('Character %r is not a valid base58 character' % c)\n digit = b58_digits.index(c)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Slot to add all pending clients to our client list | def __addNewClients(self):
while True:
client = self.nextPendingConnection()
if (client == None):
break
# Add this socket to our list of clients
self.__clients.append(client);
# When the client disconnects, rem... | [
"def track_clients(self, msg):\n with self.lock:\n self.update(msg.clients + msg.missing_clients)",
"def update_clients(self):\n pass",
"def add_client(self, cli):\n if self.clients.count(cli) is 0:\n self.clients.append(cli)",
"def __add_clients__(self, r, new_clien... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Slot to remove the signal sender from our client list. | def __removeClient(self):
client = self.sender()
if (client in self.__clients):
self.__clients.remove(client)
print "disconnect from", self.__clientName(client) | [
"def del_signal(self, signal): # type: (Signal) -> None\n if signal in self.signals:\n self.signals.remove(signal)",
"def remove_client(self, client):\n self.clients.remove(client)\n #print(\"removing:\" + str(client))",
"def mydisconnect(self, signal, callback):\n self._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send the given data, of type QByteArray, to each of the connected clients. | def sendToClients(self, data):
for client in self.__clients:
result = client.write(data)
if (result < 0):
print "Error writing to", self.__clientName(client), "-", client.errorString()
elif (result <> len(data)):
print "Only wrote", result, "of... | [
"def send_data(self, data):\n for byte in data:\n self.send_byte(byte)",
"def broadcast(self, data):\r\n peers = self.server.connected\r\n for peer in peers:\r\n broadcast_data = {'id': 11, 'data': data}\r\n peer.send(broadcast_data)",
"def broadcast(self, m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts a single fingerprint into the database. | def insert_hash(self, title, artist, song_id:int, fingerprint: str, offset:int):
fingerprint = Fingerprints(song_id=song_id, song_title=title, artist=artist, hash=fingerprint, offset=offset)
fingerprint.save() | [
"def insert(self, fingerprint):\n if len(fingerprint) > 5:\n fingerprint = fingerprint[0:5]\n if self.validate(fingerprint):\n self.fingerprints.add(fingerprint)",
"def insert(self, bhash, sid, offset):\n with self.cursor() as cur:\n cur.execute(self.INSERT_FI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert a multitude of fingerprints. | def insert_hashes(self, title, artist, song_id: int, hashes: List[Tuple[str, int]], batch_size: int = 1000):
data = []
for hsh, offset in hashes:
document = {}
document['song_id'] = song_id
document['hash'] = hsh
document['song_title'] = title
... | [
"def insert(self, fingerprint):\n if len(fingerprint) > 5:\n fingerprint = fingerprint[0:5]\n if self.validate(fingerprint):\n self.fingerprints.add(fingerprint)",
"def insert_hashes(self, sid, hashes):\n values = []\n for bhash, offset in hashes:\n val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts a song name into the database, returns the new identifier of the song. | def insert_song(self, song_name: str, title: str, artist: str, file_hash: str, total_hashes: int) -> int:
id = random.randint(1, 1000000000000)
song = Songs(meta={'id': id}, song_name=song_name, song_title=title, artist=artist, file_sha1=file_hash, total_hashes=total_hashes)
song.save()
... | [
"def insert_playlist_into_db(self, name):\n\n playlist_ = (name, self.id)\n sql = (\"INSERT INTO playlists (playlist_name, userID) VALUES (?, ?)\")\n try:\n self.cursor.execute(sql, playlist_)\n id = self.cursor.lastrowid\n self.conn.commit()\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets a specific song as having all fingerprints in the database. | def set_song_fingerprinted(self, song_id):
song = Songs.get(id=song_id)
song.fingerprinted = True
song.save() | [
"def set_song_fingerprinted(self, song_id):\n print(\"song_id to set fingerprinted: \",song_id)\n record = {\n \"doc\": {\n FIELD_FINGERPRINTED: True\n },\n \"doc_as_upsert\": True \n }\n self.cursor.update(index=SONGS_INDEXNAME, id=song_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searches the database for pairs of (hash, offset) values. | def return_matches(self, hashes, batch_size: int=1000):
# Create a dictionary of hash => offset pairs for later lookups
mapper = {}
for hsh, offset in hashes:
if hsh in mapper.keys():
mapper[hsh].append(offset)
else:
mapper[hsh] = [offset]
... | [
"def return_matches(hashes):\n # Create a dictionary of hash => offset pairs for later lookups\n mapper = {}\n for hash, offset in hashes:\n mapper[hash.upper()] = offset\n\n # Get an iteratable of all the hashes we need\n values = mapper.keys()\n\n conn = MySQLdb.connect(**connection_strin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the combination of self and self.next. sourcepoints has to be set | def mergedWithNext(self, newPath=None):
if newPath is None: newPath = Path( numpy.concatenate([self.points, self.next.points]) )
newPath.sourcepoints = self.sourcepoints
newPath.prev = self.prev
if self.prev : newPath.prev.next = newPath
newPath.next = self.next.next
if ... | [
"def link(self):\n for i in range(len(self.points) - 1):\n self.points[i].next = self.points[i + 1]\n self.points[i + 1].prev = self.points[i]",
"def next(self):\n return super(CircSLelement, self).next",
"def __next__(self):\n if self.iterator < len(self.points):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the point projection of p onto this segment | def projectPoint(self,p):
a,b,c = self.a, self.b, self.c
x,y = p
return numpy.array( [ b*(x*b-y*a) - c*a, a*(y*a-x*b) - c*b ] ) | [
"def getProjectedPoint(self, p):\n pp = self.projectedOnLine(p)\n if self.inBoundingBox(pp): # Is the projected point in inside the line segment\n return pp\n return None # Projection not within the line segment window.",
"def proj(self, p):\n raise NotImplementedError",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify self such as self.pointN is the intersection with next segment | def setIntersectWithNext(self, next=None):
if next is None:
next = self.next
if next and next.isSegment():
if abs(self.normalv.dot(next.unitv)) < 1e-3:
return
debug(' Intersect',self, next, ' from ', self.point1, self.pointN, ' to ' ,next.point1, next... | [
"def __init__(self, type_event, current_segment, current_point):\n self.type_event = type_event\n #!!current_segm = Tableau de couple de segments intersectés dans le cas d'une intersection(gauche, droite)!!\n self.current_segment = current_segment\n self.current_point = current_point #Po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Translate this segment by tr | def translate(self, tr):
c = self.c -self.a*tr[0] -self.b*tr[1]
self.c =c
self.pointN = self.pointN+tr
self.point1 = self.point1+tr
self.points +=tr | [
"def translate():\n pass",
"def translate(self, table): # real signature unknown; restored from __doc__\n return \"\"",
"def tr(self, tr):\n\n self._tr = tr",
"def translateBy(self, vec, space='preTransform'):\n \n pass",
"def __translate_text(self, event):\n\t\tselected = sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a node in the xml structure corresponding to this rect | def addToNode(self, refnode):
ele = inkex.etree.Element('{http://www.w3.org/2000/svg}rect')
self.fill(ele)
refnode.xpath('..')[0].append(ele)
return ele | [
"def add_node(self, node):",
"def addRect(self, **opts):\n\t\tif opts is None:\n\t\t\topts = {}\n\t\trect_tag = self.svg_dom.createElement(\"rect\")\n\t\trect_tag.setAttribute(\"id\",opts.get(\"id\",\"\"))\n\t\trect_tag.setAttribute(\"width\",str(opts[\"width\"]))\n\t\trect_tag.setAttribute(\"height\",str(opts[\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the segments in pathGroups can form a rectangle. Returns a Rectangle or None | def isRectangle( pathGroup):
#print 'xxxxxxxx isRectangle',pathGroups
if isinstance(pathGroup, Circle ): return None
segmentList = [p for p in pathGroup.listOfPaths if p.isSegment() ]#or p.effectiveNPoints >0]
if len(segmentList) != 4:
debug( 'rectangle Failed at length ', le... | [
"def is_rectal(self):\n return bool(self.locations and set(self.locations) <= set(StandardTerminology.RECTAL_LOCATIONS)) \\\n or bool(self.depth and 4 <= self.depth <= 16)",
"def is_rect(self):\n\n #too little vertices\n if len(self) < 3 or len(self) > 4:\n return Fal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
perform a linear regression on 2dim array a. Creates a segment object in return | def regLin(a , returnOnlyPars=False):
sumX = a[:,0].sum()
sumY = a[:,1].sum()
sumXY = (a[:,1]*a[:,0]).sum()
a2 = a*a
sumX2 = a2[:,0].sum()
sumY2 = a2[:,1].sum()
N = a.shape[0]
pa = (N*sumXY - sumX*sumY)/ ( N*sumX2 - sumX*sumX)
pb = (sumY - pa*sumX) /N
if returnOnlyPars:
... | [
"def linearRegression():\n global w\n tagger = alg.pinv( np.matmul( np.transpose(x), x ) )\n pseudoInverse = np.matmul( tagger, np.transpose(x) )\n w = np.matmul( pseudoInverse, y )\n w = np.asarray([w[1]])",
"def nnRegression(data):",
"def linear_regression():\n return LinearRegression()",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cluster together consecutive angles with similar values (within 'dAng'). | def clusterAngles(array, dAng=0.15):
N = len(array)
closebyAng = numpy.zeros( (N,4) , dtype=int)
for i,a in enumerate(array):
cb = closebyAng[i]
cb[0] =i
cb[2]=i
cb[3]=i
c=i-1
# find number of angles within dAng in nearby positions
while c>-1: # indi... | [
"def cluster(people_location, precision=40):\n points = [location for pid, location in people_location]\n p_ids = [p_id for p_id, location in people_location]\n flag = [0 for x in range(len(points))]\n cluster_center = []\n cluster_points = []\n buses = []\n for i, point in enumerate(points):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform Segment extension from list of Path segmentList returns the updated list of Path objects | def extendSegments(segmentList, relD=0.03, qual=0.5):
fwdExt = FwdExtender(relD, qual)
bwdExt = BwdExtender(relD, qual)
# tag all objects with an attribute pointing to the extended object
for seg in segmentList:
seg.mergedObj = seg # by default the extended object... | [
"def reformatList( listOfPaths):\n newList = []\n first = True\n for seg in listOfPaths: \n newList += seg.asSVGCommand(first)\n first = False\n return newList",
"def segments(self, params):\n\n if len(params) < 2:\n raise ValueError(\"at least two parameters ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a SVG paths list (same format as simplepath.parsePath) from a list of Path objects Segments in paths are added in the new list simple Path are retrieved from the original refSVGPathList and put in the new list (thus preserving original bezier curves) | def reformatList( listOfPaths):
newList = []
first = True
for seg in listOfPaths:
newList += seg.asSVGCommand(first)
first = False
return newList | [
"def _points_to_paths(self, points):\n prev = points[0]\n result = []\n for point in points[1:]:\n path = specctraobj.Path()\n path.aperture_width = self._from_pixels(1)\n path.vertex.append(prev)\n path.vertex.append(point)\n result.append... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
form clusters of similar quantities from input 'values'. Clustered values are not necessarily contiguous in the input array. Clusters size (that is maxmin) is < relScluster_average | def clusterValues( values, relS=0.1 , refScaleAbs='range' ):
if len(values)==0:
return []
if len(values.shape)==1:
sortedV = numpy.stack([ values , numpy.arange(len(values))] ,1)
else:
# Assume value.shape = (N,2) and index are ok
sortedV = values
sortedV = sortedV[ num... | [
"def clusterAlgorithm(values):\n clusterMap = dict()\n for value in values:\n if value[2] not in clusterMap.keys():\n clusterMap[value[2]] = []\n clusterMap[value[2]].append(value)\n frequency = [float(len(clusterMap[value[2]])) for value in values]\n total = sum(frequency)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove small Path objects which stand between 2 Segments (or at the ends of the sequence). Small means the bbox of the path is less then 5% of the mean of the 2 segments. | def removeSmallEdge(self, paths, wTot,hTot):
if len(paths)<2:
return
def getdiag(points):
xmin,ymin,w,h = computeBox(points)
return sqrt(w**2+h**2), w, h
removeSeg=[]
def remove(p):
removeSeg.append(p)
if p.next : p.next.prev = ... | [
"def removeSmallRegions(self):\n tolerance=0.0000001\n \n # find the area of largest regions\n area = 0\n for nameOfPortion,poly in self.portionOfRegion.iteritems():\n if area<poly.area():\n area = poly.area()\n \n # remove small reg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
group circles radius and distances into cluster. Then set circles radius according to the mean of the clusters they belong to. | def prepareRadiusEqualization(self, circles, otherDists, relSize=0.2):
ncircles = len(circles)
lengths = numpy.array( [c.radius for c in circles]+otherDists )
indices = numpy.array( range(ncircles+len(otherDists) ) )
clusters = clusterValues(numpy.stack([ lengths, indices ],1 ), relSize,... | [
"def Mean_Radius(ClusterResults):\r\n return np.mean([np.ma.average(CR.Size95X, weights=CR.Members) for CR in ClusterResults])",
"def topology_circle(self, radius):\n\t\tfor s in self.sites:\n\t\t\ts.clear_neighbor()\n\t\tfor i in range(len(self.sites)):\n\t\t\tfor r in range(radius):\n\t\t\t\tself.sites[i].ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
move centers of circles onto the segments if close enough | def centerCircOnSeg(self, circles, segments, relSize=0.18):
for circ in circles:
circ.moved = False
for seg in segments:
for circ in circles:
d = seg.distanceTo(circ.center)
#debug( ' ', seg.projectPoint(circ.center))
... | [
"def trackCircle( center, rad, imShape ):\n \n \"\"\"\n center = ccnt\n rad = rd\n inShape = segImg.shape\n debug = False\n \"\"\"\n \n # check if whole circle is inside image\n if (center[0] - rad) < 0 or (center[0] + rad) >= imShape[1] or (center[1] - rad) < 0 or (center[1] + rad) >... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if the points and their tangents represent a circle The difficulty is to be able to recognize ellipse while avoiding paths small fluctuations a nd false positive due to badly drawn rectangle or nonconvex closed curves. | def checkForCircle(self, points, tangents):
if len(points)<10:
return False, 0
if all(points[0]==points[-1]): # last exactly equals the first.
# Ignore last point for this check
points = points[:-1]
tangents = tangents[:-1]
#print 'Removed las... | [
"def is_circle(points, scale, verbose=False):\n\n # make sure input is a numpy array\n points = np.asanyarray(points)\n scale = float(scale)\n\n # can only be a circle if the first and last point are the\n # same (AKA is a closed path)\n if np.linalg.norm(points[0] - points[-1]) > tol.merge:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds segments part in a list of points represented by svgCommandsList. The method is to build the (averaged) tangent vectors to the curve. Aligned points will have tangent with similar angle, so we cluster consecutive angles together to define segments. Then we extend segments to connected points not already part of o... | def segsFromTangents(self,svgCommandsList, refNode):
sourcepoints, svgCommandsList = toArray(svgCommandsList)
d = D(sourcepoints[0],sourcepoints[-1])
x,y,wTot,hTot = computeBox(sourcepoints)
aR = min(wTot/hTot, hTot/wTot)
maxDim = max(wTot, hTot)
isClosing = aR*0.2 > d/m... | [
"def _draw_segments(frame, segments):\n for segment in segments:\n cv2.line(frame, segment[0], segment[1],\n color=(0, 255, 255), thickness=2)\n cv2.circle(frame, segment[0], radius=3,\n color=(255, 0, 0), thickness=-1)\n cv2.circle(f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the TMDB API discover endpoint | def test_discover(self):
response = Tmdb.discover()
self.assertTrue(int(response.status_code) == 200)
data = response.json()
self.assertTrue(isinstance(data['results'], list))
# TODO check if all the shows are in the good format (can be from_dict/to_dict) | [
"def test_discovery_apis_get(self):\n pass",
"def test_discovery_swagger_apis_get(self):\n pass",
"def test_retrieve_database(self):\n pass",
"def test_openstack_rest_test_get(self):\n pass",
"def test_get_devices(self):\n pass",
"def discover(self):\n pass",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the TMDB API get show | def test_detail(self):
response = Tmdb.detail(69740)
self.assertTrue(int(response.status_code) == 200)
data = response.json()
self.assertTrue(data['id'])
self.assertTrue(data['name'])
# TODO check if all the shows are in the good format (can be from_dict/to_dict) | [
"def test_discover(self):\n response = Tmdb.discover()\n self.assertTrue(int(response.status_code) == 200)\n data = response.json()\n self.assertTrue(isinstance(data['results'], list))\n # TODO check if all the shows are in the good format (can be from_dict/to_dict)",
"def test_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the TMDB API seasons endpoint | def test_seasons(self):
response = Tmdb.season(tmdb_show_id = 69740, season_number = 1)
self.assertTrue(int(response.status_code) == 200)
data = response.json()
self.assertTrue(isinstance(data['episodes'], list))
# TODO check if all the shows are in the good format (can be from_d... | [
"def test_get_season_list(self):\n msg = \"Response status is not 200.\"\n response = self.api.get_season_list()\n self.assertEqual(response.status_code, 200, msg)",
"def test_get_season_standings(self):\n msg = \"Response status is not 200.\"\n response = self.api.get_season_st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a base64 encoded Netscape SPKI DER to a crypto.NetscapeSPKI. PyOpenSSL does not yet support doing that by itself, so some work around through FFI and "internalspatching" trickery is required to perform this | def netscape_spki_from_b64(b64):
if not hasattr(netscape_spki_from_b64, 'NETSCAPE_SPKI_b64_decode'):
from cffi import FFI as CFFI
from OpenSSL._util import ffi as _sslffi, lib as _ssllib
cffi = CFFI()
cffi.cdef('void* NETSCAPE_SPKI_b64_decode(const char *str, int len);')
lib ... | [
"def EncodePrivate(sk):\n return bytes(sk)",
"def make_cert_for_spki_request(spki_req_b64, serial, ident):\n spki_obj = netscape_spki_from_b64(spki_req_b64)\n if spki_obj is None:\n raise ValueError('Invalid SPKI object')\n\n root_crt = _try_load_ca_cert(cfg.ca_cert_path())\n root_key = _try... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a new private key and saves it to the given path. | def _generate_ca_private_key(path):
DEFAULT_KEY_ALG = crypto.TYPE_RSA
DEFAULT_KEY_BITS = 2048
pkey = crypto.PKey()
pkey.generate_key(DEFAULT_KEY_ALG, DEFAULT_KEY_BITS)
data = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
open(path, 'wb').write(data)
return pkey | [
"def generate_and_add():\n\n mnemonic = generate_mnemonic()\n print(\"Generating private key.\")\n add_private_key_seed(mnemonic)",
"def create_keypair(self):\n self.keypair = rsa.generate_private_key(\n public_exponent=65537,\n key_size=4096,\n backend=default_bac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the CA private key as a crypto.PKey object. Caches the result forever we do not support reloading the CA key dynamically during runtime, and the global configuration object is not expected to change either. | def get_ca_private_key():
return _try_load_ca_private_key(cfg.ca_private_key_path()) | [
"def _generate_ca_private_key(path):\n DEFAULT_KEY_ALG = crypto.TYPE_RSA\n DEFAULT_KEY_BITS = 2048\n\n pkey = crypto.PKey()\n pkey.generate_key(DEFAULT_KEY_ALG, DEFAULT_KEY_BITS)\n data = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)\n open(path, 'wb').write(data)\n\n return pkey",
"def g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a new certificate and saves it to the given path. | def _generate_ca_cert(path, pkey):
crt = _make_base_cert(pkey, 5000, socket.gethostname(),
random.randrange(0, 2**64))
crt.set_issuer(crt.get_subject())
crt.sign(pkey, 'sha256')
data = crypto.dump_certificate(crypto.FILETYPE_PEM, crt)
open(path, 'wb').write(data) | [
"def save(self, cert_path: Union[Path, str], key_path: Union[Path, str]):\n cert_path, key_path = Path(cert_path), Path(key_path)\n\n cert_path.parent.mkdir(parents=True, exist_ok=True)\n with cert_path.open(\"wb\") as file:\n file.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a certificate for a given Netscape SPKI request. | def make_cert_for_spki_request(spki_req_b64, serial, ident):
spki_obj = netscape_spki_from_b64(spki_req_b64)
if spki_obj is None:
raise ValueError('Invalid SPKI object')
root_crt = _try_load_ca_cert(cfg.ca_cert_path())
root_key = _try_load_ca_private_key(cfg.ca_private_key_path())
crt = _ma... | [
"def create_certificate_from_csr(certificateSigningRequest=None, setAsActive=None):\n pass",
"def createCertRequest(pkey, digest=\"sha256\", **name):\n req = crypto.X509Req()\n subj = req.get_subject()\n\n for key, value in name.items():\n setattr(subj, key, value)\n\n req.set_pubkey(pkey)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
main(quiet=False) Pulling all necessary files for using the starformation script This script pulls the fitsfiles for the radiation models from the MPIAfolder of Thomas Robitaille, if the files have been moved feel free to contact robitaille.de It also pulls the extinction law from | def main(quiet=False):
if quiet:
output_stream = StringIO()
else:
output_stream = sys.stdout
newpath = r'%s/models' % os.getcwdu()
if not os.path.exists(newpath): os.makedirs(newpath)
newpath = r'%s/out' % os.getcwdu()
if not os.path.exists(newpath): os.makedirs(newpath)
exi... | [
"def main():\n\n args = sys.argv\n if '-h' in args:\n print(main.__doc__)\n sys.exit()\n\n dataframe = extractor.command_line_dataframe([ ['WD', False, '.'], ['ID', False, ''],\n ['usr', False, ''], ['ncn', False, '1'],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open Arduino's serial port and encode incoming message to files. Calculates average activity of each bin. | def encode(port,baudrate,n_pir,template,winsize,destructive):
template_filename=template+"%02d"
if destructive:
for n in range(n_pir):
with open(template_filename%(n+1),'wb') as f:
f.write()
try:
t1=time.time()
click.echo("[ ] Serial port")
ser=ser... | [
"def main():\r\n N = 200 # number of samples\r\n port_name = 'COM4' # serial port name\r\n port_speed = 19200 # serial port speed/ baudrate (bits per second)\r\n \r\n t,percent = get_data(N,port_name,port_speed) # get data\r\n file_write(t,percent) # write data to file\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save figure in specified format(s) | def save_figure(plt, name, fmt='all'):
if fmt in ('jpg', 'all'):
fname = os.path.join(SAVEDIR, f"{name}.jpg")
plt.savefig(fname, **FIGURE_KWARGS['jpg'])
if fmt in ('svg', 'all'):
fname = os.path.join(SAVEDIR, f"{name}.svg")
plt.savefig(fname, **FIGURE_KWARGS['svg']) | [
"def save_figure(\r\n figure, name=\"fig\", save_at=\"\", save_fmts=[\"png\"], output=False, **kwargs\r\n):\r\n default_config = dict(bbox_inches=\"tight\", transparent=True)\r\n config = default_config.copy()\r\n config.update(kwargs)\r\n save_at = Path(save_at)\r\n if not save_at.exists():\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot frequency of unique list items for coded columns Handle columns with list values differently from columns with single values | def plot_coded_column(df_all, col, saveFig=False, figParams=None, label='', orient='h', size=None, plotType='bar', scaleToMax=True):
df = df_all.copy(deep=True)
isListCol = any([isinstance(d, list) for d in df[col]])
if isListCol:
# Make sure all values in column are lists
df[col] ... | [
"def analyze_column_frequencies():\n def dna_freqs(xs):\n return [xs.count(b)/float(len(xs)) for b in \"ACGT\"]\n all_freqs = concat([map(dna_freqs,transpose(getattr(tfdf_obj,tf)))\n for tf in tfdf_obj.tfs])\n for k,(i,j) in enumerate(choose2(range(4))):\n plt.subplot(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a valid system description. Makes a best effort to autopopulate some of the fields, but should be manually checked prior to submission. The system name is autogenerated as ``"[world_size]x[device_name]_composer"``, e.g. ``"8xNVIDIA_A100_80GB_composer"``. | def get_system_description(
submitter: str,
division: str,
status: str,
system_name: Optional[str] = None,
host_processors_per_node: Optional[int] = None,
) -> Dict[str, str]:
is_cuda = torch.cuda.is_available()
cpu_info = cpuinfo.get_cpu_info()
system_desc = {
'submitter': subm... | [
"def create_system(sys_structure):\n pass",
"def __init__(self, name):\r\n super(SystemDescription, self).__init__()\r\n self.name = name",
"def systemSpec(self):\n\n cinfo = cpuinfo.get_cpu_info()\n data = {}\n data[\"Processor\"] = cinfo['brand_raw']\n data[\"CPU\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch feature and labels from dataset using index of the sample. | def __getitem__(self, idx):
sample = self.samples[idx]
from PIL import Image
image = Image.open(self.DatasetWrapper.features(sample))
label = self.DatasetWrapper.label(sample)
image = self.transformer(image)
return image, label | [
"def _get_feature_from_index(self, index):\n return self.features[self._use_ixs][index]",
"def get_data_by_index(self, index):\n pass",
"def get_data(features, labels_aud, labels_foc, files, indices):\n features = [features[idx] for idx in indices]\n labels_aud = [labels_aud[idx] for idx in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetches the DataLoader object for each type in types. | def fetch_dataloader(types, params, CViters):
dataloaders = {}
assert CViters[0] != CViters[1], 'ERROR! Test set and validation set cannot be the same!'
if len(types)>0:
for split in types:
if split in ['train', 'val', 'test']:
dl = DataLoader(imageDataset(split, params, CViters), batch_size=params.batch_... | [
"def fetch_dataloader(types, dataset_dir, params):\n\n dataloaders = {}\n samplers = {}\n\n for split in ['train', 'val', 'test']:\n if split in types:\n path = os.path.join(dataset_dir, \"{}\".format(split))\n\n # Use the train_transformer if training data, else use eval_trans... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
T1_int = 90e3 Intrinsic T1 of the qubit QPT1 = 1.5e6 Guess the lifetime of the quasiparticles half_decay_point = 1e6 The QP_delay time that would make qubit relax halfway to ground state with T1_delay=0, i.e. relax during readout pulse eff_T1_delay = 800.0 The effective T1_delay due to the finite length of the readout ... | def smart_T1_delays(T1_int=90e3, QPT1=1.5e6, half_decay_point=1e6, eff_T1_delay=800.0, probe_point=0.5, meas_per_QPinj=30, meas_per_reptime=5):
# rep_time = 1.0e9/fg.get_frequency()
# T1_QPref = 1/(np.log(2)/eff_T1_delay-1/T1_int) # T1 at half decay point = effective readout delay/ln(2), excluding intrinsi... | [
"def measureT1(self, delays, data=None, t1Parameters=None, dataParameters=None):\n if dataParameters is None:\n dataParameters = dict()\n dataParameters['addToDataManager'] = True\n dataParameters['save'] = True\n print t1Parameters\n if t1Parameters is None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the container could in theory accept the fluid given. When returning False, accept is never called | async def could_accept_fluid(
cls,
itemstack: ItemStack,
fluidstack: FluidStack,
) -> bool:
return False | [
"async def accept_fluid(\n cls,\n itemstack: ItemStack,\n fluidstack: FluidStack,\n insert_parts=True,\n ) -> bool:\n return False",
"async def can_provide_fluid(\n cls,\n itemstack: ItemStack,\n fluidstack: FluidStack,\n ) -> bool:\n return Fal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts a certain amount of fluid The fluidstack may contain remaining liquid if not everything could be accepted if insert_parts is True | async def accept_fluid(
cls,
itemstack: ItemStack,
fluidstack: FluidStack,
insert_parts=True,
) -> bool:
return False | [
"def insert_parts(self, parts):\r\n self.board.insert_parts(parts)\r\n self.set_changed(parts)",
"def _insert_parts_into(hierarchy, module, weight_calculator, parts):\n\tif len(parts) == 1:\n\t\treturn _add_leaf(hierarchy, module, weight_calculator, name=parts[0])\n\tnext_branch = parts[0]\n\texisti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the given fluid container can provide the given fluid with the given amount | async def can_provide_fluid(
cls,
itemstack: ItemStack,
fluidstack: FluidStack,
) -> bool:
return False | [
"async def could_accept_fluid(\n cls,\n itemstack: ItemStack,\n fluidstack: FluidStack,\n ) -> bool:\n return False",
"async def accept_fluid(\n cls,\n itemstack: ItemStack,\n fluidstack: FluidStack,\n insert_parts=True,\n ) -> bool:\n return Fa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes a certain amount of fluid from the container Is allowed to modify the fluidstack when not everything is provided when extract_parts is True | async def provide_fluid(
cls,
itemstack: ItemStack,
fluidstack: FluidStack,
extract_parts=True,
) -> bool: | [
"def clean_up_slices(self):\n self.delete_data_im_slices()\n self.delete_label_im_slices()",
"def remove_footer(img_raw):\r\n crop_height = np.floor(img_raw.shape[0]*0.955).astype(int)\r\n img_mod = img_raw[0:crop_height, :]\r\n return(img_mod)",
"def remove_excess_parts(self, observation... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View that allows to assign task quotas for accepted GHOP organization. This view allows the program admin to set the task quota limits and change them at any time when the program is active. | def assignTaskQuotas(self, request, access_type, page_name=None,
params=None, filter=None, **kwargs):
# TODO: Once GAE Task APIs arrive, this view will be managed by them
program_entity = ghop_program_logic.logic.getFromKeyFieldsOr404(kwargs)
from soc.modules.ghop.views.models impor... | [
"def assignTaskQuotasGet(self, request, context, org_params,\n page_name, params, entity, **kwargs):\n\n from soc.modules.ghop.views.models.organization import view as org_view\n \n logic = params['logic']\n program_entity = logic.getFromKeyFieldsOr404(kwargs)\n \n org_par... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles the POST request for the task quota allocation page. | def assignTaskQuotasPost(self, request, context, org_params,
page_name, params, entity, **kwargs):
ghop_org_logic = org_params['logic']
error_orgs = ''
for link_id, task_count in request.POST.items():
fields = {
'link_id': link_id,
'scope': entity,
... | [
"def assignTaskQuotasGet(self, request, context, org_params,\n page_name, params, entity, **kwargs):\n\n from soc.modules.ghop.views.models.organization import view as org_view\n \n logic = params['logic']\n program_entity = logic.getFromKeyFieldsOr404(kwargs)\n \n org_par... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles the GET request for the task quota allocation page. | def assignTaskQuotasGet(self, request, context, org_params,
page_name, params, entity, **kwargs):
from soc.modules.ghop.views.models.organization import view as org_view
logic = params['logic']
program_entity = logic.getFromKeyFieldsOr404(kwargs)
org_params['list_tem... | [
"def quota_get(self, context, project_id, resource_name):",
"def get(self, request):\n\n quota_settings = settings.PROJECT_QUOTA_SIZES\n size_order = settings.QUOTA_SIZES_ASC\n\n self.project_id = request.keystone_user['project_id']\n regions = request.query_params.get('regions', None)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View method used to edit Task Type tags. | def taskTypeEdit(self, request, access_type, page_name=None,
params=None, filter=None, **kwargs):
params = dicts.merge(params, self._params)
try:
entity = self._logic.getFromKeyFieldsOr404(kwargs)
except out_of_band.Error, error:
return helper.responses.errorResponse(
... | [
"def taskTypeTagEdit(self, request, access_type, page_name=None,\n params=None, filter=None, **kwargs):\n\n get_params = request.GET\n\n order = get_params.getlist('order')\n program_key_name = get_params.get('program_key_name')\n\n program_entity = ghop_program_logic.logic.getFromK... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View method used to edit a supplied Task Type tag. | def taskTypeTagEdit(self, request, access_type, page_name=None,
params=None, filter=None, **kwargs):
get_params = request.GET
order = get_params.getlist('order')
program_key_name = get_params.get('program_key_name')
program_entity = ghop_program_logic.logic.getFromKeyName(
... | [
"def taskTypeEdit(self, request, access_type, page_name=None,\n params=None, filter=None, **kwargs):\n\n params = dicts.merge(params, self._params)\n\n try:\n entity = self._logic.getFromKeyFieldsOr404(kwargs)\n except out_of_band.Error, error:\n return helper.responses.errorRes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all the accepted orgs for the given program. | def acceptedOrgs(self, request, access_type,
page_name=None, params=None, filter=None, **kwargs):
from soc.modules.ghop.views.models.organization import view as org_view
logic = params['logic']
program_entity = logic.getFromKeyFieldsOr404(kwargs)
fmt = {'name': program_entity.name... | [
"def program(cls, program):\n search_str = ArtePlus7.PROGRAMS[program]\n all_programs = cls.search(search_str)\n programs = [p for p in all_programs if p.name == program]\n return programs",
"def list_orgs(self):\n orgs = list(self.orgs.keys())\n orgs.sort()\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load point cloud from filename csv | def from_csv(self, filename):
points = np.genfromtxt(filename, delimiter=",")
assert points.shape[1] == 2
self.N = points.shape[0]
self.points = points
self.original_points = points | [
"def load_point_cloud(self, filename):\n f = sio.loadmat(filename)\n data = f['blob'][:]\n data -= np.mean(data, 0)\n data /= np.amax(abs(data))\n label = DataHandler.get_label_from_filename(filename)\n if self.use_softmax:\n l = np.zeros([2])\n l[labe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Two dimensional rotation matrix to rotate a line parallel with xaxis given gradient m If m is negative, we want to rotate through | arctan(m) | degrees, while if m is positive we want to rotate through |arctan(m)|. But sgn(arctan(m)) = sgn(m), so set theta = np.arctan(m). | def _rotation_from_gradient(self,m):
theta = -np.arctan(m)
self.current_theta = theta
return self._rotation_from_angle(theta) | [
"def x_rotmat(theta):\n cos_t = np.cos(theta)\n sin_t = np.sin(theta)\n return np.array([[1, 0, 0],\n [0, cos_t, -sin_t],\n [0, sin_t, cos_t]])",
"def rotate_mat(theta, phi):\n return np.dot(rotation_matrix([1, 0, 0], theta), \n rotation_matrix(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reverse hat transformation on a vector P_star = (0,c) > (x,y) | def rev_hat_transformation(self, P_star):
rotation_matrix = self._rotation_from_angle(self.current_theta)
P_star = np.dot(rotation_matrix, P_star)
P_star = P_star + self.current_point
return P_star | [
"def hat_operator(theta):\n mat = np.zeros((3, 3))\n mat[0, 1] = -theta[2, 0]\n mat[0, 2] = theta[1, 0]\n mat[1, 0] = theta[2, 0]\n mat[1, 2] = -theta[0, 0]\n mat[2, 0] = -theta[1, 0]\n mat[2, 1] = theta[0, 0]\n return mat",
"def hat(v: torch.Tensor) ->torch.Tensor:\n N, dim = v.shape\n if dim != 3:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For xy = (x,y) fit a weighted (by W) regression of the form y = ax^2 + bx + c, then return c | def quadratic_fit(self, xy, W):
# first construct the independent matrix
y = xy[:,1]
x = xy[:,0]
X = np.column_stack([np.ones(len(x)),
x, np.power(x,2)])
wls_model = sm.WLS(y, X, weights = 1.0/W)
wls_model_results = wls_model.fit()
[c,b,a] = wls_model_results.params
return [a,b,c] | [
"def linregress_weights(x,y,w):\n # compute the weighted means and weighted deviations from the means\n # wm denotes a \"weighted mean\", wm(f) = (sum_i w_i f_i) / (sum_i w_i)\n assert(len(x) == len(y) and len(x) == len(w))\n\n W = np.sum(w)\n wm_x = np.average(x,weights=w)\n wm_y = np.average(y,w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
setting of Target and Features of ML_data + choose beetween ModelQua() or ModelQuali() depend of Target type | def test(self, test):
self.ml_data.set_target(test[0])
self.ml_data.set_features(test[1])
if self.ml_data.target_type.all() == np.float64 or self.ml_data.target_type.all() == np.int64:
self.model_qua.open()
else:
self.model_quali.open() | [
"def fit(self, features, target, **kwargs):\n self.features = features\n self.target = target\n super(tpot_class, self).fit(features, target, **kwargs)",
"def train_model_for_shap(allFeatures, train_ml, test_ml, df_ml, classification_model, language_model, fold):\n # list of an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Launch all model from dict signal of ModelQua() After the result output from model Will be stored in the result windows by a setting and then these windows will be sent to the main window by signal | def model_qua_launch(self, dict):
list_result = []
if "SVR" in dict:
SVR = dict["SVR"]
if SVR["Auto"]:
result = SVR_b(self.ml_data.feature, self.ml_data.target, SVR["Auto"])
model, score, graph, time = result
result_win = Win... | [
"def _emitRunModelSignal(self):\r\n log.info(\"Run button pressed.\")\r\n\r\n # get model names as strings\r\n selectedModelNames = [item.text() for item in self.modelListWidget.selectedItems()]\r\n\r\n # get model classes from models folder\r\n modelsToRun = [model for model in m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function which browse csv file/Text file/Xlsx file | def browse_1(self):
file = QFileDialog()
filter_name = "Csv files (*.csv);;Text files (*.txt);;Xls files (*.xls);; Xlsx files (*.xlsx)"
file.setNameFilter(filter_name)
if file.exec():
filenames = file.selectedFiles()
self.browseLine.setText(str(filenames[0])... | [
"def openFile(self):\n self.filepath = askopenfilename(\n #(\"Text Files\", \"*.txt\"),\n filetypes=[(\"All Files\", \"*.*\")])\n sep = self.config[\"default\"][\"sep\"]\n sep = sep[1:-1]\n with open(self.filepath, \"r\") as input_file:\n df = pd.read_csv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the success status is between [200, 300). | def _default_is_success(status_code):
return status_code >= 200 and status_code < 300 | [
"def _check_status_code(status_code):\n if 200 <= status_code < 300:\n return True\n else:\n return False",
"def ok(self):\n if not self._responses:\n return False\n return 200 <= self._responses[-1].code < 400",
"def is_http_error(status):\n return True if int(st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Silence warnings from requests.packages.urllib3. See DCOS1007. | def silence_requests_warnings():
requests.packages.urllib3.disable_warnings() | [
"def suppress_insecure_request_warns(env) -> bool:\n verify = True\n if env in SUPPRESS_WARNING_ENVS:\n requests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n verify = False\n return verify",
"def DisableSSLVerify():\n\n\t\ttry:\n\t\t\trequests.packages.urllib3.disable_warning... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sift up an element in the heap. | def _sift_up(self, i):
while i > 0:
p = (i-1)//2
if self._heap[i] < self._heap[p]:
self._swap(i, p)
i = p
else:
break | [
"def sift_up(self, index):\n if self.size() == 1:\n return\n parent_index = self.parent(index)\n # sift up if it is larger than its parent\n while index > 0 and self.heap[index] > self.heap[parent_index]:\n self.heap[index], self.heap[parent_index] = self.heap[paren... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sift down an element in the heap. | def _sift_down(self, i):
mini = i
l = 2*i + 1
if l < self._size and\
self._heap[l] < self._heap[mini]:
mini = l
r = 2*i + 2
if r < self._size and\
self._heap[r] < self._heap[mini]:
mini = r
if mini != i:
self._sw... | [
"def __siftup(heap, nodes, pos, stopPos = 0):\n # Loop until past stopping position\n while pos > stopPos:\n # Set parent position\n parentPos = (pos - 1) >> 1\n\n # Swap if child less than parent\n if heap[pos][0] < heap[parentPos][0]:\n Grap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update an element in the heap. | def _update(self, priority, key):
i = self._index[key]
item = self._heap[i]
old_priority = item.priority
item.priority = priority
if priority < old_priority:
self._sift_up(i)
else:
self._sift_down(i) | [
"def update_node(self, node, element):\n self._validate_node(node)\n node._element = element\n parent = self.parent(node)\n if parent and node.element() < parent.element():\n self._upheap(node) # New key is smaller than parent\n else:\n self._dow... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the index of the current cup, it moves around while we poke and prod the list | def current_cup_idx(self):
return self.cups.index(self.current_cup) | [
"def pick_up_1_cup(self) -> int:\n current_position = self.cups.index(self.current)\n if current_position < len(self.cups) - 1: # Current cup is not on the end of the list.\n return self.cups.pop(current_position + 1)\n return self.cups.pop(0)",
"def select_new_current_cup(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove the cup after the provided index from the list and return it | def take_cup_after(self, idx: int):
target_idx = idx + 1
if target_idx >= len(self.cups):
target_idx = 0
result = self.cups[target_idx]
del self.cups[target_idx]
return result | [
"def remove(self, index):\n self.__validate_index(index)\n value = self.__list[index]\n self.__list = self.__list[:index] + self.__list[index + 1:]\n return value",
"def remove_from_list(self,list_,index):\r\n try:\r\n return list_.pop(self._index_to_int(index))\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
insert [cups_to_insert] to the right of target_idx | def add_cups(self, target_idx, cups_to_insert):
part_a = self.cups[0 : target_idx + 1]
part_b = self.cups[target_idx + 1 :]
print(f"cups: {self.cups} part_a[{part_a}], part_b[{part_b}]")
self.cups = part_a + cups_to_insert + part_b | [
"def insert_index(self):\n pass",
"def _insert_many(self, i, j, x):\n\n order = cupy.argsort(i) # stable for duplicates\n i = i.take(order)\n j = j.take(order)\n x = x.take(order)\n\n # Update index data type\n\n idx_dtype = _sputils.get_index_dtype(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make one move in the cup game.. The crab picks up the three cups that are immediately clockwise of the current cup. They are removed from the circle; cup spacing is adjusted as necessary to maintain the circle. | def play_one_move(self):
self.print("top of move")
# 1) grab three cups
c1 = self.take_cup_after(self.current_cup_idx())
c2 = self.take_cup_after(self.current_cup_idx())
c3 = self.take_cup_after(self.current_cup_idx())
print(f"pick up: {c1}, {c2}, {c3}")
self.prin... | [
"def cup():\n return Cup(2, 6)",
"def cercle(x,y,n):\r\n lt(90)\r\n up()\r\n goto(x,y)\r\n down()\r\n circle(n)",
"def moveCirc(self):\n\t\tfor circle in self.circles:\n\t\t\tcircle.moveStep()",
"def pick_up_cups(self, num: int) -> list:\n\n # \"The crab picks up the three cups that are im... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate random attitudes To generate a random quaternion a mapping in SO(3) is first created and then transformed as explained originally by [Shoemake]_ and summarized in [Kuffner]_. | def random_attitudes(n: int = 1, representation: str = 'quaternion') -> np.ndarray:
if not isinstance(n, int):
raise TypeError(f"n must be an integer. Got {type(n)}")
if n < 1:
raise ValueError(f"n must be greater than 0. Got {n}")
if not isinstance(representation, str):
raise TypeEr... | [
"def generate_random_rot():\n from pyso3.quaternion import quat2rot\n import numpy as np\n q = np.random.randn(4)\n q = q / np.linalg.norm(q)\n return quat2rot(q)",
"def random_quaternions(count=100):\n rands = np.random.rand(count,3)\n root_1 = np.sqrt(rands[:,0])\n minus_root_1 = np.sqrt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Third element of the vector part of the Quaternion. | def z(self) -> float:
return self.A[3] if self.scalar_vector else self.A[2] | [
"def vector3(self):\n return (Vector3(self[:3]), self[3])",
"def I3_u3(self) -> complex:\n return self.I3_u1() * cmath.rect(1, 120 / 180 * cmath.pi)",
"def x3(self):\n return self._x + self._x3",
"def rotation3DFromQuaternion(*args):\n return _almathswig.rotation3DFromQuaternion(*args)",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exponential of Quaternion The quaternion exponential works as in the ordinary case, defined with | def exponential(self) -> np.ndarray:
if self.is_real():
return np.array([1.0, 0.0, 0.0, 0.0])
t = np.linalg.norm(self.v)
u = self.v/t
q_exp = np.array([np.cos(t), *u*np.sin(t)])
if self.is_pure():
return q_exp
q_exp *= np.e**self.w
return q... | [
"def exp(cls, q):\n tolerance = 1e-17\n v_norm = np.linalg.norm(q.vector)\n vec = q.vector\n if v_norm > tolerance:\n vec = vec / v_norm\n magnitude = exp(q.scalar)\n return Quaternion(scalar = magnitude * cos(v_norm), vector = magnitude * sin(v_norm) * vec)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns array of quaternion to the power of ``a`` Assuming the quaternion is a versor, its power can be defined using the | def __pow__(self, a: float) -> np.ndarray:
return np.e**(a*self.logarithm) | [
"def signedpower(x: pd.Series, a) -> pd.Series:\n return x.pow(a)",
"def theta(self,a):\n p = SFAPower(self.parent().base_ring())\n p_self = p(self)\n res = p_self.map_item(lambda m,c: (m, c*a**len(m)))\n return self.parent()(res)",
"def _vlerchphi(self, z: np.ndarray, a: int) -> ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a bool value, where ``True`` if quaternion is pure. | def is_pure(self) -> bool:
return self.w==0.0 | [
"def quaternion_equal(v1=None, v2=None): # real signature unknown; restored from __doc__\n return 0",
"def is_pure(self) -> bool:\r\n return self.is_valid and np.all([x[\"operation\"].is_pure for x in self.operations_by_name.values()])",
"def test_check_quaternion():\n q_list = [1, 0, 0, 0]\n q ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a bool value, where ``True`` if quaternion is real. | def is_real(self) -> bool:
return not any(self.v) | [
"def is_real(self):\n return all([isinstance(dim, Real) for dim in self.dimensions])",
"def is_same_quaternion(q0, q1):\r\n q0 = numpy.array(q0)\r\n q1 = numpy.array(q1)\r\n return numpy.allclose(q0, q1) or numpy.allclose(q0, -q1)",
"def quaternion_equal(v1=None, v2=None): # real signature unkno... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a bool value, where ``True`` if quaternion is a versor. | def is_versor(self) -> bool:
return np.isclose(np.linalg.norm(self.A), 1.0) | [
"def isVersor(self) -> bool:\n\n Vhat = self.gradeInvol()\n Vrev = ~self\n Vinv = Vrev/(self*Vrev)[0]\n\n gpres = grades_present(Vhat*Vinv, 0.000001)\n if len(gpres) == 1:\n if gpres[0] == 0:\n if np.sum(np.abs((Vhat*Vinv).value - (Vinv*Vhat).value)) < 0.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a bool value, where ``True`` if quaternion is identity quaternion. An identity quaternion has its scalar part equal to 1, and its | def is_identity(self) -> bool:
return np.allclose(self.A, np.array([1.0, 0.0, 0.0, 0.0])) | [
"def is_identity(self) -> np.ndarray:\n if self.scalar_vector:\n return np.all(np.isclose(self.array, np.tile([1., 0., 0., 0.], (self.array.shape[0], 1))), axis=1)\n return np.all(np.isclose(self.array, np.tile([0., 0., 0., 1.], (self.array.shape[0], 1))), axis=1)",
"def identity() -> Qua... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Quaternion from given RPY angles. The quaternion can be constructed from the Aerospace cardanian angle | def from_rpy(self, angles: np.ndarray) -> np.ndarray:
_assert_iterables(angles, 'Roll-Pitch-Yaw angles')
angles = np.array(angles)
if angles.ndim != 1 or angles.shape[0] != 3:
raise ValueError(f"Expected `angles` must have shape (3,), got {angles.shape}.")
for angle in angles... | [
"def Quaternion_fromAngleAndAxisRotation(*args):\n return _almathswig.Quaternion_fromAngleAndAxisRotation(*args)",
"def angleAndAxisRotationFromQuaternion(*args):\n return _almathswig.angleAndAxisRotationFromQuaternion(*args)",
"def rotationFromQuaternion(*args):\n return _almathswig.rotationFromQuaternion(*... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array of boolean values, where a value is ``True`` if its corresponding quaternion is pure. | def is_pure(self) -> np.ndarray:
return np.isclose(self.w, np.zeros_like(self.w.shape[0])) | [
"def test_qual_to_bool():\n for _ in range(100):\n state = random.choice([-1,0,1])\n q = session4.Qualean(state)\n assert isinstance(q.__bool__(),bool), f'Qualean number to boolean conversion does not meet expectations'",
"def test_check_quaternion():\n q_list = [1, 0, 0, 0]\n q = pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array of boolean values, where a value is ``True`` if its corresponding quaternion is real. | def is_real(self) -> np.ndarray:
return np.all(np.isclose(self.v, np.zeros_like(self.v)), axis=1) | [
"def generate_boolean_vector(f,q,r,DIMS):\n b = None\n for i in range(DIMS):\n if b is None:\n b = (f[:,i]<q[i]+r[i]) & (f[:,i]>q[i])\n else :\n b = b & (f[:,i]<q[i]+r[i]) & (f[:,i]>q[i])\n return b",
"def test_qual_to_bool():\n for _ in range(100):\n state ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array of boolean values, where a value is ``True`` if its corresponding quaternion has a norm equal to one. A versor is a quaternion, whose `euclidean norm | def is_versor(self) -> np.ndarray:
return np.isclose(np.linalg.norm(self.array, axis=1), 1.0) | [
"def quat_normz(quat):\n quat = np.array(quat)\n norm = np.sum(quat[1:4]**2)\n if norm<1:\n quat[0] = np.sqrt(1-norm)\n else:\n quat /= np.sqrt(norm)\n quat[0] = 0\n return quat",
"def test_check_quaternions():\n Q_list = [[1, 0, 0, 0]]\n Q = pr.check_quaternions(Q_list)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array of boolean values, where a value is ``True`` if its quaternion is equal to the identity quaternion. An identity quaternion has its scalar part equal to 1, and its | def is_identity(self) -> np.ndarray:
if self.scalar_vector:
return np.all(np.isclose(self.array, np.tile([1., 0., 0., 0.], (self.array.shape[0], 1))), axis=1)
return np.all(np.isclose(self.array, np.tile([0., 0., 0., 1.], (self.array.shape[0], 1))), axis=1) | [
"def is_identity(self) -> bool:\n return np.allclose(self.A, np.array([1.0, 0.0, 0.0, 0.0]))",
"def identity() -> Quaternion:\n return Quaternion(1, np.array([0, 0, 0]))",
"def test_quaternion_rot_from_to_vec_identity(self):\n x = np.array([1, 0, 0])\n quat = Orientation.from_vecs(x,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Quaternion Array from given RPY angles. The quaternion can be constructed from the Aerospace cardanian angle | def from_rpy(self, Angles: np.ndarray) -> np.ndarray:
_assert_iterables(Angles, 'Roll-Pitch-Yaw angles')
Angles = np.copy(Angles)
if Angles.ndim != 2 or Angles.shape[-1] != 3:
raise ValueError(f"Expected `angles` must have shape (N, 3), got {Angles.shape}.")
# RPY to Quaterni... | [
"def from_rpy(self, angles: np.ndarray) -> np.ndarray:\n _assert_iterables(angles, 'Roll-Pitch-Yaw angles')\n angles = np.array(angles)\n if angles.ndim != 1 or angles.shape[0] != 3:\n raise ValueError(f\"Expected `angles` must have shape (3,), got {angles.shape}.\")\n for ang... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the angular velocity between N Quaternions. It assumes a constant sampling rate of ``dt`` seconds, and returns the angular velocity around the X, Y and Zaxis (rollpitchyaw angles), in radians per second. | def angular_velocities(self, dt: float) -> np.ndarray:
if not isinstance(dt, float):
raise TypeError(f"dt must be a float. Got {type(dt)}.")
if dt <= 0:
raise ValueError(f"dt must be greater than zero. Got {dt}.")
w = np.c_[
self.w[:-1]*self.x[1:] - self.x[:-1... | [
"def angular_velocities(prev, now, dt):\n patt = mathutils.Vector(prev.euler)\n att = mathutils.Vector(now.euler)\n euler_rate = (att - patt) /dt\n\n c0 = cos(att[0])\n c1 = cos(att[1])\n s0 = sin(att[0])\n s1 = sin(att[1])\n\n m = mathutils.Matrix(([1, 0, -s1],\n [0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visualize a quantiative measurement on a label image by replacing the label IDs with specified table colum values. | def visualize_measurement_on_labels(labels_layer:"napari.layers.Labels", column:str = "label", viewer:"napari.Viewer" = None) -> "napari.types.ImageData":
import pandas as pd
import dask.array as da
from dask import delayed
from functools import partial
from napari.utils import notifications
if ... | [
"def printtablelabels(self, rows, cols, which, info):\r\n if self.printlabels:\r\n info.addrow(_(\"Table Labels: %s. Dimensions: %s, %s\") % (which, rows, cols))\r\n for i in range(rows):\r\n for j in range(cols):\r\n info.addrow(\"%d %d: %s\" % (i, j,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produce parametric map image from a label image, a list of labels and a list of measurements. The two lists must provide labels and corresponding values in the same order. See also | def relabel_with_map_array(image, label_list, measurement_list):
from skimage.util import map_array
return map_array(np.asarray(image), np.asarray(label_list), np.array(measurement_list)) | [
"def prep_image_data(arg_dict):\n cat_df = pd.read_csv(arg_dict['category_file'],\n skiprows=1,\n sep='\\s+')\n bbox_df = pd.read_csv(arg_dict['bbox_file'],\n skiprows=1,\n sep='\\s+')\n img_dir = arg_dict['im... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |